merge: 合并 dev 并解决 PR 冲突
This commit is contained in:
@@ -81,6 +81,16 @@ test('isRecoverableStep9AuthFailure matches timeout and CPA auth failure statuse
|
||||
true
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
isRecoverableStep9AuthFailure('提交回调失败:请更新CLI Proxy API或检查连接'),
|
||||
true
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
isRecoverableStep9AuthFailure('认证失败:Bad Request'),
|
||||
true
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
isRecoverableStep9AuthFailure('认证成功!'),
|
||||
false
|
||||
|
||||
@@ -18,11 +18,11 @@ function createRetryButton() {
|
||||
function createRecoveryApi(state) {
|
||||
const retryButton = createRetryButton();
|
||||
global.location = {
|
||||
pathname: '/log-in',
|
||||
href: 'https://auth.openai.com/log-in',
|
||||
pathname: state.pathname || '/log-in',
|
||||
href: state.href || `https://auth.openai.com${state.pathname || '/log-in'}`,
|
||||
};
|
||||
global.document = {
|
||||
title: 'Something went wrong',
|
||||
title: state.title ?? 'Something went wrong',
|
||||
querySelector(selector) {
|
||||
if (selector === 'button[data-dd-action-name="Try again"]' && state.retryVisible) {
|
||||
return retryButton;
|
||||
@@ -42,6 +42,7 @@ function createRecoveryApi(state) {
|
||||
isActionEnabled: (element) => Boolean(element) && !element.disabled && element.getAttribute('aria-disabled') !== 'true',
|
||||
isVisibleElement: () => true,
|
||||
log: () => {},
|
||||
routeErrorPattern: /405\s+method\s+not\s+allowed|route\s+error.*405/i,
|
||||
simulateClick: () => {
|
||||
state.clickCount += 1;
|
||||
if (typeof state.onClick === 'function') {
|
||||
@@ -78,9 +79,30 @@ test('auth page recovery detects retry page state', () => {
|
||||
assert.equal(snapshot.retryEnabled, true);
|
||||
assert.equal(snapshot.titleMatched, true);
|
||||
assert.equal(snapshot.detailMatched, false);
|
||||
assert.equal(snapshot.routeErrorMatched, false);
|
||||
assert.equal(snapshot.maxCheckAttemptsBlocked, false);
|
||||
});
|
||||
|
||||
test('auth page recovery detects route error retry page on email verification route', () => {
|
||||
const state = {
|
||||
clickCount: 0,
|
||||
pageText: 'Route Error (405 Method Not Allowed): email-verification action missing.',
|
||||
pathname: '/email-verification',
|
||||
retryVisible: true,
|
||||
title: '',
|
||||
};
|
||||
const api = createRecoveryApi(state);
|
||||
|
||||
const snapshot = api.getAuthTimeoutErrorPageState({
|
||||
pathPatterns: [/\/email-verification(?:[/?#]|$)/i],
|
||||
});
|
||||
|
||||
assert.equal(Boolean(snapshot), true);
|
||||
assert.equal(snapshot.titleMatched, false);
|
||||
assert.equal(snapshot.detailMatched, false);
|
||||
assert.equal(snapshot.routeErrorMatched, true);
|
||||
});
|
||||
|
||||
test('auth page recovery clicks retry and waits until page recovers', async () => {
|
||||
const state = {
|
||||
clickCount: 0,
|
||||
@@ -182,3 +204,25 @@ test('auth page recovery throws cloudflare security blocked error on max_check_a
|
||||
);
|
||||
});
|
||||
|
||||
test('auth page recovery throws signup user already exists error without clicking retry', async () => {
|
||||
const state = {
|
||||
clickCount: 0,
|
||||
pageText: 'Something went wrong. user_already_exists.',
|
||||
pathname: '/email-verification',
|
||||
retryVisible: true,
|
||||
};
|
||||
const api = createRecoveryApi(state);
|
||||
|
||||
await assert.rejects(
|
||||
() => api.recoverAuthRetryPage({
|
||||
logLabel: '步骤 4:检测到注册认证重试页,正在点击“重试”恢复',
|
||||
pathPatterns: [/\/email-verification(?:[/?#]|$)/i],
|
||||
step: 4,
|
||||
timeoutMs: 1000,
|
||||
}),
|
||||
/SIGNUP_USER_ALREADY_EXISTS::/
|
||||
);
|
||||
|
||||
assert.equal(state.clickCount, 0);
|
||||
});
|
||||
|
||||
|
||||
@@ -168,3 +168,166 @@ test('auto-run controller skips add-phone failures to the next round instead of
|
||||
assert.equal(runtime.state.autoRunActive, false);
|
||||
assert.equal(runtime.state.autoRunSessionId, 0);
|
||||
});
|
||||
|
||||
test('auto-run controller skips user_already_exists failures to the next round instead of retrying the same round', async () => {
|
||||
const events = {
|
||||
logs: [],
|
||||
broadcasts: [],
|
||||
accountRecords: [],
|
||||
runCalls: 0,
|
||||
};
|
||||
|
||||
let currentState = {
|
||||
stepStatuses: {},
|
||||
vpsUrl: 'https://example.com/vps',
|
||||
vpsPassword: 'secret',
|
||||
customPassword: '',
|
||||
autoRunSkipFailures: true,
|
||||
autoRunFallbackThreadIntervalMinutes: 0,
|
||||
autoRunDelayEnabled: false,
|
||||
autoRunDelayMinutes: 30,
|
||||
autoStepDelaySeconds: null,
|
||||
mailProvider: '163',
|
||||
emailGenerator: 'duck',
|
||||
gmailBaseEmail: '',
|
||||
mail2925BaseEmail: '',
|
||||
emailPrefix: 'demo',
|
||||
inbucketHost: '',
|
||||
inbucketMailbox: '',
|
||||
cloudflareDomain: '',
|
||||
cloudflareDomains: [],
|
||||
tabRegistry: {},
|
||||
sourceLastUrls: {},
|
||||
autoRunRoundSummaries: [],
|
||||
};
|
||||
|
||||
const runtime = {
|
||||
state: {
|
||||
autoRunActive: false,
|
||||
autoRunCurrentRun: 0,
|
||||
autoRunTotalRuns: 1,
|
||||
autoRunAttemptRun: 0,
|
||||
autoRunSessionId: 0,
|
||||
},
|
||||
get() {
|
||||
return { ...this.state };
|
||||
},
|
||||
set(updates = {}) {
|
||||
this.state = { ...this.state, ...updates };
|
||||
},
|
||||
};
|
||||
|
||||
let sessionSeed = 0;
|
||||
|
||||
const controller = api.createAutoRunController({
|
||||
addLog: async (message, level = 'info') => {
|
||||
events.logs.push({ message, level });
|
||||
},
|
||||
appendAccountRunRecord: async (status, _state, reason) => {
|
||||
events.accountRecords.push({ status, reason });
|
||||
return { status, reason };
|
||||
},
|
||||
AUTO_RUN_MAX_RETRIES_PER_ROUND: 3,
|
||||
AUTO_RUN_RETRY_DELAY_MS: 3000,
|
||||
AUTO_RUN_TIMER_KIND_BEFORE_RETRY: 'before_retry',
|
||||
AUTO_RUN_TIMER_KIND_BETWEEN_ROUNDS: 'between_rounds',
|
||||
broadcastAutoRunStatus: async (phase, payload = {}) => {
|
||||
events.broadcasts.push({ phase, ...payload });
|
||||
currentState = {
|
||||
...currentState,
|
||||
autoRunning: ['scheduled', 'running', 'waiting_step', 'waiting_email', 'retrying', 'waiting_interval'].includes(phase),
|
||||
autoRunPhase: phase,
|
||||
autoRunCurrentRun: payload.currentRun ?? runtime.state.autoRunCurrentRun,
|
||||
autoRunTotalRuns: payload.totalRuns ?? runtime.state.autoRunTotalRuns,
|
||||
autoRunAttemptRun: payload.attemptRun ?? runtime.state.autoRunAttemptRun,
|
||||
autoRunSessionId: payload.sessionId ?? runtime.state.autoRunSessionId,
|
||||
};
|
||||
},
|
||||
broadcastStopToContentScripts: async () => {},
|
||||
cancelPendingCommands: () => {},
|
||||
clearStopRequest: () => {},
|
||||
createAutoRunSessionId: () => {
|
||||
sessionSeed += 1;
|
||||
return sessionSeed;
|
||||
},
|
||||
getAutoRunStatusPayload: (phase, payload = {}) => ({
|
||||
autoRunning: ['scheduled', 'running', 'waiting_step', 'waiting_email', 'retrying', 'waiting_interval'].includes(phase),
|
||||
autoRunPhase: phase,
|
||||
autoRunCurrentRun: payload.currentRun ?? 0,
|
||||
autoRunTotalRuns: payload.totalRuns ?? 1,
|
||||
autoRunAttemptRun: payload.attemptRun ?? 0,
|
||||
autoRunSessionId: payload.sessionId ?? 0,
|
||||
}),
|
||||
getErrorMessage: (error) => error?.message || String(error || ''),
|
||||
getFirstUnfinishedStep: () => 1,
|
||||
getPendingAutoRunTimerPlan: () => null,
|
||||
getRunningSteps: () => [],
|
||||
getState: async () => ({
|
||||
...currentState,
|
||||
stepStatuses: { ...(currentState.stepStatuses || {}) },
|
||||
tabRegistry: { ...(currentState.tabRegistry || {}) },
|
||||
sourceLastUrls: { ...(currentState.sourceLastUrls || {}) },
|
||||
}),
|
||||
getStopRequested: () => false,
|
||||
hasSavedProgress: () => false,
|
||||
isAddPhoneAuthFailure: () => false,
|
||||
isRestartCurrentAttemptError: () => false,
|
||||
isSignupUserAlreadyExistsFailure: (error) => /SIGNUP_USER_ALREADY_EXISTS::|user_already_exists/i.test(error?.message || String(error || '')),
|
||||
isStopError: (error) => (error?.message || String(error || '')) === '流程已被用户停止。',
|
||||
launchAutoRunTimerPlan: async () => false,
|
||||
normalizeAutoRunFallbackThreadIntervalMinutes: (value) => Math.max(0, Math.floor(Number(value) || 0)),
|
||||
persistAutoRunTimerPlan: async () => ({}),
|
||||
resetState: async () => {
|
||||
currentState = {
|
||||
...currentState,
|
||||
stepStatuses: {},
|
||||
tabRegistry: {},
|
||||
sourceLastUrls: {},
|
||||
};
|
||||
},
|
||||
runAutoSequenceFromStep: async () => {
|
||||
events.runCalls += 1;
|
||||
if (events.runCalls === 1) {
|
||||
throw new Error('SIGNUP_USER_ALREADY_EXISTS::步骤 4:检测到 user_already_exists,说明当前用户已存在,当前轮将直接停止。');
|
||||
}
|
||||
},
|
||||
runtime,
|
||||
setState: async (updates = {}) => {
|
||||
currentState = {
|
||||
...currentState,
|
||||
...updates,
|
||||
stepStatuses: updates.stepStatuses ? { ...updates.stepStatuses } : currentState.stepStatuses,
|
||||
tabRegistry: updates.tabRegistry ? { ...updates.tabRegistry } : currentState.tabRegistry,
|
||||
sourceLastUrls: updates.sourceLastUrls ? { ...updates.sourceLastUrls } : currentState.sourceLastUrls,
|
||||
};
|
||||
},
|
||||
sleepWithStop: async () => {},
|
||||
throwIfAutoRunSessionStopped: (sessionId) => {
|
||||
if (sessionId && sessionId !== runtime.state.autoRunSessionId) {
|
||||
throw new Error('流程已被用户停止。');
|
||||
}
|
||||
},
|
||||
waitForRunningStepsToFinish: async () => currentState,
|
||||
chrome: {
|
||||
runtime: {
|
||||
sendMessage() {
|
||||
return Promise.resolve();
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await controller.autoRunLoop(2, {
|
||||
autoRunSkipFailures: true,
|
||||
mode: 'restart',
|
||||
});
|
||||
|
||||
assert.equal(events.runCalls, 2, 'user_already_exists failure should skip the current round and continue with the next round');
|
||||
assert.equal(events.broadcasts.some(({ phase }) => phase === 'retrying'), false, 'user_already_exists failure should not enter same-round retrying');
|
||||
assert.equal(events.accountRecords.length, 1, 'user_already_exists should still persist a failed round record');
|
||||
assert.equal(events.accountRecords[0].status, 'failed');
|
||||
assert.match(events.accountRecords[0].reason, /SIGNUP_USER_ALREADY_EXISTS::/);
|
||||
assert.ok(events.logs.some(({ message }) => /继续下一轮/.test(message)));
|
||||
assert.equal(runtime.state.autoRunActive, false);
|
||||
assert.equal(runtime.state.autoRunSessionId, 0);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
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);
|
||||
}
|
||||
|
||||
const bundle = [
|
||||
extractFunction('isAddPhoneAuthUrl'),
|
||||
extractFunction('isAddPhoneAuthState'),
|
||||
extractFunction('isMail2925ThreadTerminatedError'),
|
||||
extractFunction('isSignupUserAlreadyExistsFailure'),
|
||||
extractFunction('getPostStep6AutoRestartDecision'),
|
||||
extractFunction('runAutoSequenceFromStep'),
|
||||
].join('\n');
|
||||
|
||||
test('auto-run stops step4 restart path when mail2925 ends the current thread', async () => {
|
||||
const api = new Function(`
|
||||
const AUTO_STEP_DELAYS = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0 };
|
||||
const LAST_STEP_ID = 10;
|
||||
const FINAL_OAUTH_CHAIN_START_STEP = 7;
|
||||
const chrome = {
|
||||
tabs: {
|
||||
update: async () => {},
|
||||
},
|
||||
runtime: {
|
||||
sendMessage: async () => {},
|
||||
},
|
||||
};
|
||||
|
||||
let currentState = {
|
||||
email: 'demo123456@2925.com',
|
||||
password: 'Secret123!',
|
||||
mailProvider: '2925',
|
||||
stepStatuses: {
|
||||
1: 'pending',
|
||||
2: 'pending',
|
||||
3: 'pending',
|
||||
4: 'pending',
|
||||
5: 'pending',
|
||||
6: 'pending',
|
||||
7: 'pending',
|
||||
8: 'pending',
|
||||
9: 'pending',
|
||||
10: 'pending',
|
||||
},
|
||||
};
|
||||
const events = {
|
||||
steps: [],
|
||||
invalidations: [],
|
||||
logs: [],
|
||||
};
|
||||
|
||||
async function addLog(message, level = 'info') {
|
||||
events.logs.push({ message, level });
|
||||
}
|
||||
|
||||
async function ensureAutoEmailReady() {
|
||||
return currentState.email;
|
||||
}
|
||||
|
||||
async function broadcastAutoRunStatus() {}
|
||||
|
||||
async function getState() {
|
||||
return currentState;
|
||||
}
|
||||
|
||||
async function setState(updates) {
|
||||
currentState = {
|
||||
...currentState,
|
||||
...updates,
|
||||
stepStatuses: updates.stepStatuses ? { ...updates.stepStatuses } : currentState.stepStatuses,
|
||||
};
|
||||
}
|
||||
|
||||
function isStopError(error) {
|
||||
return false;
|
||||
}
|
||||
|
||||
function isStepDoneStatus(status) {
|
||||
return status === 'completed' || status === 'manual_completed' || status === 'skipped';
|
||||
}
|
||||
|
||||
async function executeStepAndWait(step) {
|
||||
events.steps.push(step);
|
||||
if (step === 4) {
|
||||
throw new Error('MAIL2925_THREAD_TERMINATED::步骤 4:2925 已切换账号并要求结束当前尝试。');
|
||||
}
|
||||
}
|
||||
|
||||
async function getTabId() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
async function invalidateDownstreamAfterStepRestart(step, options = {}) {
|
||||
events.invalidations.push({ step, options });
|
||||
}
|
||||
|
||||
function getLoginAuthStateLabel(state) {
|
||||
return state || 'unknown';
|
||||
}
|
||||
|
||||
function getErrorMessage(error) {
|
||||
return error?.message || String(error || '');
|
||||
}
|
||||
|
||||
async function getLoginAuthStateFromContent() {
|
||||
return { state: 'password_page', url: 'https://auth.openai.com/log-in' };
|
||||
}
|
||||
|
||||
${bundle}
|
||||
|
||||
return {
|
||||
async run() {
|
||||
try {
|
||||
await runAutoSequenceFromStep(1, {
|
||||
targetRun: 1,
|
||||
totalRuns: 1,
|
||||
attemptRuns: 1,
|
||||
continued: false,
|
||||
});
|
||||
return { events, currentState, error: null };
|
||||
} catch (error) {
|
||||
return { events, currentState, error: error.message };
|
||||
}
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
const result = await api.run();
|
||||
|
||||
assert.match(result.error, /^MAIL2925_THREAD_TERMINATED::/);
|
||||
assert.deepStrictEqual(result.events.invalidations, []);
|
||||
assert.deepStrictEqual(result.events.steps, [1, 2, 3, 4]);
|
||||
assert.equal(result.events.logs.some(({ message }) => /回到步骤 1/.test(message)), false);
|
||||
});
|
||||
@@ -55,6 +55,8 @@ function extractFunction(name) {
|
||||
const bundle = [
|
||||
extractFunction('isAddPhoneAuthUrl'),
|
||||
extractFunction('isAddPhoneAuthState'),
|
||||
extractFunction('isMail2925ThreadTerminatedError'),
|
||||
extractFunction('isSignupUserAlreadyExistsFailure'),
|
||||
extractFunction('getPostStep6AutoRestartDecision'),
|
||||
extractFunction('runAutoSequenceFromStep'),
|
||||
].join('\n');
|
||||
@@ -207,3 +209,124 @@ return {
|
||||
assert.equal(currentState.password, 'Secret123!');
|
||||
assert.equal(events.logs.some(({ message }) => /沿用当前邮箱回到步骤 1 重新开始/.test(message)), true);
|
||||
});
|
||||
|
||||
test('auto-run does not restart step 4 current attempt when user_already_exists is detected', async () => {
|
||||
const api = new Function(`
|
||||
const AUTO_STEP_DELAYS = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0 };
|
||||
const LAST_STEP_ID = 10;
|
||||
const FINAL_OAUTH_CHAIN_START_STEP = 7;
|
||||
const chrome = {
|
||||
tabs: {
|
||||
update: async () => {},
|
||||
},
|
||||
runtime: {
|
||||
sendMessage: async () => {},
|
||||
},
|
||||
};
|
||||
|
||||
let currentState = {
|
||||
email: 'existing@example.com',
|
||||
password: 'Secret123!',
|
||||
mailProvider: '163',
|
||||
stepStatuses: {
|
||||
1: 'pending',
|
||||
2: 'pending',
|
||||
3: 'pending',
|
||||
4: 'pending',
|
||||
5: 'pending',
|
||||
6: 'pending',
|
||||
7: 'pending',
|
||||
8: 'pending',
|
||||
9: 'pending',
|
||||
10: 'pending',
|
||||
},
|
||||
};
|
||||
const events = {
|
||||
steps: [],
|
||||
invalidations: [],
|
||||
logs: [],
|
||||
};
|
||||
|
||||
async function addLog(message, level = 'info') {
|
||||
events.logs.push({ message, level });
|
||||
}
|
||||
|
||||
async function ensureAutoEmailReady() {
|
||||
return currentState.email;
|
||||
}
|
||||
|
||||
async function broadcastAutoRunStatus() {}
|
||||
|
||||
async function getState() {
|
||||
return currentState;
|
||||
}
|
||||
|
||||
async function setState(updates) {
|
||||
currentState = {
|
||||
...currentState,
|
||||
...updates,
|
||||
stepStatuses: updates.stepStatuses ? { ...updates.stepStatuses } : currentState.stepStatuses,
|
||||
};
|
||||
}
|
||||
|
||||
function isStopError(error) {
|
||||
return (error?.message || String(error || '')) === '流程已被用户停止。';
|
||||
}
|
||||
|
||||
function isStepDoneStatus(status) {
|
||||
return status === 'completed' || status === 'manual_completed' || status === 'skipped';
|
||||
}
|
||||
|
||||
async function executeStepAndWait(step) {
|
||||
events.steps.push(step);
|
||||
if (step === 4) {
|
||||
throw new Error('SIGNUP_USER_ALREADY_EXISTS::步骤 4:检测到 user_already_exists,说明当前用户已存在,当前轮将直接停止。');
|
||||
}
|
||||
}
|
||||
|
||||
async function getTabId() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
async function invalidateDownstreamAfterStepRestart(step, options = {}) {
|
||||
events.invalidations.push({ step, options });
|
||||
}
|
||||
|
||||
function getLoginAuthStateLabel(state) {
|
||||
return state || 'unknown';
|
||||
}
|
||||
|
||||
function getErrorMessage(error) {
|
||||
return error?.message || String(error || '');
|
||||
}
|
||||
|
||||
async function getLoginAuthStateFromContent() {
|
||||
return { state: 'password_page', url: 'https://auth.openai.com/log-in' };
|
||||
}
|
||||
|
||||
${bundle}
|
||||
|
||||
return {
|
||||
async run() {
|
||||
try {
|
||||
await runAutoSequenceFromStep(1, {
|
||||
targetRun: 1,
|
||||
totalRuns: 1,
|
||||
attemptRuns: 1,
|
||||
continued: false,
|
||||
});
|
||||
return { events, currentState, error: null };
|
||||
} catch (error) {
|
||||
return { events, currentState, error: error.message };
|
||||
}
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
const result = await api.run();
|
||||
|
||||
assert.match(result.error, /SIGNUP_USER_ALREADY_EXISTS::/);
|
||||
assert.deepStrictEqual(result.events.invalidations, []);
|
||||
assert.deepStrictEqual(result.events.steps, [1, 2, 3, 4]);
|
||||
assert.equal(result.events.logs.some(({ message }) => /沿用当前邮箱回到步骤 1 重新开始/.test(message)), false);
|
||||
});
|
||||
|
||||
@@ -50,6 +50,7 @@ function extractFunction(name) {
|
||||
|
||||
test('background account history settings are normalized independently from hotmail service mode', () => {
|
||||
const bundle = [
|
||||
extractFunction('normalizeCodex2ApiUrl'),
|
||||
extractFunction('normalizeHotmailLocalBaseUrl'),
|
||||
extractFunction('normalizeAccountRunHistoryHelperBaseUrl'),
|
||||
extractFunction('normalizeVerificationResendCount'),
|
||||
@@ -60,6 +61,7 @@ test('background account history settings are normalized independently from hotm
|
||||
const DEFAULT_HOTMAIL_LOCAL_BASE_URL = 'http://127.0.0.1:17373';
|
||||
const DEFAULT_ACCOUNT_RUN_HISTORY_HELPER_BASE_URL = DEFAULT_HOTMAIL_LOCAL_BASE_URL;
|
||||
const DEFAULT_HOTMAIL_REMOTE_BASE_URL = '';
|
||||
const DEFAULT_CODEX2API_URL = 'http://localhost:8080/admin/accounts';
|
||||
const DEFAULT_VERIFICATION_RESEND_COUNT = 4;
|
||||
const DEFAULT_SUB2API_PROXY_NAME = '';
|
||||
const HOTMAIL_SERVICE_MODE_REMOTE = 'remote';
|
||||
@@ -70,7 +72,7 @@ const PERSISTED_SETTING_DEFAULTS = {
|
||||
autoStepDelaySeconds: null,
|
||||
mailProvider: '163',
|
||||
};
|
||||
function normalizePanelMode(value) { return value === 'sub2api' ? 'sub2api' : 'cpa'; }
|
||||
function normalizePanelMode(value) { return value === 'sub2api' ? 'sub2api' : (value === 'codex2api' ? 'codex2api' : 'cpa'); }
|
||||
function normalizeLocalCpaStep9Mode(value) { return value === 'bypass' ? 'bypass' : 'submit'; }
|
||||
function normalizeAutoRunFallbackThreadIntervalMinutes(value) { return Number(value) || 0; }
|
||||
function normalizeAutoRunDelayMinutes(value) { return Number(value) || 30; }
|
||||
@@ -118,4 +120,16 @@ return {
|
||||
api.normalizePersistentSettingValue('sub2apiDefaultProxyName', ' proxy-a '),
|
||||
'proxy-a'
|
||||
);
|
||||
assert.equal(
|
||||
api.normalizePersistentSettingValue('codex2apiUrl', 'localhost:8080/admin'),
|
||||
'http://localhost:8080/admin/accounts'
|
||||
);
|
||||
assert.equal(
|
||||
api.normalizePersistentSettingValue('codex2apiUrl', 'https://codex-admin.example.com/'),
|
||||
'https://codex-admin.example.com/admin/accounts'
|
||||
);
|
||||
assert.equal(
|
||||
api.normalizePersistentSettingValue('codex2apiAdminKey', ' secret-key '),
|
||||
'secret-key'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -100,18 +100,42 @@ test('account run history helper upgrades old records, keeps stopped items and s
|
||||
assert.equal(fetchCalled, false);
|
||||
assert.equal(helpers.shouldAppendAccountRunTextFile({ accountRunHistoryTextEnabled: false, accountRunHistoryHelperBaseUrl: 'http://127.0.0.1:17373' }), false);
|
||||
assert.equal(helpers.shouldAppendAccountRunTextFile({ accountRunHistoryTextEnabled: true, accountRunHistoryHelperBaseUrl: 'http://127.0.0.1:17373' }), true);
|
||||
const stoppedRecord = helpers.buildAccountRunHistoryRecord({ email: 'a@b.com', password: 'x' }, 'stopped', 'stop');
|
||||
const stoppedRecord = helpers.buildAccountRunHistoryRecord(
|
||||
{ email: 'a@b.com', password: 'x' },
|
||||
'step7_stopped',
|
||||
'步骤 7 已被用户停止'
|
||||
);
|
||||
assert.equal(stoppedRecord.recordId, 'a@b.com');
|
||||
assert.equal(stoppedRecord.email, 'a@b.com');
|
||||
assert.equal(stoppedRecord.password, 'x');
|
||||
assert.equal(stoppedRecord.finalStatus, 'stopped');
|
||||
assert.equal(stoppedRecord.retryCount, 0);
|
||||
assert.equal(stoppedRecord.failureLabel, '流程已停止');
|
||||
assert.equal(stoppedRecord.failureDetail, 'stop');
|
||||
assert.equal(stoppedRecord.failedStep, null);
|
||||
assert.equal(stoppedRecord.failureLabel, '步骤 7 停止');
|
||||
assert.equal(stoppedRecord.failureDetail, '步骤 7 已被用户停止');
|
||||
assert.equal(stoppedRecord.failedStep, 7);
|
||||
assert.equal(stoppedRecord.source, 'manual');
|
||||
assert.equal(stoppedRecord.autoRunContext, null);
|
||||
assert.ok(stoppedRecord.finishedAt);
|
||||
|
||||
const genericStoppedRecord = helpers.buildAccountRunHistoryRecord({ email: 'stop@b.com', password: 'y' }, 'stopped', 'stop');
|
||||
assert.equal(genericStoppedRecord.failureLabel, '流程已停止');
|
||||
assert.equal(genericStoppedRecord.failedStep, null);
|
||||
|
||||
const normalizedStoppedRecord = helpers.normalizeAccountRunHistoryRecord({
|
||||
recordId: 'legacy-stop@example.com',
|
||||
email: 'legacy-stop@example.com',
|
||||
password: 'secret',
|
||||
finalStatus: 'stopped',
|
||||
finishedAt: '2026-04-17T00:12:00.000Z',
|
||||
retryCount: 0,
|
||||
failureLabel: '流程已停止',
|
||||
failureDetail: '步骤 7 已被用户停止。',
|
||||
failedStep: 7,
|
||||
source: 'manual',
|
||||
autoRunContext: null,
|
||||
});
|
||||
assert.equal(normalizedStoppedRecord.failureLabel, '步骤 7 停止');
|
||||
assert.equal(normalizedStoppedRecord.failedStep, 7);
|
||||
});
|
||||
|
||||
test('account run history helper clears persisted records and syncs full snapshot payload to local helper', async () => {
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
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 BROWSER_SWITCH_REQUIRED_ERROR_PREFIX = 'BROWSER_SWITCH_REQUIRED::';
|
||||
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 isBrowserSwitchRequiredError() {
|
||||
return false;
|
||||
}
|
||||
async function handleBrowserSwitchRequired() {}
|
||||
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('executeStep stops flow when browser-switch-required error is raised', async () => {
|
||||
const api = new Function(`
|
||||
const LOG_PREFIX = '[test]';
|
||||
const STOP_ERROR_MESSAGE = '流程已被用户停止。';
|
||||
const BROWSER_SWITCH_REQUIRED_ERROR_PREFIX = 'BROWSER_SWITCH_REQUIRED::';
|
||||
const AUTH_CHAIN_STEP_IDS = new Set([7, 8, 9, 10]);
|
||||
let activeTopLevelAuthChainExecution = null;
|
||||
let stopRequested = false;
|
||||
const events = {
|
||||
logs: [],
|
||||
statusCalls: [],
|
||||
stopRequests: [],
|
||||
appendRecords: [],
|
||||
};
|
||||
|
||||
async function addLog(message, level = 'info') {
|
||||
events.logs.push({ message, level });
|
||||
}
|
||||
async function setStepStatus(step, status) {
|
||||
events.statusCalls.push({ step, status });
|
||||
}
|
||||
async function humanStepDelay() {}
|
||||
async function getState() {
|
||||
return {
|
||||
flowStartTime: null,
|
||||
stepStatuses: {},
|
||||
};
|
||||
}
|
||||
function getErrorMessage(error) {
|
||||
return error?.message || String(error || '');
|
||||
}
|
||||
async function appendManualAccountRunRecordIfNeeded(status, _state, reason) {
|
||||
events.appendRecords.push({ status, reason });
|
||||
}
|
||||
function isTerminalSecurityBlockedError() {
|
||||
return false;
|
||||
}
|
||||
async function handleCloudflareSecurityBlocked() {}
|
||||
async function requestStop(options = {}) {
|
||||
events.stopRequests.push(options);
|
||||
}
|
||||
function doesStepUseCompletionSignal() {
|
||||
return false;
|
||||
}
|
||||
function isRetryableContentScriptTransportError() {
|
||||
return false;
|
||||
}
|
||||
const stepRegistry = {
|
||||
async executeStep() {
|
||||
throw new Error('BROWSER_SWITCH_REQUIRED::请更换浏览器进行注册登录。');
|
||||
},
|
||||
};
|
||||
|
||||
${extractFunction('isStopError')}
|
||||
${extractFunction('throwIfStopped')}
|
||||
${extractFunction('isAuthChainStep')}
|
||||
${extractFunction('acquireTopLevelAuthChainExecution')}
|
||||
${extractFunction('isBrowserSwitchRequiredError')}
|
||||
${extractFunction('getBrowserSwitchRequiredMessage')}
|
||||
${extractFunction('handleBrowserSwitchRequired')}
|
||||
${extractFunction('executeStep')}
|
||||
|
||||
return {
|
||||
executeStep,
|
||||
snapshot() {
|
||||
return events;
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
await assert.rejects(
|
||||
() => api.executeStep(10),
|
||||
/流程已被用户停止。/
|
||||
);
|
||||
|
||||
const events = api.snapshot();
|
||||
assert.deepStrictEqual(events.stopRequests, [
|
||||
{ logMessage: '请更换浏览器进行注册登录。' },
|
||||
]);
|
||||
assert.deepStrictEqual(events.statusCalls, [
|
||||
{ step: 10, status: 'running' },
|
||||
]);
|
||||
assert.equal(
|
||||
events.logs.some(({ message }) => /步骤 10 失败/.test(message)),
|
||||
false,
|
||||
'browser-switch-required error should stop the flow before generic failed logging'
|
||||
);
|
||||
});
|
||||
|
||||
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 = 5 * 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);
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
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('cloudflare temp email settings normalize and expose the random-subdomain toggle', () => {
|
||||
const bundle = [
|
||||
extractFunction('normalizeCloudflareTempEmailReceiveMailbox'),
|
||||
extractFunction('getCloudflareTempEmailConfig'),
|
||||
extractFunction('normalizePersistentSettingValue'),
|
||||
extractFunction('buildPersistentSettingsPayload'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
const DEFAULT_VERIFICATION_RESEND_COUNT = 4;
|
||||
const PERSISTED_SETTING_DEFAULTS = {
|
||||
panelMode: 'cpa',
|
||||
autoStepDelaySeconds: null,
|
||||
verificationResendCount: DEFAULT_VERIFICATION_RESEND_COUNT,
|
||||
mailProvider: '163',
|
||||
mail2925Mode: 'provide',
|
||||
emailGenerator: 'duck',
|
||||
autoDeleteUsedIcloudAlias: false,
|
||||
accountRunHistoryTextEnabled: false,
|
||||
cloudflareTempEmailUseRandomSubdomain: false,
|
||||
cloudflareTempEmailDomain: '',
|
||||
cloudflareTempEmailDomains: [],
|
||||
};
|
||||
const PERSISTED_SETTING_KEYS = Object.keys(PERSISTED_SETTING_DEFAULTS);
|
||||
function normalizePanelMode(value) { return value === 'sub2api' ? 'sub2api' : 'cpa'; }
|
||||
function normalizeLocalCpaStep9Mode(value) { return value === 'bypass' ? 'bypass' : 'submit'; }
|
||||
function normalizeAutoRunFallbackThreadIntervalMinutes(value) { return Number(value) || 0; }
|
||||
function normalizeAutoRunDelayMinutes(value) { return Number(value) || 30; }
|
||||
function normalizeAutoStepDelaySeconds(value, fallback = null) { return value == null || value === '' ? fallback : Number(value); }
|
||||
function normalizeVerificationResendCount(value, fallback) { return Number.isFinite(Number(value)) ? Number(value) : fallback; }
|
||||
function normalizeMailProvider(value) { return String(value || '').trim().toLowerCase() || '163'; }
|
||||
function normalizeMail2925Mode(value) { return String(value || '').trim().toLowerCase() === 'receive' ? 'receive' : 'provide'; }
|
||||
function normalizeEmailGenerator(value) { return String(value || '').trim().toLowerCase() || 'duck'; }
|
||||
function normalizeIcloudHost(value) { const normalized = String(value || '').trim().toLowerCase(); return normalized === 'icloud.com' || normalized === 'icloud.com.cn' ? normalized : ''; }
|
||||
function normalizeAccountRunHistoryHelperBaseUrl(value) { return String(value || '').trim(); }
|
||||
function normalizeHotmailServiceMode(value) { return String(value || '').trim().toLowerCase() === 'remote' ? 'remote' : 'local'; }
|
||||
function normalizeHotmailRemoteBaseUrl(value) { return String(value || '').trim(); }
|
||||
function normalizeHotmailLocalBaseUrl(value) { return String(value || '').trim(); }
|
||||
function normalizeCloudflareDomain(value) { return String(value || '').trim().toLowerCase(); }
|
||||
function normalizeCloudflareDomains(value) { return Array.isArray(value) ? value.map((item) => String(item || '').trim().toLowerCase()).filter(Boolean) : []; }
|
||||
function normalizeCloudflareTempEmailBaseUrl(value) { return String(value || '').trim(); }
|
||||
function normalizeCloudflareTempEmailAddress(value = '') { return String(value || '').trim().toLowerCase(); }
|
||||
function normalizeCloudflareTempEmailDomain(value) { return String(value || '').trim().toLowerCase(); }
|
||||
function normalizeCloudflareTempEmailDomains(value) {
|
||||
const seen = new Set();
|
||||
const domains = [];
|
||||
for (const item of Array.isArray(value) ? value : []) {
|
||||
const normalized = normalizeCloudflareTempEmailDomain(item);
|
||||
if (!normalized || seen.has(normalized)) continue;
|
||||
seen.add(normalized);
|
||||
domains.push(normalized);
|
||||
}
|
||||
return domains;
|
||||
}
|
||||
function normalizeHotmailAccounts(value) { return Array.isArray(value) ? value : []; }
|
||||
function normalizeMail2925Accounts(value) { return Array.isArray(value) ? value : []; }
|
||||
function resolveLegacyAutoStepDelaySeconds() { return undefined; }
|
||||
${bundle}
|
||||
return {
|
||||
buildPersistentSettingsPayload,
|
||||
getCloudflareTempEmailConfig,
|
||||
normalizePersistentSettingValue,
|
||||
};
|
||||
`)();
|
||||
|
||||
assert.equal(api.normalizePersistentSettingValue('cloudflareTempEmailUseRandomSubdomain', 1), true);
|
||||
|
||||
const payload = api.buildPersistentSettingsPayload({
|
||||
cloudflareTempEmailUseRandomSubdomain: true,
|
||||
cloudflareTempEmailDomain: 'mail.example.com',
|
||||
cloudflareTempEmailDomains: ['mail.example.com', 'alt.example.com'],
|
||||
});
|
||||
assert.equal(payload.cloudflareTempEmailUseRandomSubdomain, true);
|
||||
assert.equal(payload.cloudflareTempEmailDomain, 'mail.example.com');
|
||||
assert.deepEqual(payload.cloudflareTempEmailDomains, ['mail.example.com', 'alt.example.com']);
|
||||
|
||||
const config = api.getCloudflareTempEmailConfig({
|
||||
cloudflareTempEmailBaseUrl: 'https://temp.example.com',
|
||||
cloudflareTempEmailAdminAuth: 'admin-secret',
|
||||
cloudflareTempEmailCustomAuth: 'custom-secret',
|
||||
cloudflareTempEmailReceiveMailbox: 'Forward@Example.com',
|
||||
cloudflareTempEmailUseRandomSubdomain: true,
|
||||
cloudflareTempEmailDomain: 'mail.example.com',
|
||||
cloudflareTempEmailDomains: ['mail.example.com'],
|
||||
});
|
||||
assert.deepEqual(config, {
|
||||
baseUrl: 'https://temp.example.com',
|
||||
adminAuth: 'admin-secret',
|
||||
customAuth: 'custom-secret',
|
||||
receiveMailbox: 'forward@example.com',
|
||||
useRandomSubdomain: true,
|
||||
domain: 'mail.example.com',
|
||||
domains: ['mail.example.com'],
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,622 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const backgroundSource = fs.readFileSync('background.js', 'utf8');
|
||||
|
||||
function extractFunction(source, 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);
|
||||
}
|
||||
|
||||
function createMockResponse(ok, status, payload) {
|
||||
return {
|
||||
ok,
|
||||
status,
|
||||
async json() {
|
||||
return payload;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('background imports contribution oauth module and keeps contribution runtime out of persisted settings', () => {
|
||||
const persistedStart = backgroundSource.indexOf('const PERSISTED_SETTING_DEFAULTS = {');
|
||||
const persistedEnd = backgroundSource.indexOf('const PERSISTED_SETTING_KEYS = Object.keys(PERSISTED_SETTING_DEFAULTS);');
|
||||
const defaultStateStart = backgroundSource.indexOf('const DEFAULT_STATE = {');
|
||||
const defaultStateEnd = backgroundSource.indexOf('async function getState()');
|
||||
|
||||
const persistedBlock = backgroundSource.slice(persistedStart, persistedEnd);
|
||||
const defaultStateBlock = backgroundSource.slice(defaultStateStart, defaultStateEnd);
|
||||
|
||||
assert.match(backgroundSource, /background\/contribution-oauth\.js/);
|
||||
assert.doesNotMatch(persistedBlock, /contributionSessionId|contributionAuthUrl|contributionCallbackUrl|contributionStatus/);
|
||||
assert.match(defaultStateBlock, /contributionMode:\s*false|CONTRIBUTION_RUNTIME_DEFAULTS/);
|
||||
});
|
||||
|
||||
test('contribution oauth module exposes a factory', () => {
|
||||
const source = fs.readFileSync('background/contribution-oauth.js', 'utf8');
|
||||
const globalScope = {};
|
||||
const api = new Function('self', 'fetch', `${source}; return self.MultiPageBackgroundContributionOAuth;`)(
|
||||
globalScope,
|
||||
async () => createMockResponse(true, 200, { ok: true })
|
||||
);
|
||||
|
||||
assert.equal(typeof api?.createContributionOAuthManager, 'function');
|
||||
assert.equal(Array.isArray(api?.RUNTIME_KEYS), true);
|
||||
});
|
||||
|
||||
test('buildContributionModeState preserves active contribution runtime while forcing CPA mode', () => {
|
||||
const bundle = extractFunction(backgroundSource, 'buildContributionModeState');
|
||||
|
||||
const api = new Function(`
|
||||
const DEFAULT_STATE = { panelMode: 'cpa' };
|
||||
const CONTRIBUTION_RUNTIME_DEFAULTS = {
|
||||
contributionMode: false,
|
||||
contributionModeExpected: false,
|
||||
contributionNickname: '',
|
||||
contributionQq: '',
|
||||
contributionSessionId: '',
|
||||
contributionAuthUrl: '',
|
||||
contributionAuthState: '',
|
||||
contributionCallbackUrl: '',
|
||||
contributionStatus: '',
|
||||
contributionStatusMessage: '',
|
||||
contributionLastPollAt: 0,
|
||||
contributionCallbackStatus: 'idle',
|
||||
contributionCallbackMessage: '',
|
||||
contributionAuthOpenedAt: 0,
|
||||
contributionAuthTabId: 0,
|
||||
};
|
||||
const CONTRIBUTION_RUNTIME_KEYS = Object.keys(CONTRIBUTION_RUNTIME_DEFAULTS);
|
||||
${bundle}
|
||||
return { buildContributionModeState };
|
||||
`)();
|
||||
|
||||
assert.deepStrictEqual(
|
||||
api.buildContributionModeState(true, {
|
||||
panelMode: 'sub2api',
|
||||
customPassword: 'Secret123!',
|
||||
accountRunHistoryTextEnabled: true,
|
||||
}, {
|
||||
contributionSessionId: 'session-001',
|
||||
contributionAuthUrl: 'https://auth.example.com',
|
||||
contributionStatus: 'waiting',
|
||||
contributionCallbackStatus: 'waiting',
|
||||
}),
|
||||
{
|
||||
contributionMode: true,
|
||||
contributionModeExpected: true,
|
||||
contributionNickname: '',
|
||||
contributionQq: '',
|
||||
contributionSessionId: 'session-001',
|
||||
contributionAuthUrl: 'https://auth.example.com',
|
||||
contributionAuthState: '',
|
||||
contributionCallbackUrl: '',
|
||||
contributionStatus: 'waiting',
|
||||
contributionStatusMessage: '',
|
||||
contributionLastPollAt: 0,
|
||||
contributionCallbackStatus: 'waiting',
|
||||
contributionCallbackMessage: '',
|
||||
contributionAuthOpenedAt: 0,
|
||||
contributionAuthTabId: 0,
|
||||
panelMode: 'cpa',
|
||||
customPassword: '',
|
||||
accountRunHistoryTextEnabled: false,
|
||||
}
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(
|
||||
api.buildContributionModeState(false, {
|
||||
panelMode: 'sub2api',
|
||||
customPassword: 'Secret123!',
|
||||
accountRunHistoryTextEnabled: true,
|
||||
}, {
|
||||
contributionSessionId: 'session-001',
|
||||
contributionAuthUrl: 'https://auth.example.com',
|
||||
contributionStatus: 'waiting',
|
||||
}),
|
||||
{
|
||||
contributionMode: false,
|
||||
contributionModeExpected: false,
|
||||
contributionNickname: '',
|
||||
contributionQq: '',
|
||||
contributionSessionId: '',
|
||||
contributionAuthUrl: '',
|
||||
contributionAuthState: '',
|
||||
contributionCallbackUrl: '',
|
||||
contributionStatus: '',
|
||||
contributionStatusMessage: '',
|
||||
contributionLastPollAt: 0,
|
||||
contributionCallbackStatus: 'idle',
|
||||
contributionCallbackMessage: '',
|
||||
contributionAuthOpenedAt: 0,
|
||||
contributionAuthTabId: 0,
|
||||
panelMode: 'sub2api',
|
||||
customPassword: 'Secret123!',
|
||||
accountRunHistoryTextEnabled: true,
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test('resetState preserves contribution runtime across reset', () => {
|
||||
assert.match(backgroundSource, /CONTRIBUTION_RUNTIME_KEYS/);
|
||||
assert.match(backgroundSource, /const contributionModeState = buildContributionModeState/);
|
||||
assert.match(backgroundSource, /\.\.\.contributionModeState/);
|
||||
});
|
||||
|
||||
test('message router handles contribution mode, start flow, and status polling messages', async () => {
|
||||
const source = fs.readFileSync('background/message-router.js', 'utf8');
|
||||
const globalScope = {};
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundMessageRouter;`)(globalScope);
|
||||
|
||||
const calls = [];
|
||||
const router = api.createMessageRouter({
|
||||
ensureManualInteractionAllowed: async () => ({
|
||||
stepStatuses: { 1: 'pending', 2: 'completed' },
|
||||
contributionMode: true,
|
||||
}),
|
||||
pollContributionStatus: async (options) => {
|
||||
calls.push({ type: 'poll', options });
|
||||
return { contributionStatus: 'waiting' };
|
||||
},
|
||||
setContributionMode: async (enabled) => {
|
||||
calls.push({ type: 'toggle', enabled });
|
||||
return {
|
||||
contributionMode: Boolean(enabled),
|
||||
panelMode: 'cpa',
|
||||
};
|
||||
},
|
||||
startContributionFlow: async (options) => {
|
||||
calls.push({ type: 'start', options });
|
||||
return {
|
||||
contributionMode: true,
|
||||
contributionSessionId: 'session-001',
|
||||
contributionStatus: 'started',
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const enableResponse = await router.handleMessage({
|
||||
type: 'SET_CONTRIBUTION_MODE',
|
||||
payload: { enabled: true },
|
||||
});
|
||||
const startResponse = await router.handleMessage({
|
||||
type: 'START_CONTRIBUTION_FLOW',
|
||||
payload: { nickname: '阿青', qq: '123456' },
|
||||
});
|
||||
const pollResponse = await router.handleMessage({
|
||||
type: 'POLL_CONTRIBUTION_STATUS',
|
||||
payload: { reason: 'test_poll' },
|
||||
});
|
||||
|
||||
assert.equal(enableResponse.ok, true);
|
||||
assert.equal(startResponse.ok, true);
|
||||
assert.equal(pollResponse.ok, true);
|
||||
assert.deepStrictEqual(calls, [
|
||||
{ type: 'toggle', enabled: true },
|
||||
{ type: 'start', options: { nickname: '阿青', qq: '123456' } },
|
||||
{ type: 'poll', options: { reason: 'test_poll' } },
|
||||
]);
|
||||
});
|
||||
|
||||
test('message router re-syncs contribution mode before AUTO_RUN when sidepanel payload marks contributionMode=true', async () => {
|
||||
const source = fs.readFileSync('background/message-router.js', 'utf8');
|
||||
const globalScope = {};
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundMessageRouter;`)(globalScope);
|
||||
|
||||
const calls = [];
|
||||
const router = api.createMessageRouter({
|
||||
clearStopRequest: () => {},
|
||||
getPendingAutoRunTimerPlan: () => null,
|
||||
getState: async () => ({
|
||||
contributionMode: false,
|
||||
stepStatuses: {},
|
||||
}),
|
||||
normalizeRunCount: (value) => Number(value) || 1,
|
||||
setContributionMode: async (enabled) => {
|
||||
calls.push({ type: 'toggle', enabled });
|
||||
return { contributionMode: true };
|
||||
},
|
||||
setState: async (updates) => {
|
||||
calls.push({ type: 'setState', updates });
|
||||
},
|
||||
startAutoRunLoop: (totalRuns, options) => {
|
||||
calls.push({ type: 'startAutoRunLoop', totalRuns, options });
|
||||
},
|
||||
});
|
||||
|
||||
const response = await router.handleMessage({
|
||||
type: 'AUTO_RUN',
|
||||
payload: {
|
||||
totalRuns: 2,
|
||||
autoRunSkipFailures: true,
|
||||
mode: 'restart',
|
||||
contributionMode: true,
|
||||
contributionNickname: '阿青',
|
||||
contributionQq: '123456',
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(response.ok, true);
|
||||
assert.deepStrictEqual(calls, [
|
||||
{ type: 'toggle', enabled: true },
|
||||
{ type: 'setState', updates: { contributionNickname: '阿青', contributionQq: '123456' } },
|
||||
{ type: 'setState', updates: { autoRunSkipFailures: true } },
|
||||
{ type: 'startAutoRunLoop', totalRuns: 2, options: { autoRunSkipFailures: true, mode: 'restart' } },
|
||||
]);
|
||||
});
|
||||
|
||||
test('account run history snapshot sync is disabled in contribution mode', () => {
|
||||
const source = fs.readFileSync('background/account-run-history.js', 'utf8');
|
||||
const globalScope = {};
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundAccountRunHistory;`)(globalScope);
|
||||
|
||||
const helpers = api.createAccountRunHistoryHelpers({
|
||||
addLog: async () => {},
|
||||
buildLocalHelperEndpoint: (baseUrl, path) => `${baseUrl}${path}`,
|
||||
chrome: {
|
||||
storage: {
|
||||
local: {
|
||||
get: async () => ({}),
|
||||
set: async () => {},
|
||||
},
|
||||
},
|
||||
},
|
||||
getErrorMessage: (error) => error?.message || String(error || ''),
|
||||
getState: async () => ({}),
|
||||
normalizeAccountRunHistoryHelperBaseUrl: (value) => String(value || '').trim(),
|
||||
});
|
||||
|
||||
assert.equal(
|
||||
helpers.shouldSyncAccountRunHistorySnapshot({
|
||||
contributionMode: true,
|
||||
accountRunHistoryTextEnabled: true,
|
||||
accountRunHistoryHelperBaseUrl: 'http://127.0.0.1:17373',
|
||||
}),
|
||||
false
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
helpers.shouldSyncAccountRunHistorySnapshot({
|
||||
contributionMode: false,
|
||||
accountRunHistoryTextEnabled: true,
|
||||
accountRunHistoryHelperBaseUrl: 'http://127.0.0.1:17373',
|
||||
}),
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
test('contribution oauth manager starts session, opens auth url, submits callback, and continues polling final status', async () => {
|
||||
const source = fs.readFileSync('background/contribution-oauth.js', 'utf8');
|
||||
const globalScope = {};
|
||||
const fetchCalls = [];
|
||||
const tabCalls = [];
|
||||
const closeCallbackCalls = [];
|
||||
let statusPollCount = 0;
|
||||
let currentState = {
|
||||
contributionMode: true,
|
||||
email: 'user@example.com',
|
||||
contributionSessionId: '',
|
||||
contributionStatus: '',
|
||||
contributionCallbackStatus: 'idle',
|
||||
};
|
||||
const broadcasts = [];
|
||||
|
||||
const api = new Function('self', 'fetch', `${source}; return self.MultiPageBackgroundContributionOAuth;`)(
|
||||
globalScope,
|
||||
async (url, options = {}) => {
|
||||
fetchCalls.push({ url, options });
|
||||
if (String(url).endsWith('/start')) {
|
||||
return createMockResponse(true, 200, {
|
||||
ok: true,
|
||||
session_id: 'session-001',
|
||||
state: 'oauth-state-001',
|
||||
auth_url: 'https://auth.example.com/oauth?state=oauth-state-001',
|
||||
message: '登录地址已生成',
|
||||
});
|
||||
}
|
||||
if (String(url).includes('/status?')) {
|
||||
statusPollCount += 1;
|
||||
if (statusPollCount === 1) {
|
||||
return createMockResponse(true, 200, {
|
||||
ok: true,
|
||||
session_id: 'session-001',
|
||||
status: 'waiting',
|
||||
message: '等待提交回调。',
|
||||
});
|
||||
}
|
||||
return createMockResponse(true, 200, {
|
||||
ok: true,
|
||||
session_id: 'session-001',
|
||||
status: 'processing',
|
||||
message: '回调地址已提交给 CPA,正在等待结果确认。',
|
||||
});
|
||||
}
|
||||
if (String(url).endsWith('/submit-callback')) {
|
||||
return createMockResponse(true, 200, {
|
||||
ok: true,
|
||||
session_id: 'session-001',
|
||||
status: 'processing',
|
||||
message: '回调地址已提交给 CPA,正在等待结果确认。',
|
||||
});
|
||||
}
|
||||
return createMockResponse(true, 200, { ok: true });
|
||||
}
|
||||
);
|
||||
|
||||
const manager = api.createContributionOAuthManager({
|
||||
addLog: async () => {},
|
||||
broadcastDataUpdate(updates) {
|
||||
broadcasts.push(updates);
|
||||
currentState = { ...currentState, ...updates };
|
||||
},
|
||||
chrome: {
|
||||
tabs: {
|
||||
async create(payload) {
|
||||
tabCalls.push(payload);
|
||||
return { id: 88, url: payload.url };
|
||||
},
|
||||
async update() {
|
||||
return null;
|
||||
},
|
||||
onUpdated: { addListener() {} },
|
||||
},
|
||||
webNavigation: {
|
||||
onCommitted: { addListener() {} },
|
||||
onHistoryStateUpdated: { addListener() {} },
|
||||
},
|
||||
},
|
||||
closeLocalhostCallbackTabs: async (callbackUrl) => {
|
||||
closeCallbackCalls.push(callbackUrl);
|
||||
},
|
||||
getState: async () => currentState,
|
||||
setState: async (updates) => {
|
||||
currentState = { ...currentState, ...updates };
|
||||
},
|
||||
});
|
||||
|
||||
const startedState = await manager.startContributionFlow();
|
||||
assert.equal(startedState.contributionSessionId, 'session-001');
|
||||
assert.equal(startedState.contributionAuthState, 'oauth-state-001');
|
||||
assert.equal(startedState.contributionStatus, 'waiting');
|
||||
assert.equal(startedState.contributionAuthTabId, 88);
|
||||
assert.equal(tabCalls.length, 1);
|
||||
assert.match(fetchCalls[0].url, /\/start$/);
|
||||
assert.match(String(fetchCalls[0].options.body || ''), /"nickname":""/);
|
||||
assert.match(String(fetchCalls[0].options.body || ''), /"qq":""/);
|
||||
assert.match(String(fetchCalls[0].options.body || ''), /"email":"user@example\.com"/);
|
||||
assert.match(fetchCalls[1].url, /\/status\?/);
|
||||
|
||||
const callbackState = await manager.handleCapturedCallback(
|
||||
'http://localhost:1455/auth/callback?code=abc123&state=oauth-state-001',
|
||||
{ source: 'test' }
|
||||
);
|
||||
|
||||
assert.equal(callbackState.contributionCallbackUrl, 'http://localhost:1455/auth/callback?code=abc123&state=oauth-state-001');
|
||||
assert.equal(callbackState.contributionCallbackStatus, 'submitted');
|
||||
assert.equal(callbackState.contributionStatus, 'processing');
|
||||
assert.equal(closeCallbackCalls[0], 'http://localhost:1455/auth/callback?code=abc123&state=oauth-state-001');
|
||||
assert.ok(fetchCalls.some((call) => String(call.url).endsWith('/submit-callback')));
|
||||
assert.ok(broadcasts.some((item) => item.contributionCallbackStatus === 'captured'));
|
||||
assert.ok(broadcasts.some((item) => item.contributionCallbackStatus === 'submitted'));
|
||||
});
|
||||
|
||||
test('contribution oauth manager accepts localhost callback urls that contain error and state', async () => {
|
||||
const source = fs.readFileSync('background/contribution-oauth.js', 'utf8');
|
||||
const globalScope = {};
|
||||
const api = new Function('self', 'fetch', `${source}; return self.MultiPageBackgroundContributionOAuth;`)(
|
||||
globalScope,
|
||||
async () => createMockResponse(true, 200, { ok: true })
|
||||
);
|
||||
|
||||
const manager = api.createContributionOAuthManager({
|
||||
chrome: {
|
||||
tabs: {
|
||||
onUpdated: { addListener() {} },
|
||||
},
|
||||
webNavigation: {
|
||||
onCommitted: { addListener() {} },
|
||||
onHistoryStateUpdated: { addListener() {} },
|
||||
},
|
||||
},
|
||||
getState: async () => ({}),
|
||||
setState: async () => ({}),
|
||||
});
|
||||
|
||||
assert.equal(
|
||||
manager.isContributionCallbackUrl(
|
||||
'http://localhost:1455/auth/callback?error=access_denied&state=oauth-state-001',
|
||||
{ contributionAuthState: 'oauth-state-001' }
|
||||
),
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
test('refreshOAuthUrlBeforeStep6 uses contribution oauth session instead of panel bridge in contribution mode', async () => {
|
||||
const bundle = extractFunction(backgroundSource, 'refreshOAuthUrlBeforeStep6');
|
||||
const calls = [];
|
||||
|
||||
const api = new Function(`
|
||||
${bundle}
|
||||
return { refreshOAuthUrlBeforeStep6 };
|
||||
`)();
|
||||
|
||||
globalThis.addLog = async (message) => {
|
||||
calls.push({ type: 'log', message });
|
||||
};
|
||||
globalThis.contributionOAuthManager = {
|
||||
async startContributionFlow(options) {
|
||||
calls.push({ type: 'contribution', options });
|
||||
return {
|
||||
contributionAuthUrl: 'https://auth.example.com/oauth?state=oauth-state-001',
|
||||
};
|
||||
},
|
||||
};
|
||||
globalThis.handleStepData = async (step, payload) => {
|
||||
calls.push({ type: 'step', step, payload });
|
||||
};
|
||||
globalThis.getPanelModeLabel = () => 'CPA';
|
||||
globalThis.requestOAuthUrlFromPanel = async () => {
|
||||
calls.push({ type: 'panel' });
|
||||
return { oauthUrl: 'https://panel.example.com/oauth' };
|
||||
};
|
||||
globalThis.LOG_PREFIX = '[test]';
|
||||
|
||||
const oauthUrl = await api.refreshOAuthUrlBeforeStep6({
|
||||
contributionMode: true,
|
||||
email: 'user@example.com',
|
||||
});
|
||||
|
||||
assert.equal(oauthUrl, 'https://auth.example.com/oauth?state=oauth-state-001');
|
||||
assert.deepStrictEqual(calls, [
|
||||
{ type: 'log', message: '步骤 7:contributionMode=true,走公开贡献接口,正在申请 OAuth 登录地址...' },
|
||||
{
|
||||
type: 'contribution',
|
||||
options: {
|
||||
nickname: '',
|
||||
openAuthTab: false,
|
||||
stateOverride: {
|
||||
contributionMode: true,
|
||||
email: 'user@example.com',
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'step',
|
||||
step: 1,
|
||||
payload: {
|
||||
oauthUrl: 'https://auth.example.com/oauth?state=oauth-state-001',
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
delete globalThis.addLog;
|
||||
delete globalThis.contributionOAuthManager;
|
||||
delete globalThis.handleStepData;
|
||||
delete globalThis.getPanelModeLabel;
|
||||
delete globalThis.requestOAuthUrlFromPanel;
|
||||
delete globalThis.LOG_PREFIX;
|
||||
});
|
||||
|
||||
test('refreshOAuthUrlBeforeStep6 logs the normal CPA/SUB2API/Codex2API path explicitly when contributionMode=false', async () => {
|
||||
const bundle = extractFunction(backgroundSource, 'refreshOAuthUrlBeforeStep6');
|
||||
const calls = [];
|
||||
|
||||
const api = new Function(`
|
||||
${bundle}
|
||||
return { refreshOAuthUrlBeforeStep6 };
|
||||
`)();
|
||||
|
||||
globalThis.addLog = async (message) => {
|
||||
calls.push({ type: 'log', message });
|
||||
};
|
||||
globalThis.contributionOAuthManager = {
|
||||
async startContributionFlow() {
|
||||
calls.push({ type: 'contribution' });
|
||||
return {
|
||||
contributionAuthUrl: 'https://auth.example.com/oauth?state=unexpected',
|
||||
};
|
||||
},
|
||||
};
|
||||
globalThis.handleStepData = async (step, payload) => {
|
||||
calls.push({ type: 'step', step, payload });
|
||||
};
|
||||
globalThis.getPanelModeLabel = () => 'SUB2API';
|
||||
globalThis.requestOAuthUrlFromPanel = async () => {
|
||||
calls.push({ type: 'panel' });
|
||||
return { oauthUrl: 'https://panel.example.com/oauth' };
|
||||
};
|
||||
globalThis.LOG_PREFIX = '[test]';
|
||||
|
||||
const oauthUrl = await api.refreshOAuthUrlBeforeStep6({
|
||||
contributionMode: false,
|
||||
panelMode: 'sub2api',
|
||||
email: 'user@example.com',
|
||||
});
|
||||
|
||||
assert.equal(oauthUrl, 'https://panel.example.com/oauth');
|
||||
assert.deepStrictEqual(calls, [
|
||||
{ type: 'log', message: '步骤 7:contributionMode=false,走普通 CPA / SUB2API / Codex2API 链路(当前面板:SUB2API),正在刷新 OAuth 登录地址...' },
|
||||
{ type: 'panel' },
|
||||
{
|
||||
type: 'step',
|
||||
step: 1,
|
||||
payload: {
|
||||
oauthUrl: 'https://panel.example.com/oauth',
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
delete globalThis.addLog;
|
||||
delete globalThis.contributionOAuthManager;
|
||||
delete globalThis.handleStepData;
|
||||
delete globalThis.getPanelModeLabel;
|
||||
delete globalThis.requestOAuthUrlFromPanel;
|
||||
delete globalThis.LOG_PREFIX;
|
||||
});
|
||||
|
||||
test('executeStep10 blocks silent fallback when contributionModeExpected=true but contributionMode=false', async () => {
|
||||
const bundle = extractFunction(backgroundSource, 'executeStep10');
|
||||
|
||||
const api = new Function(`
|
||||
${bundle}
|
||||
return { executeStep10 };
|
||||
`)();
|
||||
|
||||
globalThis.executeContributionStep10 = async () => ({ ok: true });
|
||||
globalThis.step10Executor = {
|
||||
async executeStep10() {
|
||||
return { ok: true };
|
||||
},
|
||||
};
|
||||
|
||||
await assert.rejects(
|
||||
() => api.executeStep10({
|
||||
contributionModeExpected: true,
|
||||
contributionMode: false,
|
||||
}),
|
||||
/步骤 10:当前自动流程预期使用贡献模式/
|
||||
);
|
||||
|
||||
delete globalThis.executeContributionStep10;
|
||||
delete globalThis.step10Executor;
|
||||
});
|
||||
@@ -2,16 +2,232 @@ const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
function loadGeneratedEmailHelpersApi() {
|
||||
const source = fs.readFileSync('background/generated-email-helpers.js', 'utf8');
|
||||
const globalScope = {};
|
||||
return new Function('self', `${source}; return self.MultiPageGeneratedEmailHelpers;`)(globalScope);
|
||||
}
|
||||
|
||||
test('background imports generated email helper module', () => {
|
||||
const source = fs.readFileSync('background.js', 'utf8');
|
||||
assert.match(source, /importScripts\([\s\S]*'background\/generated-email-helpers\.js'/);
|
||||
});
|
||||
|
||||
test('generated email helper module exposes a factory', () => {
|
||||
const source = fs.readFileSync('background/generated-email-helpers.js', 'utf8');
|
||||
const globalScope = {};
|
||||
|
||||
const api = new Function('self', `${source}; return self.MultiPageGeneratedEmailHelpers;`)(globalScope);
|
||||
const api = loadGeneratedEmailHelpersApi();
|
||||
|
||||
assert.equal(typeof api?.createGeneratedEmailHelpers, 'function');
|
||||
});
|
||||
|
||||
test('generated email helper falls back to normal generator when 2925 is in receive mode', async () => {
|
||||
const api = loadGeneratedEmailHelpersApi();
|
||||
const events = [];
|
||||
|
||||
const helpers = api.createGeneratedEmailHelpers({
|
||||
addLog: async () => {},
|
||||
buildGeneratedAliasEmail: () => {
|
||||
throw new Error('should not build alias in receive mode');
|
||||
},
|
||||
buildCloudflareTempEmailHeaders: () => ({}),
|
||||
CLOUDFLARE_TEMP_EMAIL_GENERATOR: 'cloudflare-temp-email',
|
||||
DUCK_AUTOFILL_URL: 'https://duckduckgo.com/email',
|
||||
fetch: async () => ({ ok: true, text: async () => '{}' }),
|
||||
fetchIcloudHideMyEmail: async () => {
|
||||
throw new Error('should not use icloud generator');
|
||||
},
|
||||
getCloudflareTempEmailAddressFromResponse: () => '',
|
||||
getCloudflareTempEmailConfig: () => ({ baseUrl: '', adminAuth: '', domain: '' }),
|
||||
getState: async () => ({
|
||||
mailProvider: '2925',
|
||||
mail2925Mode: 'receive',
|
||||
emailGenerator: 'duck',
|
||||
}),
|
||||
ensureMail2925AccountForFlow: async () => {
|
||||
throw new Error('should not allocate 2925 account in receive mode');
|
||||
},
|
||||
joinCloudflareTempEmailUrl: () => '',
|
||||
normalizeCloudflareDomain: () => '',
|
||||
normalizeCloudflareTempEmailAddress: () => '',
|
||||
normalizeEmailGenerator: (value) => String(value || '').trim().toLowerCase(),
|
||||
isGeneratedAliasProvider: (_provider, mail2925Mode) => mail2925Mode === 'provide',
|
||||
reuseOrCreateTab: async () => {},
|
||||
sendToContentScript: async (_source, message) => {
|
||||
events.push(message.type);
|
||||
return { email: 'duck@example.com', generated: true };
|
||||
},
|
||||
setEmailState: async (email) => {
|
||||
events.push(['email', email]);
|
||||
},
|
||||
throwIfStopped: () => {},
|
||||
});
|
||||
|
||||
const email = await helpers.fetchGeneratedEmail({
|
||||
mailProvider: '2925',
|
||||
mail2925Mode: 'receive',
|
||||
emailGenerator: 'duck',
|
||||
}, {
|
||||
mailProvider: '2925',
|
||||
mail2925Mode: 'receive',
|
||||
generator: 'duck',
|
||||
});
|
||||
|
||||
assert.equal(email, 'duck@example.com');
|
||||
assert.deepStrictEqual(events, [
|
||||
'FETCH_DUCK_EMAIL',
|
||||
['email', 'duck@example.com'],
|
||||
]);
|
||||
});
|
||||
|
||||
test('generated email helper uses the regular temp email domain when random subdomain mode is disabled', async () => {
|
||||
const api = loadGeneratedEmailHelpersApi();
|
||||
const requests = [];
|
||||
const savedEmails = [];
|
||||
|
||||
const helpers = api.createGeneratedEmailHelpers({
|
||||
addLog: async () => {},
|
||||
buildGeneratedAliasEmail: () => {
|
||||
throw new Error('should not build managed alias');
|
||||
},
|
||||
buildCloudflareTempEmailHeaders: () => ({ 'x-admin-auth': 'admin-secret' }),
|
||||
CLOUDFLARE_TEMP_EMAIL_GENERATOR: 'cloudflare-temp-email',
|
||||
DUCK_AUTOFILL_URL: 'https://duckduckgo.com/email',
|
||||
fetch: async (url, options = {}) => {
|
||||
requests.push({
|
||||
url,
|
||||
method: options.method,
|
||||
body: options.body ? JSON.parse(options.body) : null,
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
text: async () => JSON.stringify({ address: 'user@mail.example.com' }),
|
||||
};
|
||||
},
|
||||
fetchIcloudHideMyEmail: async () => {
|
||||
throw new Error('should not use icloud generator');
|
||||
},
|
||||
getCloudflareTempEmailAddressFromResponse: (payload) => payload.address,
|
||||
getCloudflareTempEmailConfig: () => ({
|
||||
baseUrl: 'https://temp.example.com',
|
||||
adminAuth: 'admin-secret',
|
||||
customAuth: '',
|
||||
useRandomSubdomain: false,
|
||||
domain: 'mail.example.com',
|
||||
}),
|
||||
getState: async () => ({
|
||||
mailProvider: '163',
|
||||
emailGenerator: 'cloudflare-temp-email',
|
||||
}),
|
||||
ensureMail2925AccountForFlow: async () => {
|
||||
throw new Error('should not allocate mail2925 account');
|
||||
},
|
||||
joinCloudflareTempEmailUrl: (baseUrl, path) => `${baseUrl}${path}`,
|
||||
normalizeCloudflareDomain: () => '',
|
||||
normalizeCloudflareTempEmailAddress: (value) => String(value || '').trim().toLowerCase(),
|
||||
normalizeEmailGenerator: (value) => String(value || '').trim().toLowerCase(),
|
||||
isGeneratedAliasProvider: () => false,
|
||||
reuseOrCreateTab: async () => {},
|
||||
sendToContentScript: async () => {
|
||||
throw new Error('should not use duck generator');
|
||||
},
|
||||
setEmailState: async (email) => {
|
||||
savedEmails.push(email);
|
||||
},
|
||||
throwIfStopped: () => {},
|
||||
});
|
||||
|
||||
const email = await helpers.fetchGeneratedEmail({
|
||||
emailGenerator: 'cloudflare-temp-email',
|
||||
}, {
|
||||
generator: 'cloudflare-temp-email',
|
||||
});
|
||||
|
||||
assert.equal(email, 'user@mail.example.com');
|
||||
assert.deepEqual(savedEmails, ['user@mail.example.com']);
|
||||
assert.equal(requests.length, 1);
|
||||
assert.equal(requests[0].url, 'https://temp.example.com/admin/new_address');
|
||||
assert.equal(requests[0].method, 'POST');
|
||||
assert.deepEqual(requests[0].body, {
|
||||
enablePrefix: true,
|
||||
enableRandomSubdomain: false,
|
||||
name: requests[0].body.name,
|
||||
domain: 'mail.example.com',
|
||||
});
|
||||
assert.match(requests[0].body.name, /^[a-z0-9]+$/);
|
||||
});
|
||||
|
||||
test('generated email helper requests random subdomain creation while preserving the returned address', async () => {
|
||||
const api = loadGeneratedEmailHelpersApi();
|
||||
const requests = [];
|
||||
const savedEmails = [];
|
||||
|
||||
const helpers = api.createGeneratedEmailHelpers({
|
||||
addLog: async () => {},
|
||||
buildGeneratedAliasEmail: () => {
|
||||
throw new Error('should not build managed alias');
|
||||
},
|
||||
buildCloudflareTempEmailHeaders: () => ({ 'x-admin-auth': 'admin-secret' }),
|
||||
CLOUDFLARE_TEMP_EMAIL_GENERATOR: 'cloudflare-temp-email',
|
||||
DUCK_AUTOFILL_URL: 'https://duckduckgo.com/email',
|
||||
fetch: async (url, options = {}) => {
|
||||
requests.push({
|
||||
url,
|
||||
method: options.method,
|
||||
body: options.body ? JSON.parse(options.body) : null,
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
text: async () => JSON.stringify({ address: 'user@a1b2c3d4.example.com' }),
|
||||
};
|
||||
},
|
||||
fetchIcloudHideMyEmail: async () => {
|
||||
throw new Error('should not use icloud generator');
|
||||
},
|
||||
getCloudflareTempEmailAddressFromResponse: (payload) => payload.address,
|
||||
getCloudflareTempEmailConfig: () => ({
|
||||
baseUrl: 'https://temp.example.com',
|
||||
adminAuth: 'admin-secret',
|
||||
customAuth: '',
|
||||
useRandomSubdomain: true,
|
||||
domain: 'mail.example.com',
|
||||
}),
|
||||
getState: async () => ({
|
||||
mailProvider: '163',
|
||||
emailGenerator: 'cloudflare-temp-email',
|
||||
}),
|
||||
ensureMail2925AccountForFlow: async () => {
|
||||
throw new Error('should not allocate mail2925 account');
|
||||
},
|
||||
joinCloudflareTempEmailUrl: (baseUrl, path) => `${baseUrl}${path}`,
|
||||
normalizeCloudflareDomain: () => '',
|
||||
normalizeCloudflareTempEmailAddress: (value) => String(value || '').trim().toLowerCase(),
|
||||
normalizeEmailGenerator: (value) => String(value || '').trim().toLowerCase(),
|
||||
isGeneratedAliasProvider: () => false,
|
||||
reuseOrCreateTab: async () => {},
|
||||
sendToContentScript: async () => {
|
||||
throw new Error('should not use duck generator');
|
||||
},
|
||||
setEmailState: async (email) => {
|
||||
savedEmails.push(email);
|
||||
},
|
||||
throwIfStopped: () => {},
|
||||
});
|
||||
|
||||
const email = await helpers.fetchGeneratedEmail({
|
||||
emailGenerator: 'cloudflare-temp-email',
|
||||
}, {
|
||||
generator: 'cloudflare-temp-email',
|
||||
localPart: 'user',
|
||||
});
|
||||
|
||||
assert.equal(email, 'user@a1b2c3d4.example.com');
|
||||
assert.deepEqual(savedEmails, ['user@a1b2c3d4.example.com']);
|
||||
assert.equal(requests.length, 1);
|
||||
assert.equal(requests[0].url, 'https://temp.example.com/admin/new_address');
|
||||
assert.equal(requests[0].method, 'POST');
|
||||
assert.deepEqual(requests[0].body, {
|
||||
enablePrefix: true,
|
||||
enableRandomSubdomain: true,
|
||||
name: 'user',
|
||||
domain: 'mail.example.com',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -143,3 +143,32 @@ return { getMailConfig };
|
||||
navigateOnReuse: true,
|
||||
});
|
||||
});
|
||||
|
||||
test('getMailConfig keeps provider metadata for 2925 mailboxes', () => {
|
||||
const bundle = extractFunction('getMailConfig');
|
||||
const api = new Function(`
|
||||
const ICLOUD_PROVIDER = 'icloud';
|
||||
const GMAIL_PROVIDER = 'gmail';
|
||||
const HOTMAIL_PROVIDER = 'hotmail-api';
|
||||
const LUCKMAIL_PROVIDER = 'luckmail-api';
|
||||
const CLOUDFLARE_TEMP_EMAIL_PROVIDER = 'cloudflare-temp-email';
|
||||
function normalizeIcloudHost(value = '') { return String(value || '').trim().toLowerCase(); }
|
||||
function normalizeInbucketOrigin(value) { return String(value || '').trim(); }
|
||||
function getConfiguredIcloudHostPreference() { return ''; }
|
||||
function getIcloudLoginUrlForHost(host) { return host; }
|
||||
function getIcloudMailUrlForHost(host) { return host; }
|
||||
${bundle}
|
||||
return { getMailConfig };
|
||||
`)();
|
||||
|
||||
assert.deepEqual(api.getMailConfig({
|
||||
mailProvider: '2925',
|
||||
}), {
|
||||
provider: '2925',
|
||||
source: 'mail-2925',
|
||||
url: 'https://2925.com/#/mailList',
|
||||
label: '2925 邮箱',
|
||||
inject: ['content/utils.js', 'content/mail-2925.js'],
|
||||
injectSource: 'mail-2925',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -406,7 +406,10 @@ return {
|
||||
});
|
||||
|
||||
test('resetState preserves LuckMail session config, used map, and preserve tag cache while clearing runtime purchase state', async () => {
|
||||
const bundle = extractFunction('resetState');
|
||||
const bundle = [
|
||||
extractFunction('buildContributionModeState'),
|
||||
extractFunction('resetState'),
|
||||
].join('\n');
|
||||
|
||||
const factory = new Function([
|
||||
'let cleared = false;',
|
||||
@@ -418,6 +421,7 @@ test('resetState preserves LuckMail session config, used map, and preserve tag c
|
||||
" luckmailBaseUrl: 'https://mails.luckyous.com',",
|
||||
" luckmailEmailType: 'ms_graph',",
|
||||
" luckmailDomain: '',",
|
||||
" panelMode: 'cpa',",
|
||||
' luckmailUsedPurchases: {},',
|
||||
' luckmailPreserveTagId: 0,',
|
||||
" luckmailPreserveTagName: '保留',",
|
||||
@@ -425,6 +429,21 @@ test('resetState preserves LuckMail session config, used map, and preserve tag c
|
||||
" currentLuckmailMailCursor: { messageId: 'stale' },",
|
||||
' email: null,',
|
||||
'};',
|
||||
'const CONTRIBUTION_RUNTIME_DEFAULTS = {',
|
||||
' contributionMode: false,',
|
||||
" contributionSessionId: '',",
|
||||
" contributionAuthUrl: '',",
|
||||
" contributionAuthState: '',",
|
||||
" contributionCallbackUrl: '',",
|
||||
" contributionStatus: '',",
|
||||
" contributionStatusMessage: '',",
|
||||
' contributionLastPollAt: 0,',
|
||||
" contributionCallbackStatus: 'idle',",
|
||||
" contributionCallbackMessage: '',",
|
||||
' contributionAuthOpenedAt: 0,',
|
||||
' contributionAuthTabId: 0,',
|
||||
'};',
|
||||
'const CONTRIBUTION_RUNTIME_KEYS = Object.keys(CONTRIBUTION_RUNTIME_DEFAULTS);',
|
||||
'function normalizeLuckmailBaseUrl(value) {',
|
||||
" const normalized = String(value || '').trim() || 'https://mails.luckyous.com';",
|
||||
" return normalized.replace(/\\/$/, '');",
|
||||
|
||||
@@ -0,0 +1,579 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const mail2925Utils = require('../mail2925-utils.js');
|
||||
|
||||
const source = fs.readFileSync('background/mail-2925-session.js', 'utf8');
|
||||
const globalScope = {};
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundMail2925Session;`)(globalScope);
|
||||
|
||||
test('ensureMail2925MailboxSession reuses current mailbox page without sending login when page stays on mailList', async () => {
|
||||
let currentState = {
|
||||
autoRunning: false,
|
||||
mail2925Accounts: mail2925Utils.normalizeMail2925Accounts([
|
||||
{ id: 'acc-1', email: 'acc1@2925.com', password: 'p1', enabled: true, lastUsedAt: 10 },
|
||||
]),
|
||||
currentMail2925AccountId: 'acc-1',
|
||||
};
|
||||
let sendCalls = 0;
|
||||
let readyCalls = 0;
|
||||
|
||||
const manager = api.createMail2925SessionManager({
|
||||
addLog: async () => {},
|
||||
broadcastDataUpdate: () => {},
|
||||
chrome: {
|
||||
tabs: {
|
||||
get: async () => ({ id: 9, url: 'https://2925.com/#/mailList' }),
|
||||
},
|
||||
cookies: {
|
||||
getAll: async () => [],
|
||||
remove: async () => ({ ok: true }),
|
||||
},
|
||||
browsingData: {
|
||||
removeCookies: async () => {},
|
||||
},
|
||||
},
|
||||
ensureContentScriptReadyOnTab: async () => {
|
||||
readyCalls += 1;
|
||||
},
|
||||
findMail2925Account: mail2925Utils.findMail2925Account,
|
||||
getMail2925AccountStatus: mail2925Utils.getMail2925AccountStatus,
|
||||
getState: async () => currentState,
|
||||
isAutoRunLockedState: () => false,
|
||||
isMail2925AccountAvailable: mail2925Utils.isMail2925AccountAvailable,
|
||||
MAIL2925_LIMIT_COOLDOWN_MS: mail2925Utils.MAIL2925_LIMIT_COOLDOWN_MS,
|
||||
normalizeMail2925Account: mail2925Utils.normalizeMail2925Account,
|
||||
normalizeMail2925Accounts: mail2925Utils.normalizeMail2925Accounts,
|
||||
pickMail2925AccountForRun: mail2925Utils.pickMail2925AccountForRun,
|
||||
reuseOrCreateTab: async () => 9,
|
||||
sendToMailContentScriptResilient: async () => {
|
||||
sendCalls += 1;
|
||||
return { loggedIn: true };
|
||||
},
|
||||
setPersistentSettings: async (payload) => {
|
||||
currentState = { ...currentState, ...payload };
|
||||
},
|
||||
setState: async (updates) => {
|
||||
currentState = { ...currentState, ...updates };
|
||||
},
|
||||
throwIfStopped: () => {},
|
||||
upsertMail2925AccountInList: mail2925Utils.upsertMail2925AccountInList,
|
||||
});
|
||||
|
||||
const result = await manager.ensureMail2925MailboxSession({
|
||||
accountId: 'acc-1',
|
||||
forceRelogin: false,
|
||||
allowLoginWhenOnLoginPage: true,
|
||||
actionLabel: '步骤 8:确认 2925 邮箱登录态',
|
||||
});
|
||||
|
||||
assert.equal(sendCalls, 0);
|
||||
assert.equal(readyCalls, 0);
|
||||
assert.equal(result.result.usedExistingSession, true);
|
||||
});
|
||||
|
||||
test('ensureMail2925MailboxSession does not require account-pool accounts when pool is off and mailbox page stays on mailList', async () => {
|
||||
let currentState = {
|
||||
autoRunning: false,
|
||||
mail2925UseAccountPool: false,
|
||||
mail2925Accounts: [],
|
||||
currentMail2925AccountId: null,
|
||||
};
|
||||
let sendCalls = 0;
|
||||
|
||||
const manager = api.createMail2925SessionManager({
|
||||
addLog: async () => {},
|
||||
broadcastDataUpdate: () => {},
|
||||
chrome: {
|
||||
tabs: {
|
||||
get: async () => ({ id: 9, url: 'https://2925.com/#/mailList' }),
|
||||
},
|
||||
cookies: {
|
||||
getAll: async () => [],
|
||||
remove: async () => ({ ok: true }),
|
||||
},
|
||||
browsingData: {
|
||||
removeCookies: async () => {},
|
||||
},
|
||||
},
|
||||
ensureContentScriptReadyOnTab: async () => {},
|
||||
findMail2925Account: mail2925Utils.findMail2925Account,
|
||||
getMail2925AccountStatus: mail2925Utils.getMail2925AccountStatus,
|
||||
getState: async () => currentState,
|
||||
isAutoRunLockedState: () => false,
|
||||
isMail2925AccountAvailable: mail2925Utils.isMail2925AccountAvailable,
|
||||
MAIL2925_LIMIT_COOLDOWN_MS: mail2925Utils.MAIL2925_LIMIT_COOLDOWN_MS,
|
||||
normalizeMail2925Account: mail2925Utils.normalizeMail2925Account,
|
||||
normalizeMail2925Accounts: mail2925Utils.normalizeMail2925Accounts,
|
||||
pickMail2925AccountForRun: mail2925Utils.pickMail2925AccountForRun,
|
||||
reuseOrCreateTab: async () => 9,
|
||||
sendToMailContentScriptResilient: async () => {
|
||||
sendCalls += 1;
|
||||
return { loggedIn: true };
|
||||
},
|
||||
setPersistentSettings: async (payload) => {
|
||||
currentState = { ...currentState, ...payload };
|
||||
},
|
||||
setState: async (updates) => {
|
||||
currentState = { ...currentState, ...updates };
|
||||
},
|
||||
throwIfStopped: () => {},
|
||||
upsertMail2925AccountInList: mail2925Utils.upsertMail2925AccountInList,
|
||||
});
|
||||
|
||||
const result = await manager.ensureMail2925MailboxSession({
|
||||
accountId: null,
|
||||
forceRelogin: false,
|
||||
allowLoginWhenOnLoginPage: false,
|
||||
actionLabel: '步骤 4:确认 2925 邮箱登录态',
|
||||
});
|
||||
|
||||
assert.equal(sendCalls, 0);
|
||||
assert.equal(result.result.usedExistingSession, true);
|
||||
assert.equal(result.account, null);
|
||||
});
|
||||
|
||||
test('ensureMail2925MailboxSession stops immediately when login page is detected and account pool is off', async () => {
|
||||
let currentState = {
|
||||
autoRunning: true,
|
||||
autoRunPhase: 'running',
|
||||
mail2925Accounts: mail2925Utils.normalizeMail2925Accounts([
|
||||
{ id: 'acc-1', email: 'acc1@2925.com', password: 'p1', enabled: true, lastUsedAt: 10 },
|
||||
]),
|
||||
currentMail2925AccountId: 'acc-1',
|
||||
};
|
||||
const stopCalls = [];
|
||||
let sendCalls = 0;
|
||||
|
||||
const manager = api.createMail2925SessionManager({
|
||||
addLog: async () => {},
|
||||
broadcastDataUpdate: () => {},
|
||||
chrome: {
|
||||
tabs: {
|
||||
get: async () => ({ id: 9, url: 'https://2925.com/login/' }),
|
||||
},
|
||||
cookies: {
|
||||
getAll: async () => [],
|
||||
remove: async () => ({ ok: true }),
|
||||
},
|
||||
browsingData: {
|
||||
removeCookies: async () => {},
|
||||
},
|
||||
},
|
||||
ensureContentScriptReadyOnTab: async () => {},
|
||||
findMail2925Account: mail2925Utils.findMail2925Account,
|
||||
getMail2925AccountStatus: mail2925Utils.getMail2925AccountStatus,
|
||||
getState: async () => currentState,
|
||||
isAutoRunLockedState: (state) => Boolean(state?.autoRunning) && state?.autoRunPhase === 'running',
|
||||
isMail2925AccountAvailable: mail2925Utils.isMail2925AccountAvailable,
|
||||
MAIL2925_LIMIT_COOLDOWN_MS: mail2925Utils.MAIL2925_LIMIT_COOLDOWN_MS,
|
||||
normalizeMail2925Account: mail2925Utils.normalizeMail2925Account,
|
||||
normalizeMail2925Accounts: mail2925Utils.normalizeMail2925Accounts,
|
||||
pickMail2925AccountForRun: mail2925Utils.pickMail2925AccountForRun,
|
||||
requestStop: async (options = {}) => {
|
||||
stopCalls.push(options);
|
||||
},
|
||||
reuseOrCreateTab: async () => 9,
|
||||
sendToMailContentScriptResilient: async () => {
|
||||
sendCalls += 1;
|
||||
return { loggedIn: true };
|
||||
},
|
||||
setPersistentSettings: async (payload) => {
|
||||
currentState = { ...currentState, ...payload };
|
||||
},
|
||||
setState: async (updates) => {
|
||||
currentState = { ...currentState, ...updates };
|
||||
},
|
||||
throwIfStopped: () => {},
|
||||
upsertMail2925AccountInList: mail2925Utils.upsertMail2925AccountInList,
|
||||
});
|
||||
|
||||
await assert.rejects(
|
||||
() => manager.ensureMail2925MailboxSession({
|
||||
accountId: 'acc-1',
|
||||
forceRelogin: false,
|
||||
allowLoginWhenOnLoginPage: false,
|
||||
actionLabel: '步骤 4:确认 2925 邮箱登录态',
|
||||
}),
|
||||
/流程已被用户停止。/
|
||||
);
|
||||
|
||||
assert.equal(sendCalls, 0);
|
||||
assert.equal(stopCalls.length, 1);
|
||||
});
|
||||
|
||||
test('ensureMail2925MailboxSession logs in when login page is detected and account pool is on', async () => {
|
||||
let currentState = {
|
||||
autoRunning: false,
|
||||
mail2925Accounts: mail2925Utils.normalizeMail2925Accounts([
|
||||
{ id: 'acc-1', email: 'acc1@2925.com', password: 'p1', enabled: true, lastUsedAt: 10 },
|
||||
]),
|
||||
currentMail2925AccountId: 'acc-1',
|
||||
};
|
||||
let sendCalls = 0;
|
||||
let readyCalls = 0;
|
||||
|
||||
const manager = api.createMail2925SessionManager({
|
||||
addLog: async () => {},
|
||||
broadcastDataUpdate: () => {},
|
||||
chrome: {
|
||||
tabs: {
|
||||
get: async () => ({ id: 9, url: 'https://2925.com/login/' }),
|
||||
},
|
||||
cookies: {
|
||||
getAll: async () => [],
|
||||
remove: async () => ({ ok: true }),
|
||||
},
|
||||
browsingData: {
|
||||
removeCookies: async () => {},
|
||||
},
|
||||
},
|
||||
ensureContentScriptReadyOnTab: async () => {
|
||||
readyCalls += 1;
|
||||
},
|
||||
findMail2925Account: mail2925Utils.findMail2925Account,
|
||||
getMail2925AccountStatus: mail2925Utils.getMail2925AccountStatus,
|
||||
getState: async () => currentState,
|
||||
isAutoRunLockedState: () => false,
|
||||
isMail2925AccountAvailable: mail2925Utils.isMail2925AccountAvailable,
|
||||
MAIL2925_LIMIT_COOLDOWN_MS: mail2925Utils.MAIL2925_LIMIT_COOLDOWN_MS,
|
||||
normalizeMail2925Account: mail2925Utils.normalizeMail2925Account,
|
||||
normalizeMail2925Accounts: mail2925Utils.normalizeMail2925Accounts,
|
||||
pickMail2925AccountForRun: mail2925Utils.pickMail2925AccountForRun,
|
||||
reuseOrCreateTab: async () => 9,
|
||||
sendToMailContentScriptResilient: async () => {
|
||||
sendCalls += 1;
|
||||
return { loggedIn: true, currentView: 'mailbox' };
|
||||
},
|
||||
setPersistentSettings: async (payload) => {
|
||||
currentState = { ...currentState, ...payload };
|
||||
},
|
||||
setState: async (updates) => {
|
||||
currentState = { ...currentState, ...updates };
|
||||
},
|
||||
throwIfStopped: () => {},
|
||||
upsertMail2925AccountInList: mail2925Utils.upsertMail2925AccountInList,
|
||||
});
|
||||
|
||||
const result = await manager.ensureMail2925MailboxSession({
|
||||
accountId: 'acc-1',
|
||||
forceRelogin: false,
|
||||
allowLoginWhenOnLoginPage: true,
|
||||
actionLabel: '步骤 4:确认 2925 邮箱登录态',
|
||||
});
|
||||
|
||||
assert.equal(sendCalls, 1);
|
||||
assert.equal(readyCalls, 1);
|
||||
assert.equal(result.result.loggedIn, true);
|
||||
});
|
||||
|
||||
test('ensureMail2925MailboxSession recovers after login-page navigation reload breaks the old content-script channel', async () => {
|
||||
let currentState = {
|
||||
autoRunning: false,
|
||||
mail2925Accounts: mail2925Utils.normalizeMail2925Accounts([
|
||||
{ id: 'acc-1', email: 'acc1@2925.com', password: 'p1', enabled: true, lastUsedAt: 10 },
|
||||
]),
|
||||
currentMail2925AccountId: 'acc-1',
|
||||
};
|
||||
let tabUrl = 'https://2925.com/login/';
|
||||
const events = {
|
||||
logs: [],
|
||||
readyCalls: 0,
|
||||
sendCalls: 0,
|
||||
waitCompleteCalls: 0,
|
||||
};
|
||||
|
||||
const manager = api.createMail2925SessionManager({
|
||||
addLog: async (message, level = 'info') => {
|
||||
events.logs.push({ message, level });
|
||||
},
|
||||
broadcastDataUpdate: () => {},
|
||||
chrome: {
|
||||
tabs: {
|
||||
get: async () => ({ id: 9, url: tabUrl, status: tabUrl.includes('/#/mailList') ? 'complete' : 'loading' }),
|
||||
},
|
||||
cookies: {
|
||||
getAll: async () => [],
|
||||
remove: async () => ({ ok: true }),
|
||||
},
|
||||
browsingData: {
|
||||
removeCookies: async () => {},
|
||||
},
|
||||
},
|
||||
ensureContentScriptReadyOnTab: async () => {
|
||||
events.readyCalls += 1;
|
||||
},
|
||||
findMail2925Account: mail2925Utils.findMail2925Account,
|
||||
getMail2925AccountStatus: mail2925Utils.getMail2925AccountStatus,
|
||||
getState: async () => currentState,
|
||||
isAutoRunLockedState: () => false,
|
||||
isMail2925AccountAvailable: mail2925Utils.isMail2925AccountAvailable,
|
||||
MAIL2925_LIMIT_COOLDOWN_MS: mail2925Utils.MAIL2925_LIMIT_COOLDOWN_MS,
|
||||
normalizeMail2925Account: mail2925Utils.normalizeMail2925Account,
|
||||
normalizeMail2925Accounts: mail2925Utils.normalizeMail2925Accounts,
|
||||
pickMail2925AccountForRun: mail2925Utils.pickMail2925AccountForRun,
|
||||
reuseOrCreateTab: async () => 9,
|
||||
sendToContentScriptResilient: async () => {
|
||||
events.sendCalls += 1;
|
||||
if (events.sendCalls === 1) {
|
||||
throw new Error('Could not establish connection. Receiving end does not exist.');
|
||||
}
|
||||
return { loggedIn: true, currentView: 'mailbox', mailboxEmail: 'acc1@2925.com' };
|
||||
},
|
||||
setPersistentSettings: async (payload) => {
|
||||
currentState = { ...currentState, ...payload };
|
||||
},
|
||||
setState: async (updates) => {
|
||||
currentState = { ...currentState, ...updates };
|
||||
},
|
||||
throwIfStopped: () => {},
|
||||
upsertMail2925AccountInList: mail2925Utils.upsertMail2925AccountInList,
|
||||
waitForTabComplete: async () => {
|
||||
events.waitCompleteCalls += 1;
|
||||
tabUrl = 'https://2925.com/#/mailList';
|
||||
return { id: 9, url: tabUrl, status: 'complete' };
|
||||
},
|
||||
});
|
||||
|
||||
const result = await manager.ensureMail2925MailboxSession({
|
||||
accountId: 'acc-1',
|
||||
forceRelogin: false,
|
||||
allowLoginWhenOnLoginPage: true,
|
||||
actionLabel: '步骤 4:确认 2925 邮箱登录态',
|
||||
});
|
||||
|
||||
assert.equal(events.sendCalls, 2);
|
||||
assert.equal(events.readyCalls, 2);
|
||||
assert.equal(events.waitCompleteCalls, 1);
|
||||
assert.equal(result.result.loggedIn, true);
|
||||
const combinedLogs = events.logs.map(({ message }) => message).join('\n');
|
||||
assert.match(combinedLogs, /登录提交后页面发生跳转或重载/);
|
||||
assert.match(combinedLogs, /登录跳转恢复后当前标签地址:https:\/\/2925\.com\/#\/mailList/);
|
||||
assert.match(combinedLogs, /页面恢复完成,正在重新确认登录态/);
|
||||
});
|
||||
|
||||
test('ensureMail2925MailboxSession relogs with selected account when mailbox page email mismatches and pool is on', async () => {
|
||||
let currentState = {
|
||||
autoRunning: false,
|
||||
mail2925UseAccountPool: true,
|
||||
mail2925Accounts: mail2925Utils.normalizeMail2925Accounts([
|
||||
{ id: 'acc-1', email: 'target@2925.com', password: 'p1', enabled: true, lastUsedAt: 10 },
|
||||
]),
|
||||
currentMail2925AccountId: 'acc-1',
|
||||
};
|
||||
const openedUrls = [];
|
||||
const sendPayloads = [];
|
||||
|
||||
const manager = api.createMail2925SessionManager({
|
||||
addLog: async () => {},
|
||||
broadcastDataUpdate: () => {},
|
||||
chrome: {
|
||||
tabs: {
|
||||
get: async () => ({ id: 9, url: openedUrls.at(-1) || 'https://2925.com/#/mailList' }),
|
||||
},
|
||||
cookies: {
|
||||
getAll: async () => [],
|
||||
remove: async () => ({ ok: true }),
|
||||
},
|
||||
browsingData: {
|
||||
removeCookies: async () => {},
|
||||
},
|
||||
},
|
||||
ensureContentScriptReadyOnTab: async () => {},
|
||||
findMail2925Account: mail2925Utils.findMail2925Account,
|
||||
getMail2925AccountStatus: mail2925Utils.getMail2925AccountStatus,
|
||||
getState: async () => currentState,
|
||||
isAutoRunLockedState: () => false,
|
||||
isMail2925AccountAvailable: mail2925Utils.isMail2925AccountAvailable,
|
||||
MAIL2925_LIMIT_COOLDOWN_MS: mail2925Utils.MAIL2925_LIMIT_COOLDOWN_MS,
|
||||
normalizeMail2925Account: mail2925Utils.normalizeMail2925Account,
|
||||
normalizeMail2925Accounts: mail2925Utils.normalizeMail2925Accounts,
|
||||
pickMail2925AccountForRun: mail2925Utils.pickMail2925AccountForRun,
|
||||
reuseOrCreateTab: async (_source, url) => {
|
||||
openedUrls.push(url);
|
||||
return 9;
|
||||
},
|
||||
sendToMailContentScriptResilient: async (_mail, message) => {
|
||||
sendPayloads.push(message.payload);
|
||||
if (sendPayloads.length === 1) {
|
||||
return {
|
||||
loggedIn: true,
|
||||
currentView: 'mailbox',
|
||||
mailboxEmail: 'wrong@2925.com',
|
||||
};
|
||||
}
|
||||
return {
|
||||
loggedIn: true,
|
||||
currentView: 'mailbox',
|
||||
mailboxEmail: 'target@2925.com',
|
||||
};
|
||||
},
|
||||
setPersistentSettings: async (payload) => {
|
||||
currentState = { ...currentState, ...payload };
|
||||
},
|
||||
setState: async (updates) => {
|
||||
currentState = { ...currentState, ...updates };
|
||||
},
|
||||
sleepWithStop: async () => {},
|
||||
throwIfStopped: () => {},
|
||||
upsertMail2925AccountInList: mail2925Utils.upsertMail2925AccountInList,
|
||||
waitForTabUrlMatch: async () => ({ url: 'https://2925.com/login/' }),
|
||||
});
|
||||
|
||||
const result = await manager.ensureMail2925MailboxSession({
|
||||
accountId: 'acc-1',
|
||||
forceRelogin: false,
|
||||
allowLoginWhenOnLoginPage: true,
|
||||
expectedMailboxEmail: 'target@2925.com',
|
||||
actionLabel: '步骤 4:确认 2925 邮箱登录态',
|
||||
});
|
||||
|
||||
assert.equal(result.result.loggedIn, true);
|
||||
assert.deepStrictEqual(openedUrls, [
|
||||
'https://2925.com/#/mailList',
|
||||
'https://2925.com/login/',
|
||||
]);
|
||||
assert.equal(sendPayloads.length, 2);
|
||||
assert.equal(sendPayloads[0].allowLoginWhenOnLoginPage, true);
|
||||
assert.equal(sendPayloads[1].forceLogin, true);
|
||||
});
|
||||
|
||||
test('ensureMail2925MailboxSession stops when mailbox page email mismatches and pool is off', async () => {
|
||||
let currentState = {
|
||||
autoRunning: true,
|
||||
autoRunPhase: 'running',
|
||||
mail2925UseAccountPool: false,
|
||||
mail2925Accounts: [],
|
||||
currentMail2925AccountId: null,
|
||||
};
|
||||
const stopCalls = [];
|
||||
let sendCalls = 0;
|
||||
|
||||
const manager = api.createMail2925SessionManager({
|
||||
addLog: async () => {},
|
||||
broadcastDataUpdate: () => {},
|
||||
chrome: {
|
||||
tabs: {
|
||||
get: async () => ({ id: 9, url: 'https://2925.com/#/mailList' }),
|
||||
},
|
||||
cookies: {
|
||||
getAll: async () => [],
|
||||
remove: async () => ({ ok: true }),
|
||||
},
|
||||
browsingData: {
|
||||
removeCookies: async () => {},
|
||||
},
|
||||
},
|
||||
ensureContentScriptReadyOnTab: async () => {},
|
||||
findMail2925Account: mail2925Utils.findMail2925Account,
|
||||
getMail2925AccountStatus: mail2925Utils.getMail2925AccountStatus,
|
||||
getState: async () => currentState,
|
||||
isAutoRunLockedState: (state) => Boolean(state?.autoRunning) && state?.autoRunPhase === 'running',
|
||||
isMail2925AccountAvailable: mail2925Utils.isMail2925AccountAvailable,
|
||||
MAIL2925_LIMIT_COOLDOWN_MS: mail2925Utils.MAIL2925_LIMIT_COOLDOWN_MS,
|
||||
normalizeMail2925Account: mail2925Utils.normalizeMail2925Account,
|
||||
normalizeMail2925Accounts: mail2925Utils.normalizeMail2925Accounts,
|
||||
pickMail2925AccountForRun: mail2925Utils.pickMail2925AccountForRun,
|
||||
requestStop: async (options = {}) => {
|
||||
stopCalls.push(options);
|
||||
},
|
||||
reuseOrCreateTab: async () => 9,
|
||||
sendToMailContentScriptResilient: async () => {
|
||||
sendCalls += 1;
|
||||
return {
|
||||
loggedIn: true,
|
||||
currentView: 'mailbox',
|
||||
mailboxEmail: 'wrong@2925.com',
|
||||
};
|
||||
},
|
||||
setPersistentSettings: async (payload) => {
|
||||
currentState = { ...currentState, ...payload };
|
||||
},
|
||||
setState: async (updates) => {
|
||||
currentState = { ...currentState, ...updates };
|
||||
},
|
||||
throwIfStopped: () => {},
|
||||
upsertMail2925AccountInList: mail2925Utils.upsertMail2925AccountInList,
|
||||
});
|
||||
|
||||
await assert.rejects(
|
||||
() => manager.ensureMail2925MailboxSession({
|
||||
accountId: null,
|
||||
forceRelogin: false,
|
||||
allowLoginWhenOnLoginPage: false,
|
||||
expectedMailboxEmail: 'target@2925.com',
|
||||
actionLabel: '步骤 4:确认 2925 邮箱登录态',
|
||||
}),
|
||||
/流程已被用户停止。/
|
||||
);
|
||||
|
||||
assert.equal(sendCalls, 1);
|
||||
assert.equal(stopCalls.length, 1);
|
||||
assert.match(stopCalls[0].logMessage, /与目标账号 target@2925\.com 不一致/);
|
||||
});
|
||||
|
||||
test('ensureMail2925MailboxSession does not crash when mailbox page is reused but top email cannot be detected', async () => {
|
||||
let currentState = {
|
||||
autoRunning: false,
|
||||
mail2925UseAccountPool: false,
|
||||
mail2925Accounts: [],
|
||||
currentMail2925AccountId: null,
|
||||
};
|
||||
let sendCalls = 0;
|
||||
|
||||
const manager = api.createMail2925SessionManager({
|
||||
addLog: async () => {},
|
||||
broadcastDataUpdate: () => {},
|
||||
chrome: {
|
||||
tabs: {
|
||||
get: async () => ({ id: 9, url: 'https://2925.com/#/mailList' }),
|
||||
},
|
||||
cookies: {
|
||||
getAll: async () => [],
|
||||
remove: async () => ({ ok: true }),
|
||||
},
|
||||
browsingData: {
|
||||
removeCookies: async () => {},
|
||||
},
|
||||
},
|
||||
ensureContentScriptReadyOnTab: async () => {},
|
||||
findMail2925Account: mail2925Utils.findMail2925Account,
|
||||
getMail2925AccountStatus: mail2925Utils.getMail2925AccountStatus,
|
||||
getState: async () => currentState,
|
||||
isAutoRunLockedState: () => false,
|
||||
isMail2925AccountAvailable: mail2925Utils.isMail2925AccountAvailable,
|
||||
MAIL2925_LIMIT_COOLDOWN_MS: mail2925Utils.MAIL2925_LIMIT_COOLDOWN_MS,
|
||||
normalizeMail2925Account: mail2925Utils.normalizeMail2925Account,
|
||||
normalizeMail2925Accounts: mail2925Utils.normalizeMail2925Accounts,
|
||||
pickMail2925AccountForRun: mail2925Utils.pickMail2925AccountForRun,
|
||||
reuseOrCreateTab: async () => 9,
|
||||
sendToMailContentScriptResilient: async () => {
|
||||
sendCalls += 1;
|
||||
return {
|
||||
loggedIn: true,
|
||||
currentView: 'mailbox',
|
||||
mailboxEmail: '',
|
||||
};
|
||||
},
|
||||
setPersistentSettings: async (payload) => {
|
||||
currentState = { ...currentState, ...payload };
|
||||
},
|
||||
setState: async (updates) => {
|
||||
currentState = { ...currentState, ...updates };
|
||||
},
|
||||
throwIfStopped: () => {},
|
||||
upsertMail2925AccountInList: mail2925Utils.upsertMail2925AccountInList,
|
||||
});
|
||||
|
||||
const result = await manager.ensureMail2925MailboxSession({
|
||||
accountId: null,
|
||||
forceRelogin: false,
|
||||
allowLoginWhenOnLoginPage: false,
|
||||
expectedMailboxEmail: 'target@2925.com',
|
||||
actionLabel: '步骤 4:确认 2925 邮箱登录态',
|
||||
});
|
||||
|
||||
assert.equal(sendCalls, 1);
|
||||
assert.equal(result.account, null);
|
||||
assert.equal(result.result.usedExistingSession, true);
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const mail2925Utils = require('../mail2925-utils.js');
|
||||
|
||||
test('background mail2925 session uses /login/ as relogin entry url', () => {
|
||||
const source = fs.readFileSync('background/mail-2925-session.js', 'utf8');
|
||||
assert.match(source, /const MAIL2925_LOGIN_URL = 'https:\/\/2925\.com\/login\/';/);
|
||||
});
|
||||
|
||||
test('background mail2925 session keeps a long login response timeout and a separate page-recovery window', () => {
|
||||
const source = fs.readFileSync('background/mail-2925-session.js', 'utf8');
|
||||
assert.match(source, /const MAIL2925_LOGIN_MESSAGE_RETRY_WINDOW_MS = 15000;/);
|
||||
assert.match(source, /const MAIL2925_LOGIN_RESPONSE_TIMEOUT_MS = 120000;/);
|
||||
assert.match(source, /const MAIL2925_LOGIN_PAGE_RECOVERY_TIMEOUT_MS = 120000;/);
|
||||
assert.match(source, /responseTimeoutMs:\s*MAIL2925_LOGIN_RESPONSE_TIMEOUT_MS,/);
|
||||
assert.match(source, /recoverMail2925LoginPageAfterTransportError/);
|
||||
});
|
||||
|
||||
test('ensureMail2925MailboxSession waits 3 seconds before and after opening login page on force relogin', async () => {
|
||||
const source = fs.readFileSync('background/mail-2925-session.js', 'utf8');
|
||||
const globalScope = {};
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundMail2925Session;`)(globalScope);
|
||||
|
||||
let currentState = {
|
||||
autoRunning: false,
|
||||
mail2925Accounts: mail2925Utils.normalizeMail2925Accounts([
|
||||
{ id: 'acc-1', email: 'acc1@2925.com', password: 'p1', enabled: true, lastUsedAt: 10 },
|
||||
]),
|
||||
currentMail2925AccountId: 'acc-1',
|
||||
};
|
||||
const events = {
|
||||
sleeps: [],
|
||||
openedUrls: [],
|
||||
readyCalls: 0,
|
||||
};
|
||||
|
||||
const manager = api.createMail2925SessionManager({
|
||||
addLog: async () => {},
|
||||
broadcastDataUpdate: () => {},
|
||||
chrome: {
|
||||
cookies: {
|
||||
getAll: async () => [],
|
||||
remove: async () => ({ ok: true }),
|
||||
},
|
||||
browsingData: {
|
||||
removeCookies: async () => {},
|
||||
},
|
||||
},
|
||||
findMail2925Account: mail2925Utils.findMail2925Account,
|
||||
getMail2925AccountStatus: mail2925Utils.getMail2925AccountStatus,
|
||||
getState: async () => currentState,
|
||||
isAutoRunLockedState: () => false,
|
||||
isMail2925AccountAvailable: mail2925Utils.isMail2925AccountAvailable,
|
||||
MAIL2925_LIMIT_COOLDOWN_MS: mail2925Utils.MAIL2925_LIMIT_COOLDOWN_MS,
|
||||
normalizeMail2925Account: mail2925Utils.normalizeMail2925Account,
|
||||
normalizeMail2925Accounts: mail2925Utils.normalizeMail2925Accounts,
|
||||
pickMail2925AccountForRun: mail2925Utils.pickMail2925AccountForRun,
|
||||
requestStop: async () => {},
|
||||
ensureContentScriptReadyOnTab: async () => {
|
||||
events.readyCalls += 1;
|
||||
},
|
||||
reuseOrCreateTab: async (_source, url) => {
|
||||
events.openedUrls.push(url);
|
||||
return 1;
|
||||
},
|
||||
sendToMailContentScriptResilient: async () => ({ loggedIn: true }),
|
||||
setPersistentSettings: async (payload) => {
|
||||
currentState = { ...currentState, ...payload };
|
||||
},
|
||||
setState: async (updates) => {
|
||||
currentState = { ...currentState, ...updates };
|
||||
},
|
||||
sleepWithStop: async (ms) => {
|
||||
events.sleeps.push(ms);
|
||||
},
|
||||
throwIfStopped: () => {},
|
||||
upsertMail2925AccountInList: mail2925Utils.upsertMail2925AccountInList,
|
||||
waitForTabUrlMatch: async () => ({ url: 'https://2925.com/login/' }),
|
||||
});
|
||||
|
||||
await manager.ensureMail2925MailboxSession({
|
||||
accountId: 'acc-1',
|
||||
forceRelogin: true,
|
||||
actionLabel: '步骤 4:确认 2925 邮箱登录态',
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(events.openedUrls, ['https://2925.com/login/']);
|
||||
assert.deepStrictEqual(events.sleeps, [3000, 3000]);
|
||||
assert.equal(events.readyCalls, 1);
|
||||
});
|
||||
@@ -0,0 +1,339 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const mail2925Utils = require('../mail2925-utils.js');
|
||||
|
||||
test('background mail2925 session module exposes a factory', () => {
|
||||
const source = fs.readFileSync('background/mail-2925-session.js', 'utf8');
|
||||
const globalScope = {};
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundMail2925Session;`)(globalScope);
|
||||
|
||||
assert.equal(typeof api?.createMail2925SessionManager, 'function');
|
||||
});
|
||||
|
||||
test('handleMail2925LimitReachedError disables current account and switches to the next one', async () => {
|
||||
const source = fs.readFileSync('background/mail-2925-session.js', 'utf8');
|
||||
const globalScope = {};
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundMail2925Session;`)(globalScope);
|
||||
|
||||
let currentState = {
|
||||
mail2925UseAccountPool: true,
|
||||
mail2925Accounts: mail2925Utils.normalizeMail2925Accounts([
|
||||
{ id: 'current', email: 'current@2925.com', password: 'p1', enabled: true, lastUsedAt: 10 },
|
||||
{ id: 'next', email: 'next@2925.com', password: 'p2', enabled: true, lastUsedAt: 20 },
|
||||
]),
|
||||
currentMail2925AccountId: 'current',
|
||||
};
|
||||
const events = {
|
||||
logs: [],
|
||||
dataUpdates: [],
|
||||
tabOpens: 0,
|
||||
sessionChecks: 0,
|
||||
};
|
||||
|
||||
const manager = api.createMail2925SessionManager({
|
||||
addLog: async (message, level = 'info') => {
|
||||
events.logs.push({ message, level });
|
||||
},
|
||||
broadcastDataUpdate: (payload) => {
|
||||
events.dataUpdates.push(payload);
|
||||
},
|
||||
chrome: {
|
||||
cookies: {
|
||||
getAll: async () => [],
|
||||
remove: async () => ({ ok: true }),
|
||||
},
|
||||
browsingData: {
|
||||
removeCookies: async () => {},
|
||||
},
|
||||
},
|
||||
findMail2925Account: mail2925Utils.findMail2925Account,
|
||||
getMail2925AccountStatus: mail2925Utils.getMail2925AccountStatus,
|
||||
getState: async () => currentState,
|
||||
isMail2925AccountAvailable: mail2925Utils.isMail2925AccountAvailable,
|
||||
MAIL2925_LIMIT_COOLDOWN_MS: mail2925Utils.MAIL2925_LIMIT_COOLDOWN_MS,
|
||||
normalizeMail2925Account: mail2925Utils.normalizeMail2925Account,
|
||||
normalizeMail2925Accounts: mail2925Utils.normalizeMail2925Accounts,
|
||||
pickMail2925AccountForRun: mail2925Utils.pickMail2925AccountForRun,
|
||||
reuseOrCreateTab: async () => {
|
||||
events.tabOpens += 1;
|
||||
return 1;
|
||||
},
|
||||
sendToMailContentScriptResilient: async () => {
|
||||
events.sessionChecks += 1;
|
||||
return { loggedIn: true };
|
||||
},
|
||||
setPersistentSettings: async (payload) => {
|
||||
currentState = {
|
||||
...currentState,
|
||||
...payload,
|
||||
};
|
||||
},
|
||||
setState: async (updates) => {
|
||||
currentState = {
|
||||
...currentState,
|
||||
...updates,
|
||||
};
|
||||
},
|
||||
throwIfStopped: () => {},
|
||||
upsertMail2925AccountInList: mail2925Utils.upsertMail2925AccountInList,
|
||||
});
|
||||
|
||||
const error = await manager.handleMail2925LimitReachedError(
|
||||
4,
|
||||
new Error('MAIL2925_LIMIT_REACHED::子邮箱已达上限邮箱')
|
||||
);
|
||||
|
||||
assert.match(error.message, /^MAIL2925_THREAD_TERMINATED::/);
|
||||
assert.equal(currentState.currentMail2925AccountId, 'next');
|
||||
assert.ok(events.tabOpens >= 1);
|
||||
assert.ok(events.sessionChecks >= 1);
|
||||
|
||||
const currentAccount = currentState.mail2925Accounts.find((account) => account.id === 'current');
|
||||
assert.equal(currentAccount.lastError, '子邮箱已达上限邮箱');
|
||||
assert.ok(currentAccount.disabledUntil > Date.now());
|
||||
});
|
||||
|
||||
test('handleMail2925LimitReachedError requests stop when no next mail2925 account is available', async () => {
|
||||
const source = fs.readFileSync('background/mail-2925-session.js', 'utf8');
|
||||
const globalScope = {};
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundMail2925Session;`)(globalScope);
|
||||
|
||||
let currentState = {
|
||||
mail2925UseAccountPool: true,
|
||||
mail2925Accounts: mail2925Utils.normalizeMail2925Accounts([
|
||||
{ id: 'only', email: 'only@2925.com', password: 'p1', enabled: true, lastUsedAt: 10 },
|
||||
]),
|
||||
currentMail2925AccountId: 'only',
|
||||
};
|
||||
const events = {
|
||||
stopCalls: [],
|
||||
};
|
||||
|
||||
const manager = api.createMail2925SessionManager({
|
||||
addLog: async () => {},
|
||||
broadcastDataUpdate: () => {},
|
||||
chrome: {
|
||||
cookies: {
|
||||
getAll: async () => [],
|
||||
remove: async () => ({ ok: true }),
|
||||
},
|
||||
browsingData: {
|
||||
removeCookies: async () => {},
|
||||
},
|
||||
},
|
||||
findMail2925Account: mail2925Utils.findMail2925Account,
|
||||
getMail2925AccountStatus: mail2925Utils.getMail2925AccountStatus,
|
||||
getState: async () => currentState,
|
||||
isMail2925AccountAvailable: mail2925Utils.isMail2925AccountAvailable,
|
||||
MAIL2925_LIMIT_COOLDOWN_MS: mail2925Utils.MAIL2925_LIMIT_COOLDOWN_MS,
|
||||
normalizeMail2925Account: mail2925Utils.normalizeMail2925Account,
|
||||
normalizeMail2925Accounts: mail2925Utils.normalizeMail2925Accounts,
|
||||
pickMail2925AccountForRun: mail2925Utils.pickMail2925AccountForRun,
|
||||
requestStop: async (options = {}) => {
|
||||
events.stopCalls.push(options);
|
||||
},
|
||||
reuseOrCreateTab: async () => 1,
|
||||
sendToMailContentScriptResilient: async () => ({ loggedIn: true }),
|
||||
setPersistentSettings: async (payload) => {
|
||||
currentState = {
|
||||
...currentState,
|
||||
...payload,
|
||||
};
|
||||
},
|
||||
setState: async (updates) => {
|
||||
currentState = {
|
||||
...currentState,
|
||||
...updates,
|
||||
};
|
||||
},
|
||||
throwIfStopped: () => {},
|
||||
upsertMail2925AccountInList: mail2925Utils.upsertMail2925AccountInList,
|
||||
});
|
||||
|
||||
const error = await manager.handleMail2925LimitReachedError(
|
||||
4,
|
||||
new Error('MAIL2925_LIMIT_REACHED::子邮箱已达上限邮箱')
|
||||
);
|
||||
|
||||
assert.equal(error.message, '流程已被用户停止。');
|
||||
assert.equal(currentState.currentMail2925AccountId, null);
|
||||
assert.equal(events.stopCalls.length, 1);
|
||||
assert.match(events.stopCalls[0].logMessage, /没有可切换的下一个账号/);
|
||||
});
|
||||
|
||||
test('ensureMail2925MailboxSession requests stop when auto run is active and login does not reach mailbox', async () => {
|
||||
const source = fs.readFileSync('background/mail-2925-session.js', 'utf8');
|
||||
const globalScope = {};
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundMail2925Session;`)(globalScope);
|
||||
|
||||
let currentState = {
|
||||
autoRunning: true,
|
||||
autoRunPhase: 'running',
|
||||
mail2925Accounts: mail2925Utils.normalizeMail2925Accounts([
|
||||
{ id: 'acc-1', email: 'acc1@2925.com', password: 'p1', enabled: true, lastUsedAt: 10 },
|
||||
]),
|
||||
currentMail2925AccountId: 'acc-1',
|
||||
};
|
||||
const events = {
|
||||
stopCalls: [],
|
||||
};
|
||||
|
||||
const manager = api.createMail2925SessionManager({
|
||||
addLog: async () => {},
|
||||
broadcastDataUpdate: () => {},
|
||||
chrome: {
|
||||
cookies: {
|
||||
getAll: async () => [],
|
||||
remove: async () => ({ ok: true }),
|
||||
},
|
||||
browsingData: {
|
||||
removeCookies: async () => {},
|
||||
},
|
||||
},
|
||||
findMail2925Account: mail2925Utils.findMail2925Account,
|
||||
getMail2925AccountStatus: mail2925Utils.getMail2925AccountStatus,
|
||||
getState: async () => currentState,
|
||||
isAutoRunLockedState: (state) => Boolean(state?.autoRunning) && state?.autoRunPhase === 'running',
|
||||
isMail2925AccountAvailable: mail2925Utils.isMail2925AccountAvailable,
|
||||
MAIL2925_LIMIT_COOLDOWN_MS: mail2925Utils.MAIL2925_LIMIT_COOLDOWN_MS,
|
||||
normalizeMail2925Account: mail2925Utils.normalizeMail2925Account,
|
||||
normalizeMail2925Accounts: mail2925Utils.normalizeMail2925Accounts,
|
||||
pickMail2925AccountForRun: mail2925Utils.pickMail2925AccountForRun,
|
||||
requestStop: async (options = {}) => {
|
||||
events.stopCalls.push(options);
|
||||
},
|
||||
reuseOrCreateTab: async () => 1,
|
||||
sendToMailContentScriptResilient: async () => ({ loggedIn: false }),
|
||||
setPersistentSettings: async (payload) => {
|
||||
currentState = { ...currentState, ...payload };
|
||||
},
|
||||
setState: async (updates) => {
|
||||
currentState = { ...currentState, ...updates };
|
||||
},
|
||||
throwIfStopped: () => {},
|
||||
upsertMail2925AccountInList: mail2925Utils.upsertMail2925AccountInList,
|
||||
});
|
||||
|
||||
await assert.rejects(
|
||||
() => manager.ensureMail2925MailboxSession({
|
||||
accountId: 'acc-1',
|
||||
forceRelogin: true,
|
||||
actionLabel: '步骤 4:确认 2925 邮箱登录态',
|
||||
}),
|
||||
/流程已被用户停止。/
|
||||
);
|
||||
|
||||
assert.equal(events.stopCalls.length, 1);
|
||||
assert.match(events.stopCalls[0].logMessage, /登录后仍未进入收件箱/);
|
||||
});
|
||||
|
||||
test('handleMail2925LimitReachedError stops immediately when account pool is off even if another account exists', async () => {
|
||||
const source = fs.readFileSync('background/mail-2925-session.js', 'utf8');
|
||||
const globalScope = {};
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundMail2925Session;`)(globalScope);
|
||||
|
||||
let currentState = {
|
||||
mail2925UseAccountPool: false,
|
||||
mail2925Accounts: mail2925Utils.normalizeMail2925Accounts([
|
||||
{ id: 'current', email: 'current@2925.com', password: 'p1', enabled: true, lastUsedAt: 10 },
|
||||
{ id: 'next', email: 'next@2925.com', password: 'p2', enabled: true, lastUsedAt: 20 },
|
||||
]),
|
||||
currentMail2925AccountId: 'current',
|
||||
};
|
||||
const events = {
|
||||
stopCalls: [],
|
||||
sessionChecks: 0,
|
||||
};
|
||||
|
||||
const manager = api.createMail2925SessionManager({
|
||||
addLog: async () => {},
|
||||
broadcastDataUpdate: () => {},
|
||||
chrome: {
|
||||
cookies: {
|
||||
getAll: async () => [],
|
||||
remove: async () => ({ ok: true }),
|
||||
},
|
||||
browsingData: {
|
||||
removeCookies: async () => {},
|
||||
},
|
||||
},
|
||||
findMail2925Account: mail2925Utils.findMail2925Account,
|
||||
getMail2925AccountStatus: mail2925Utils.getMail2925AccountStatus,
|
||||
getState: async () => currentState,
|
||||
isMail2925AccountAvailable: mail2925Utils.isMail2925AccountAvailable,
|
||||
MAIL2925_LIMIT_COOLDOWN_MS: mail2925Utils.MAIL2925_LIMIT_COOLDOWN_MS,
|
||||
normalizeMail2925Account: mail2925Utils.normalizeMail2925Account,
|
||||
normalizeMail2925Accounts: mail2925Utils.normalizeMail2925Accounts,
|
||||
pickMail2925AccountForRun: mail2925Utils.pickMail2925AccountForRun,
|
||||
requestStop: async (options = {}) => {
|
||||
events.stopCalls.push(options);
|
||||
},
|
||||
reuseOrCreateTab: async () => 1,
|
||||
sendToMailContentScriptResilient: async () => {
|
||||
events.sessionChecks += 1;
|
||||
return { loggedIn: true };
|
||||
},
|
||||
setPersistentSettings: async (payload) => {
|
||||
currentState = { ...currentState, ...payload };
|
||||
},
|
||||
setState: async (updates) => {
|
||||
currentState = { ...currentState, ...updates };
|
||||
},
|
||||
throwIfStopped: () => {},
|
||||
upsertMail2925AccountInList: mail2925Utils.upsertMail2925AccountInList,
|
||||
});
|
||||
|
||||
const error = await manager.handleMail2925LimitReachedError(
|
||||
4,
|
||||
new Error('MAIL2925_LIMIT_REACHED::子邮箱已达上限邮箱')
|
||||
);
|
||||
|
||||
assert.equal(error.message, '流程已被用户停止。');
|
||||
assert.equal(events.sessionChecks, 0);
|
||||
assert.equal(events.stopCalls.length, 1);
|
||||
assert.equal(currentState.currentMail2925AccountId, 'current');
|
||||
});
|
||||
|
||||
test('setCurrentMail2925Account persists currentMail2925AccountId for browser restart restore', async () => {
|
||||
const source = fs.readFileSync('background/mail-2925-session.js', 'utf8');
|
||||
const globalScope = {};
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundMail2925Session;`)(globalScope);
|
||||
|
||||
let currentState = {
|
||||
mail2925Accounts: mail2925Utils.normalizeMail2925Accounts([
|
||||
{ id: 'acc-1', email: 'acc1@2925.com', password: 'p1', enabled: true, lastUsedAt: 10 },
|
||||
]),
|
||||
currentMail2925AccountId: null,
|
||||
};
|
||||
const persistedUpdates = [];
|
||||
|
||||
const manager = api.createMail2925SessionManager({
|
||||
addLog: async () => {},
|
||||
broadcastDataUpdate: () => {},
|
||||
chrome: {},
|
||||
findMail2925Account: mail2925Utils.findMail2925Account,
|
||||
getMail2925AccountStatus: mail2925Utils.getMail2925AccountStatus,
|
||||
getState: async () => currentState,
|
||||
isMail2925AccountAvailable: mail2925Utils.isMail2925AccountAvailable,
|
||||
MAIL2925_LIMIT_COOLDOWN_MS: mail2925Utils.MAIL2925_LIMIT_COOLDOWN_MS,
|
||||
normalizeMail2925Account: mail2925Utils.normalizeMail2925Account,
|
||||
normalizeMail2925Accounts: mail2925Utils.normalizeMail2925Accounts,
|
||||
pickMail2925AccountForRun: mail2925Utils.pickMail2925AccountForRun,
|
||||
setPersistentSettings: async (payload) => {
|
||||
persistedUpdates.push(payload);
|
||||
},
|
||||
setState: async (updates) => {
|
||||
currentState = { ...currentState, ...updates };
|
||||
},
|
||||
throwIfStopped: () => {},
|
||||
upsertMail2925AccountInList: mail2925Utils.upsertMail2925AccountInList,
|
||||
});
|
||||
|
||||
await manager.setCurrentMail2925Account('acc-1');
|
||||
|
||||
assert.equal(currentState.currentMail2925AccountId, 'acc-1');
|
||||
assert.deepStrictEqual(persistedUpdates, [
|
||||
{ currentMail2925AccountId: 'acc-1' },
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const signupFlowSource = fs.readFileSync('background/signup-flow-helpers.js', 'utf8');
|
||||
const signupFlowGlobalScope = {};
|
||||
const signupFlowApi = new Function('self', `${signupFlowSource}; return self.MultiPageSignupFlowHelpers;`)(signupFlowGlobalScope);
|
||||
|
||||
test('signup flow helper allocates mail2925 account before generating alias email', async () => {
|
||||
const calls = {
|
||||
ensureMail2925: [],
|
||||
buildAlias: 0,
|
||||
setEmail: [],
|
||||
};
|
||||
|
||||
const helpers = signupFlowApi.createSignupFlowHelpers({
|
||||
buildGeneratedAliasEmail: (state) => {
|
||||
calls.buildAlias += 1;
|
||||
assert.equal(state.currentMail2925AccountId, 'acc-2');
|
||||
return 'demo123456@2925.com';
|
||||
},
|
||||
chrome: { tabs: { get: async () => ({ id: 1, url: 'https://auth.openai.com/create-account/password' }) } },
|
||||
ensureContentScriptReadyOnTab: async () => {},
|
||||
ensureHotmailAccountForFlow: async () => ({}),
|
||||
ensureMail2925AccountForFlow: async (options) => {
|
||||
calls.ensureMail2925.push(options);
|
||||
return { id: 'acc-2', email: 'demo@2925.com' };
|
||||
},
|
||||
ensureLuckmailPurchaseForFlow: async () => ({}),
|
||||
isGeneratedAliasProvider: () => true,
|
||||
isReusableGeneratedAliasEmail: () => false,
|
||||
isHotmailProvider: () => false,
|
||||
isLuckmailProvider: () => false,
|
||||
isSignupEmailVerificationPageUrl: () => false,
|
||||
isSignupPasswordPageUrl: () => true,
|
||||
reuseOrCreateTab: async () => 1,
|
||||
sendToContentScriptResilient: async () => ({}),
|
||||
setEmailState: async (email) => {
|
||||
calls.setEmail.push(email);
|
||||
},
|
||||
SIGNUP_ENTRY_URL: 'https://chatgpt.com/',
|
||||
SIGNUP_PAGE_INJECT_FILES: [],
|
||||
waitForTabUrlMatch: async () => null,
|
||||
});
|
||||
|
||||
const email = await helpers.resolveSignupEmailForFlow({
|
||||
mailProvider: '2925',
|
||||
mail2925UseAccountPool: true,
|
||||
currentMail2925AccountId: 'acc-2',
|
||||
email: '',
|
||||
});
|
||||
|
||||
assert.equal(email, 'demo123456@2925.com');
|
||||
assert.deepStrictEqual(calls.ensureMail2925, [
|
||||
{
|
||||
allowAllocate: true,
|
||||
preferredAccountId: 'acc-2',
|
||||
markUsed: true,
|
||||
},
|
||||
]);
|
||||
assert.equal(calls.buildAlias, 1);
|
||||
assert.deepStrictEqual(calls.setEmail, ['demo123456@2925.com']);
|
||||
});
|
||||
|
||||
test('signup flow helper skips mail2925 account allocation when account pool switch is off', async () => {
|
||||
const calls = {
|
||||
ensureMail2925: 0,
|
||||
};
|
||||
|
||||
const helpers = signupFlowApi.createSignupFlowHelpers({
|
||||
buildGeneratedAliasEmail: () => 'manual123456@2925.com',
|
||||
chrome: { tabs: { get: async () => ({ id: 1, url: 'https://auth.openai.com/create-account/password' }) } },
|
||||
ensureContentScriptReadyOnTab: async () => {},
|
||||
ensureHotmailAccountForFlow: async () => ({}),
|
||||
ensureMail2925AccountForFlow: async () => {
|
||||
calls.ensureMail2925 += 1;
|
||||
return { id: 'acc-2', email: 'demo@2925.com' };
|
||||
},
|
||||
ensureLuckmailPurchaseForFlow: async () => ({}),
|
||||
isGeneratedAliasProvider: () => true,
|
||||
isReusableGeneratedAliasEmail: () => false,
|
||||
isHotmailProvider: () => false,
|
||||
isLuckmailProvider: () => false,
|
||||
isSignupEmailVerificationPageUrl: () => false,
|
||||
isSignupPasswordPageUrl: () => true,
|
||||
reuseOrCreateTab: async () => 1,
|
||||
sendToContentScriptResilient: async () => ({}),
|
||||
setEmailState: async () => {},
|
||||
SIGNUP_ENTRY_URL: 'https://chatgpt.com/',
|
||||
SIGNUP_PAGE_INJECT_FILES: [],
|
||||
waitForTabUrlMatch: async () => null,
|
||||
});
|
||||
|
||||
const email = await helpers.resolveSignupEmailForFlow({
|
||||
mailProvider: '2925',
|
||||
mail2925UseAccountPool: false,
|
||||
currentMail2925AccountId: 'acc-2',
|
||||
email: '',
|
||||
});
|
||||
|
||||
assert.equal(email, 'manual123456@2925.com');
|
||||
assert.equal(calls.ensureMail2925, 0);
|
||||
});
|
||||
@@ -15,6 +15,8 @@ function createRouter(overrides = {}) {
|
||||
notifyCompletions: [],
|
||||
notifyErrors: [],
|
||||
securityBlocks: [],
|
||||
invalidations: [],
|
||||
executedSteps: [],
|
||||
};
|
||||
|
||||
const router = api.createMessageRouter({
|
||||
@@ -41,7 +43,9 @@ function createRouter(overrides = {}) {
|
||||
disableUsedLuckmailPurchases: async () => {},
|
||||
doesStepUseCompletionSignal: () => false,
|
||||
ensureManualInteractionAllowed: async () => ({}),
|
||||
executeStep: async () => {},
|
||||
executeStep: async (step) => {
|
||||
events.executedSteps.push(step);
|
||||
},
|
||||
executeStepViaCompletionSignal: async () => {},
|
||||
exportSettingsBundle: async () => ({}),
|
||||
fetchGeneratedEmail: async () => '',
|
||||
@@ -55,6 +59,7 @@ function createRouter(overrides = {}) {
|
||||
getPendingAutoRunTimerPlan: () => null,
|
||||
getSourceLabel: () => '',
|
||||
getState: async () => overrides.state || { stepStatuses: { 3: 'pending' } },
|
||||
getTabId: overrides.getTabId || (async () => null),
|
||||
getStopRequested: () => false,
|
||||
handleAutoRunLoopUnhandledError: async () => {},
|
||||
handleCloudflareSecurityBlocked: overrides.handleCloudflareSecurityBlocked || (async (error) => {
|
||||
@@ -63,13 +68,16 @@ function createRouter(overrides = {}) {
|
||||
return message.replace(/^CF_SECURITY_BLOCKED::/, '') || message;
|
||||
}),
|
||||
importSettingsBundle: async () => {},
|
||||
invalidateDownstreamAfterStepRestart: async () => {},
|
||||
invalidateDownstreamAfterStepRestart: async (step, options) => {
|
||||
events.invalidations.push({ step, options });
|
||||
},
|
||||
isCloudflareSecurityBlockedError: overrides.isCloudflareSecurityBlockedError || ((error) => /^CF_SECURITY_BLOCKED::/.test(typeof error === 'string' ? error : error?.message || '')),
|
||||
isAutoRunLockedState: () => false,
|
||||
isHotmailProvider: () => false,
|
||||
isLocalhostOAuthCallbackUrl: () => true,
|
||||
isLuckmailProvider: () => false,
|
||||
isStopError: () => false,
|
||||
isTabAlive: overrides.isTabAlive || (async () => false),
|
||||
launchAutoRunTimerPlan: async () => {},
|
||||
listIcloudAliases: async () => [],
|
||||
listLuckmailPurchasesForManagement: async () => [],
|
||||
@@ -226,3 +234,22 @@ test('message router stops the flow and surfaces cloudflare security block error
|
||||
error: '您已触发Cloudflare 安全防护系统',
|
||||
});
|
||||
});
|
||||
|
||||
test('message router blocks manual step 4 execution when signup page tab is missing', async () => {
|
||||
const { router, events } = createRouter({
|
||||
getTabId: async () => null,
|
||||
isTabAlive: async () => false,
|
||||
});
|
||||
|
||||
await assert.rejects(
|
||||
() => router.handleMessage({
|
||||
type: 'EXECUTE_STEP',
|
||||
source: 'sidepanel',
|
||||
payload: { step: 4 },
|
||||
}, {}),
|
||||
/手动执行步骤 4 前,请先执行步骤 1 或步骤 2/
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(events.invalidations, []);
|
||||
assert.deepStrictEqual(events.executedSteps, []);
|
||||
});
|
||||
|
||||
@@ -35,3 +35,23 @@ test('navigation utils treat 126 mail hosts as part of the shared NetEase mail f
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
test('navigation utils support codex2api mode and url normalization', () => {
|
||||
const source = fs.readFileSync('background/navigation-utils.js', 'utf8');
|
||||
const globalScope = {};
|
||||
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundNavigationUtils;`)(globalScope);
|
||||
const utils = api.createNavigationUtils({
|
||||
DEFAULT_CODEX2API_URL: 'http://localhost:8080/admin/accounts',
|
||||
DEFAULT_SUB2API_URL: 'https://sub.example.com/admin/accounts',
|
||||
normalizeLocalCpaStep9Mode: (value) => value,
|
||||
});
|
||||
|
||||
assert.equal(utils.normalizeCodex2ApiUrl('localhost:8080/admin'), 'http://localhost:8080/admin/accounts');
|
||||
assert.equal(
|
||||
utils.normalizeCodex2ApiUrl('https://codex-admin.example.com/'),
|
||||
'https://codex-admin.example.com/admin/accounts'
|
||||
);
|
||||
assert.equal(utils.getPanelMode({ panelMode: 'codex2api' }), 'codex2api');
|
||||
assert.equal(utils.getPanelModeLabel('codex2api'), 'Codex2API');
|
||||
});
|
||||
|
||||
@@ -15,3 +15,59 @@ 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/);
|
||||
});
|
||||
|
||||
test('panel bridge can request codex2api oauth url via protocol', async () => {
|
||||
const source = fs.readFileSync('background/panel-bridge.js', 'utf8');
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = async (url, options = {}) => {
|
||||
assert.equal(url, 'http://localhost:8080/api/admin/oauth/generate-auth-url');
|
||||
assert.equal(options.method, 'POST');
|
||||
assert.equal(options.headers['X-Admin-Key'], 'admin-secret');
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
auth_url: 'https://auth.openai.com/authorize?state=oauth-state',
|
||||
session_id: 'session-123',
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
try {
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundPanelBridge;`)({});
|
||||
const bridge = api.createPanelBridge({
|
||||
addLog: async () => {},
|
||||
chrome: {},
|
||||
closeConflictingTabsForSource: async () => {},
|
||||
ensureContentScriptReadyOnTab: async () => {},
|
||||
getPanelMode: () => 'codex2api',
|
||||
normalizeCodex2ApiUrl: (value) => value ? `http://${value.replace(/^https?:\/\//, '')}`.replace(/\/admin$/, '/admin/accounts') : 'http://localhost:8080/admin/accounts',
|
||||
normalizeSub2ApiUrl: (value) => value,
|
||||
rememberSourceLastUrl: async () => {},
|
||||
sendToContentScript: async () => ({}),
|
||||
sendToContentScriptResilient: async () => ({}),
|
||||
waitForTabUrlFamily: async () => null,
|
||||
DEFAULT_SUB2API_GROUP_NAME: 'codex',
|
||||
SUB2API_STEP1_RESPONSE_TIMEOUT_MS: 90000,
|
||||
});
|
||||
|
||||
const result = await bridge.requestOAuthUrlFromPanel({
|
||||
panelMode: 'codex2api',
|
||||
codex2apiUrl: 'localhost:8080/admin',
|
||||
codex2apiAdminKey: 'admin-secret',
|
||||
}, { logLabel: '步骤 7' });
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
oauthUrl: 'https://auth.openai.com/authorize?state=oauth-state',
|
||||
codex2apiSessionId: 'session-123',
|
||||
codex2apiOAuthState: 'oauth-state',
|
||||
});
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const test = require('node:test');
|
||||
|
||||
test('platform verify module supports codex2api protocol callback exchange', async () => {
|
||||
const source = fs.readFileSync('background/steps/platform-verify.js', 'utf8');
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = async (url, options = {}) => {
|
||||
assert.equal(url, 'http://localhost:8080/api/admin/oauth/exchange-code');
|
||||
assert.equal(options.method, 'POST');
|
||||
assert.equal(options.headers['X-Admin-Key'], 'admin-secret');
|
||||
assert.deepStrictEqual(JSON.parse(options.body), {
|
||||
session_id: 'session-123',
|
||||
code: 'callback-code',
|
||||
state: 'oauth-state',
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
message: 'OAuth 账号 flow@example.com 添加成功',
|
||||
id: 42,
|
||||
email: 'flow@example.com',
|
||||
plan_type: 'pro',
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
try {
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundStep10;`)({});
|
||||
const completed = [];
|
||||
const logs = [];
|
||||
const executor = api.createStep10Executor({
|
||||
addLog: async (message, level = 'info') => {
|
||||
logs.push({ message, level });
|
||||
},
|
||||
chrome: {},
|
||||
closeConflictingTabsForSource: async () => {},
|
||||
completeStepFromBackground: async (step, payload) => {
|
||||
completed.push({ step, payload });
|
||||
},
|
||||
ensureContentScriptReadyOnTab: async () => {},
|
||||
getPanelMode: () => 'codex2api',
|
||||
getTabId: async () => 0,
|
||||
isLocalhostOAuthCallbackUrl: (value) => String(value || '').includes('/auth/callback?code='),
|
||||
isTabAlive: async () => false,
|
||||
normalizeCodex2ApiUrl: () => 'http://localhost:8080/admin/accounts',
|
||||
normalizeSub2ApiUrl: (value) => value,
|
||||
rememberSourceLastUrl: async () => {},
|
||||
reuseOrCreateTab: async () => 0,
|
||||
sendToContentScript: async () => ({}),
|
||||
sendToContentScriptResilient: async () => ({}),
|
||||
shouldBypassStep9ForLocalCpa: () => false,
|
||||
SUB2API_STEP9_RESPONSE_TIMEOUT_MS: 120000,
|
||||
});
|
||||
|
||||
await executor.executeStep10({
|
||||
panelMode: 'codex2api',
|
||||
localhostUrl: 'http://localhost:1455/auth/callback?code=callback-code&state=oauth-state',
|
||||
codex2apiUrl: 'http://localhost:8080/admin/accounts',
|
||||
codex2apiAdminKey: 'admin-secret',
|
||||
codex2apiSessionId: 'session-123',
|
||||
codex2apiOAuthState: 'oauth-state',
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(logs, [
|
||||
{ message: '步骤 10:正在向 Codex2API 提交回调并创建账号...', level: 'info' },
|
||||
{ message: '步骤 10:OAuth 账号 flow@example.com 添加成功', level: 'ok' },
|
||||
]);
|
||||
assert.deepStrictEqual(completed, [
|
||||
{
|
||||
step: 10,
|
||||
payload: {
|
||||
localhostUrl: 'http://localhost:1455/auth/callback?code=callback-code&state=oauth-state',
|
||||
verifiedStatus: 'OAuth 账号 flow@example.com 添加成功',
|
||||
},
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const source = fs.readFileSync('background/steps/fetch-signup-code.js', 'utf8');
|
||||
const globalScope = {};
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundStep4;`)(globalScope);
|
||||
|
||||
test('step 4 passes a fixed 10-minute lookback window to 2925 mailbox polling', async () => {
|
||||
let capturedOptions = null;
|
||||
let ensureCalls = 0;
|
||||
const tabUpdates = [];
|
||||
const tabReuses = [];
|
||||
const realDateNow = Date.now;
|
||||
Date.now = () => 700000;
|
||||
|
||||
const executor = api.createStep4Executor({
|
||||
addLog: async () => {},
|
||||
chrome: {
|
||||
tabs: {
|
||||
update: async (tabId, payload) => {
|
||||
tabUpdates.push({ tabId, payload });
|
||||
},
|
||||
},
|
||||
},
|
||||
completeStepFromBackground: async () => {},
|
||||
confirmCustomVerificationStepBypass: async () => {},
|
||||
ensureMail2925MailboxSession: async () => {
|
||||
ensureCalls += 1;
|
||||
},
|
||||
getMailConfig: () => ({
|
||||
provider: '2925',
|
||||
label: '2925 邮箱',
|
||||
source: 'mail-2925',
|
||||
url: 'https://2925.com',
|
||||
}),
|
||||
getTabId: async () => 1,
|
||||
HOTMAIL_PROVIDER: 'hotmail-api',
|
||||
isTabAlive: async () => true,
|
||||
LUCKMAIL_PROVIDER: 'luckmail-api',
|
||||
CLOUDFLARE_TEMP_EMAIL_PROVIDER: 'cloudflare-temp-email',
|
||||
resolveVerificationStep: async (_step, _state, _mail, options) => {
|
||||
capturedOptions = options;
|
||||
},
|
||||
reuseOrCreateTab: async (source, url) => {
|
||||
tabReuses.push({ source, url });
|
||||
},
|
||||
sendToContentScriptResilient: async () => ({}),
|
||||
shouldUseCustomRegistrationEmail: () => false,
|
||||
STANDARD_MAIL_VERIFICATION_RESEND_INTERVAL_MS: 25000,
|
||||
throwIfStopped: () => {},
|
||||
});
|
||||
|
||||
try {
|
||||
await executor.executeStep4({
|
||||
email: 'user@example.com',
|
||||
password: 'secret',
|
||||
mail2925UseAccountPool: true,
|
||||
});
|
||||
} finally {
|
||||
Date.now = realDateNow;
|
||||
}
|
||||
|
||||
assert.equal(ensureCalls, 1);
|
||||
assert.deepStrictEqual(tabReuses, []);
|
||||
assert.deepStrictEqual(tabUpdates, [
|
||||
{ tabId: 1, payload: { active: true } },
|
||||
]);
|
||||
assert.equal(capturedOptions.filterAfterTimestamp, 100000);
|
||||
assert.equal(capturedOptions.resendIntervalMs, 0);
|
||||
});
|
||||
|
||||
test('step 4 does not request a fresh code first for Cloudflare temp mail', async () => {
|
||||
let capturedOptions = null;
|
||||
const realDateNow = Date.now;
|
||||
Date.now = () => 700000;
|
||||
|
||||
const executor = api.createStep4Executor({
|
||||
addLog: async () => {},
|
||||
chrome: {
|
||||
tabs: {
|
||||
update: async () => {},
|
||||
},
|
||||
},
|
||||
completeStepFromBackground: async () => {},
|
||||
confirmCustomVerificationStepBypass: async () => {},
|
||||
ensureMail2925MailboxSession: async () => {},
|
||||
getMailConfig: () => ({
|
||||
provider: 'cloudflare-temp-email',
|
||||
label: 'Cloudflare Temp Email',
|
||||
source: 'cloudflare-temp-email',
|
||||
url: 'https://temp.peekcart.com',
|
||||
}),
|
||||
getTabId: async () => 1,
|
||||
HOTMAIL_PROVIDER: 'hotmail-api',
|
||||
isTabAlive: async () => true,
|
||||
LUCKMAIL_PROVIDER: 'luckmail-api',
|
||||
CLOUDFLARE_TEMP_EMAIL_PROVIDER: 'cloudflare-temp-email',
|
||||
resolveVerificationStep: async (_step, _state, _mail, options) => {
|
||||
capturedOptions = options;
|
||||
},
|
||||
reuseOrCreateTab: async () => {},
|
||||
sendToContentScriptResilient: async () => ({}),
|
||||
shouldUseCustomRegistrationEmail: () => false,
|
||||
STANDARD_MAIL_VERIFICATION_RESEND_INTERVAL_MS: 25000,
|
||||
throwIfStopped: () => {},
|
||||
});
|
||||
|
||||
try {
|
||||
await executor.executeStep4({
|
||||
email: 'user@example.com',
|
||||
password: 'secret',
|
||||
});
|
||||
} finally {
|
||||
Date.now = realDateNow;
|
||||
}
|
||||
|
||||
assert.equal(capturedOptions.filterAfterTimestamp, 700000);
|
||||
assert.equal(capturedOptions.requestFreshCodeFirst, false);
|
||||
assert.equal(capturedOptions.resendIntervalMs, 25000);
|
||||
});
|
||||
@@ -172,7 +172,93 @@ 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',
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('step 7 stops immediately when management secret is missing', async () => {
|
||||
const source = fs.readFileSync('background/steps/oauth-login.js', 'utf8');
|
||||
const globalScope = {};
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundStep7;`)(globalScope);
|
||||
|
||||
const events = {
|
||||
refreshCalls: 0,
|
||||
sendCalls: 0,
|
||||
logs: [],
|
||||
};
|
||||
|
||||
const executor = api.createStep7Executor({
|
||||
addLog: async (message, level = 'info') => {
|
||||
events.logs.push({ message, level });
|
||||
},
|
||||
completeStepFromBackground: async () => {},
|
||||
getErrorMessage: (error) => error?.message || String(error || ''),
|
||||
getLoginAuthStateLabel: (state) => state || 'unknown',
|
||||
getState: async () => ({ email: 'user@example.com', password: 'secret' }),
|
||||
isStep6RecoverableResult: (result) => result?.step6Outcome === 'recoverable',
|
||||
isStep6SuccessResult: (result) => result?.step6Outcome === 'success',
|
||||
refreshOAuthUrlBeforeStep6: async () => {
|
||||
events.refreshCalls += 1;
|
||||
throw new Error('尚未配置 Codex2API 管理密钥,请先在侧边栏填写。');
|
||||
},
|
||||
reuseOrCreateTab: async () => {},
|
||||
sendToContentScriptResilient: async () => {
|
||||
events.sendCalls += 1;
|
||||
return { step6Outcome: 'success' };
|
||||
},
|
||||
STEP6_MAX_ATTEMPTS: 3,
|
||||
throwIfStopped: () => {},
|
||||
});
|
||||
|
||||
await assert.rejects(
|
||||
() => executor.executeStep7({ email: 'user@example.com', password: 'secret' }),
|
||||
/管理密钥/
|
||||
);
|
||||
|
||||
assert.equal(events.refreshCalls, 1);
|
||||
assert.equal(events.sendCalls, 0);
|
||||
assert.ok(events.logs.some(({ message }) => /管理密钥缺失或错误,不再重试,当前流程停止/.test(message)));
|
||||
assert.ok(!events.logs.some(({ message }) => /准备重试/.test(message)));
|
||||
});
|
||||
|
||||
test('step 7 stops immediately when management secret is invalid', async () => {
|
||||
const source = fs.readFileSync('background/steps/oauth-login.js', 'utf8');
|
||||
const globalScope = {};
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundStep7;`)(globalScope);
|
||||
|
||||
const events = {
|
||||
refreshCalls: 0,
|
||||
logs: [],
|
||||
};
|
||||
|
||||
const executor = api.createStep7Executor({
|
||||
addLog: async (message, level = 'info') => {
|
||||
events.logs.push({ message, level });
|
||||
},
|
||||
completeStepFromBackground: async () => {},
|
||||
getErrorMessage: (error) => error?.message || String(error || ''),
|
||||
getLoginAuthStateLabel: (state) => state || 'unknown',
|
||||
getState: async () => ({ email: 'user@example.com', password: 'secret' }),
|
||||
isStep6RecoverableResult: (result) => result?.step6Outcome === 'recoverable',
|
||||
isStep6SuccessResult: (result) => result?.step6Outcome === 'success',
|
||||
refreshOAuthUrlBeforeStep6: async () => {
|
||||
events.refreshCalls += 1;
|
||||
throw new Error('Codex2API 请求失败(HTTP 401)。X-Admin-Key 无效或未授权。');
|
||||
},
|
||||
reuseOrCreateTab: async () => {},
|
||||
sendToContentScriptResilient: async () => ({ step6Outcome: 'success' }),
|
||||
STEP6_MAX_ATTEMPTS: 3,
|
||||
throwIfStopped: () => {},
|
||||
});
|
||||
|
||||
await assert.rejects(
|
||||
() => executor.executeStep7({ email: 'user@example.com', password: 'secret' }),
|
||||
/401|未授权|无效/
|
||||
);
|
||||
|
||||
assert.equal(events.refreshCalls, 1);
|
||||
assert.ok(events.logs.some(({ message }) => /管理密钥缺失或错误,不再重试,当前流程停止/.test(message)));
|
||||
assert.ok(!events.logs.some(({ message }) => /准备重试/.test(message)));
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
@@ -94,20 +89,32 @@ test('step 8 submits login verification directly without replaying step 7', asyn
|
||||
]);
|
||||
});
|
||||
|
||||
test('step 8 disables resend interval for 2925 mailbox polling', async () => {
|
||||
test('step 8 uses a fixed 10-minute lookback window and disables resend interval for 2925 mailbox polling', async () => {
|
||||
let capturedOptions = null;
|
||||
let ensureCalls = 0;
|
||||
let ensureOptions = null;
|
||||
const tabUpdates = [];
|
||||
const tabReuses = [];
|
||||
const realDateNow = Date.now;
|
||||
Date.now = () => 900000;
|
||||
|
||||
const executor = api.createStep8Executor({
|
||||
addLog: async () => {},
|
||||
chrome: {
|
||||
tabs: {
|
||||
update: async () => {},
|
||||
update: async (tabId, payload) => {
|
||||
tabUpdates.push({ tabId, payload });
|
||||
},
|
||||
},
|
||||
},
|
||||
CLOUDFLARE_TEMP_EMAIL_PROVIDER: 'cloudflare-temp-email',
|
||||
confirmCustomVerificationStepBypass: async () => {},
|
||||
ensureMail2925MailboxSession: async (options) => {
|
||||
ensureCalls += 1;
|
||||
ensureOptions = options;
|
||||
},
|
||||
ensureStep8VerificationPageReady: async () => ({ state: 'verification_page' }),
|
||||
executeStep7: async () => {},
|
||||
rerunStep7ForStep8Recovery: async () => {},
|
||||
getOAuthFlowRemainingMs: async () => 8000,
|
||||
getOAuthFlowStepTimeoutMs: async (defaultTimeoutMs) => Math.min(defaultTimeoutMs, 8000),
|
||||
getMailConfig: () => ({
|
||||
@@ -117,7 +124,15 @@ test('step 8 disables resend interval for 2925 mailbox polling', async () => {
|
||||
url: 'https://2925.com',
|
||||
navigateOnReuse: false,
|
||||
}),
|
||||
getState: async () => ({ email: 'user@example.com', password: 'secret' }),
|
||||
getState: async () => ({
|
||||
email: 'user@example.com',
|
||||
password: 'secret',
|
||||
mail2925UseAccountPool: true,
|
||||
currentMail2925AccountId: 'acc-1',
|
||||
mail2925Accounts: [
|
||||
{ id: 'acc-1', email: 'pool-user@2925.com' },
|
||||
],
|
||||
}),
|
||||
getTabId: async (sourceName) => (sourceName === 'signup-page' ? 1 : 2),
|
||||
HOTMAIL_PROVIDER: 'hotmail-api',
|
||||
isTabAlive: async () => true,
|
||||
@@ -126,22 +141,45 @@ test('step 8 disables resend interval for 2925 mailbox polling', async () => {
|
||||
resolveVerificationStep: async (_step, _state, _mail, options) => {
|
||||
capturedOptions = options;
|
||||
},
|
||||
reuseOrCreateTab: async () => {},
|
||||
reuseOrCreateTab: async (source, url) => {
|
||||
tabReuses.push({ source, url });
|
||||
},
|
||||
setState: async () => {},
|
||||
setStepStatus: async () => {},
|
||||
shouldUseCustomRegistrationEmail: () => false,
|
||||
sleepWithStop: async () => {},
|
||||
STANDARD_MAIL_VERIFICATION_RESEND_INTERVAL_MS: 25000,
|
||||
STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS: 8,
|
||||
throwIfStopped: () => {},
|
||||
});
|
||||
|
||||
await executor.executeStep8({
|
||||
email: 'user@example.com',
|
||||
password: 'secret',
|
||||
oauthUrl: 'https://oauth.example/latest',
|
||||
});
|
||||
try {
|
||||
await executor.executeStep8({
|
||||
email: 'user@example.com',
|
||||
password: 'secret',
|
||||
oauthUrl: 'https://oauth.example/latest',
|
||||
mail2925UseAccountPool: true,
|
||||
currentMail2925AccountId: 'acc-1',
|
||||
mail2925Accounts: [
|
||||
{ id: 'acc-1', email: 'pool-user@2925.com' },
|
||||
],
|
||||
});
|
||||
} finally {
|
||||
Date.now = realDateNow;
|
||||
}
|
||||
|
||||
assert.equal(ensureCalls, 1);
|
||||
assert.deepStrictEqual(ensureOptions, {
|
||||
accountId: 'acc-1',
|
||||
forceRelogin: false,
|
||||
allowLoginWhenOnLoginPage: true,
|
||||
expectedMailboxEmail: 'pool-user@2925.com',
|
||||
actionLabel: 'Step 8: ensure 2925 mailbox session',
|
||||
});
|
||||
assert.deepStrictEqual(tabReuses, []);
|
||||
assert.deepStrictEqual(tabUpdates, [
|
||||
{ tabId: 1, payload: { active: true } },
|
||||
]);
|
||||
assert.equal(capturedOptions.filterAfterTimestamp, 300000);
|
||||
assert.equal(capturedOptions.resendIntervalMs, 0);
|
||||
assert.equal(capturedOptions.targetEmail, '');
|
||||
assert.equal(capturedOptions.beforeSubmit, undefined);
|
||||
@@ -161,7 +199,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 +222,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 +238,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 +254,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 +279,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 +293,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)));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
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('generic stopped record resolves to next unfinished step during execution gap', async () => {
|
||||
const bundle = [
|
||||
extractFunction('getRunningSteps'),
|
||||
extractFunction('inferStoppedRecordStep'),
|
||||
extractFunction('resolveAccountRunRecordStatusForStop'),
|
||||
extractFunction('extractStoppedStepFromRecordStatus'),
|
||||
extractFunction('resolveAccountRunRecordReasonForStop'),
|
||||
extractFunction('appendAndBroadcastAccountRunRecord'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
const STEP_IDS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
||||
const STOP_ERROR_MESSAGE = '流程已被用户停止。';
|
||||
const DEFAULT_STATE = {
|
||||
stepStatuses: Object.fromEntries(STEP_IDS.map((step) => [step, 'pending'])),
|
||||
};
|
||||
let captured = null;
|
||||
const accountRunHistoryHelpers = {
|
||||
appendAccountRunRecord: async (status, state, reason) => {
|
||||
captured = { status, state, reason };
|
||||
return { status, state, reason };
|
||||
},
|
||||
};
|
||||
async function broadcastAccountRunHistoryUpdate() {}
|
||||
async function getState() {
|
||||
return {};
|
||||
}
|
||||
${bundle}
|
||||
return {
|
||||
inferStoppedRecordStep,
|
||||
resolveAccountRunRecordStatusForStop,
|
||||
resolveAccountRunRecordReasonForStop,
|
||||
appendAndBroadcastAccountRunRecord,
|
||||
getCaptured() {
|
||||
return captured;
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
const state = {
|
||||
email: 'user@example.com',
|
||||
password: 'secret',
|
||||
stepStatuses: {
|
||||
1: 'completed',
|
||||
2: 'completed',
|
||||
3: 'completed',
|
||||
4: 'completed',
|
||||
5: 'completed',
|
||||
6: 'completed',
|
||||
7: 'pending',
|
||||
8: 'pending',
|
||||
9: 'pending',
|
||||
10: 'pending',
|
||||
},
|
||||
};
|
||||
|
||||
assert.equal(api.inferStoppedRecordStep(state), 7);
|
||||
assert.equal(api.resolveAccountRunRecordStatusForStop('stopped', state), 'step7_stopped');
|
||||
assert.equal(api.resolveAccountRunRecordReasonForStop('step7_stopped', '流程已被用户停止。'), '步骤 7 已被用户停止。');
|
||||
assert.equal(
|
||||
api.resolveAccountRunRecordReasonForStop('step2_stopped', '步骤 2 已使用邮箱,流程尚未完成。'),
|
||||
'步骤 2 已停止:邮箱已设置,流程尚未完成。'
|
||||
);
|
||||
|
||||
await api.appendAndBroadcastAccountRunRecord('stopped', state, '流程已被用户停止。');
|
||||
assert.deepStrictEqual(api.getCaptured(), {
|
||||
status: 'step7_stopped',
|
||||
state,
|
||||
reason: '步骤 7 已被用户停止。',
|
||||
});
|
||||
});
|
||||
|
||||
test('requestStop appends a stopped record for the next unfinished step when no step is running', async () => {
|
||||
const bundle = [
|
||||
extractFunction('normalizeAutoRunSessionId'),
|
||||
extractFunction('clearCurrentAutoRunSessionId'),
|
||||
extractFunction('cleanupStep8NavigationListeners'),
|
||||
extractFunction('rejectPendingStep8'),
|
||||
extractFunction('getRunningSteps'),
|
||||
extractFunction('inferStoppedRecordStep'),
|
||||
extractFunction('requestStop'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
let stopRequested = false;
|
||||
let autoRunActive = false;
|
||||
let autoRunCurrentRun = 0;
|
||||
let autoRunTotalRuns = 1;
|
||||
let autoRunAttemptRun = 0;
|
||||
let autoRunSessionId = 99;
|
||||
let webNavListener = null;
|
||||
let webNavCommittedListener = null;
|
||||
let step8TabUpdatedListener = null;
|
||||
let step8PendingReject = null;
|
||||
let resumeWaiter = null;
|
||||
const STOP_ERROR_MESSAGE = '流程已被用户停止。';
|
||||
const AUTO_RUN_TIMER_KIND_SCHEDULED_START = 'scheduled_start';
|
||||
const DEFAULT_STATE = {
|
||||
stepStatuses: Object.fromEntries([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((step) => [step, 'pending'])),
|
||||
};
|
||||
const stepWaiters = new Map();
|
||||
const appended = [];
|
||||
const logs = [];
|
||||
const chrome = {
|
||||
webNavigation: {
|
||||
onBeforeNavigate: { removeListener() {} },
|
||||
onCommitted: { removeListener() {} },
|
||||
},
|
||||
tabs: {
|
||||
onUpdated: { removeListener() {} },
|
||||
},
|
||||
};
|
||||
|
||||
function cancelPendingCommands() {}
|
||||
function getPendingAutoRunTimerPlan() {
|
||||
return null;
|
||||
}
|
||||
async function cancelScheduledAutoRun() {}
|
||||
async function clearAutoRunTimerAlarm() {}
|
||||
function clearStopRequest() {
|
||||
stopRequested = false;
|
||||
}
|
||||
async function addLog(message, level) {
|
||||
logs.push({ message, level });
|
||||
}
|
||||
async function broadcastStopToContentScripts() {}
|
||||
async function markRunningStepsStopped() {}
|
||||
async function broadcastAutoRunStatus() {}
|
||||
async function appendAndBroadcastAccountRunRecord(status, state, reason) {
|
||||
appended.push({ status, state, reason });
|
||||
return { status, state, reason };
|
||||
}
|
||||
async function getState() {
|
||||
return {
|
||||
email: 'user@example.com',
|
||||
password: 'secret',
|
||||
stepStatuses: {
|
||||
1: 'completed',
|
||||
2: 'completed',
|
||||
3: 'completed',
|
||||
4: 'completed',
|
||||
5: 'completed',
|
||||
6: 'completed',
|
||||
7: 'pending',
|
||||
8: 'pending',
|
||||
9: 'pending',
|
||||
10: 'pending',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
${bundle}
|
||||
|
||||
return {
|
||||
requestStop,
|
||||
snapshot() {
|
||||
return { appended, logs, stopRequested, autoRunSessionId };
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
await api.requestStop();
|
||||
const state = api.snapshot();
|
||||
|
||||
assert.deepStrictEqual(state.appended, [{
|
||||
status: 'stopped',
|
||||
state: {
|
||||
email: 'user@example.com',
|
||||
password: 'secret',
|
||||
stepStatuses: {
|
||||
1: 'completed',
|
||||
2: 'completed',
|
||||
3: 'completed',
|
||||
4: 'completed',
|
||||
5: 'completed',
|
||||
6: 'completed',
|
||||
7: 'pending',
|
||||
8: 'pending',
|
||||
9: 'pending',
|
||||
10: 'pending',
|
||||
},
|
||||
},
|
||||
reason: '流程已被用户停止。',
|
||||
}]);
|
||||
assert.equal(state.autoRunSessionId, 0);
|
||||
assert.equal(state.stopRequested, true);
|
||||
});
|
||||
@@ -0,0 +1,161 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const source = fs.readFileSync('sidepanel/contribution-content-update-service.js', 'utf8');
|
||||
|
||||
function createContributionContentService(options = {}) {
|
||||
const cache = new Map();
|
||||
const windowObject = {};
|
||||
let fetchCalls = 0;
|
||||
|
||||
const localStorage = {
|
||||
getItem(key) {
|
||||
return cache.has(key) ? cache.get(key) : null;
|
||||
},
|
||||
setItem(key, value) {
|
||||
cache.set(key, String(value));
|
||||
},
|
||||
removeItem(key) {
|
||||
cache.delete(key);
|
||||
},
|
||||
};
|
||||
|
||||
if (options.cachedSnapshot) {
|
||||
cache.set(
|
||||
'multipage-contribution-content-summary-v1',
|
||||
JSON.stringify(options.cachedSnapshot)
|
||||
);
|
||||
}
|
||||
|
||||
const fetchImpl = options.fetchImpl || (async () => ({
|
||||
ok: true,
|
||||
async json() {
|
||||
return {
|
||||
ok: true,
|
||||
items: [],
|
||||
prompt_version: '',
|
||||
has_visible_updates: false,
|
||||
latest_updated_at: '',
|
||||
latest_updated_at_display: '',
|
||||
};
|
||||
},
|
||||
}));
|
||||
|
||||
const wrappedFetch = async (...args) => {
|
||||
fetchCalls += 1;
|
||||
return fetchImpl(...args);
|
||||
};
|
||||
|
||||
const api = new Function(
|
||||
'window',
|
||||
'localStorage',
|
||||
'fetch',
|
||||
'AbortController',
|
||||
'setTimeout',
|
||||
'clearTimeout',
|
||||
`${source}; return window.SidepanelContributionContentService;`
|
||||
)(
|
||||
windowObject,
|
||||
localStorage,
|
||||
wrappedFetch,
|
||||
AbortController,
|
||||
setTimeout,
|
||||
clearTimeout
|
||||
);
|
||||
|
||||
return {
|
||||
api,
|
||||
getFetchCalls() {
|
||||
return fetchCalls;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('getContentUpdateSnapshot returns a prompt version for visible contribution content updates', async () => {
|
||||
const { api } = createContributionContentService({
|
||||
fetchImpl: async () => ({
|
||||
ok: true,
|
||||
async json() {
|
||||
return {
|
||||
ok: true,
|
||||
prompt_version: 'announcement:2026-04-21T12:00:00Z|tutorial:2026-04-21T12:05:00Z',
|
||||
has_visible_updates: true,
|
||||
latest_updated_at: '2026-04-21T12:05:00Z',
|
||||
latest_updated_at_display: '2026-04-21 20:05',
|
||||
items: [
|
||||
{
|
||||
slug: 'announcement',
|
||||
title: '最新公告',
|
||||
is_enabled: true,
|
||||
has_content: true,
|
||||
is_visible: true,
|
||||
updated_at: '2026-04-21T12:00:00Z',
|
||||
updated_at_display: '2026-04-21 20:00',
|
||||
},
|
||||
{
|
||||
slug: 'tutorial',
|
||||
title: '使用教程',
|
||||
is_enabled: true,
|
||||
has_content: true,
|
||||
is_visible: true,
|
||||
updated_at: '2026-04-21T12:05:00Z',
|
||||
updated_at_display: '2026-04-21 20:05',
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const snapshot = await api.getContentUpdateSnapshot();
|
||||
|
||||
assert.equal(snapshot.status, 'update-available');
|
||||
assert.equal(snapshot.promptVersion, 'announcement:2026-04-21T12:00:00Z|tutorial:2026-04-21T12:05:00Z');
|
||||
assert.equal(snapshot.hasVisibleUpdates, true);
|
||||
assert.equal(snapshot.latestUpdatedAt, '2026-04-21T12:05:00Z');
|
||||
assert.equal(snapshot.items.length, 2);
|
||||
assert.deepEqual(
|
||||
snapshot.items.map((item) => [item.slug, item.isVisible]),
|
||||
[['announcement', true], ['tutorial', true]]
|
||||
);
|
||||
});
|
||||
|
||||
test('getContentUpdateSnapshot falls back to cached snapshot when the live request fails', async () => {
|
||||
const cachedSnapshot = {
|
||||
status: 'update-available',
|
||||
promptVersion: 'announcement:2026-04-20T00:00:00Z',
|
||||
hasVisibleUpdates: true,
|
||||
latestUpdatedAt: '2026-04-20T00:00:00Z',
|
||||
latestUpdatedAtDisplay: '2026-04-20 08:00',
|
||||
items: [
|
||||
{
|
||||
slug: 'announcement',
|
||||
title: '站点公告',
|
||||
isEnabled: true,
|
||||
hasContent: true,
|
||||
isVisible: true,
|
||||
updatedAt: '2026-04-20T00:00:00Z',
|
||||
updatedAtDisplay: '2026-04-20 08:00',
|
||||
},
|
||||
],
|
||||
portalUrl: 'https://apikey.qzz.io',
|
||||
apiUrl: 'https://apikey.qzz.io/api/content-summary',
|
||||
checkedAt: Date.now() - 1000,
|
||||
};
|
||||
|
||||
const { api, getFetchCalls } = createContributionContentService({
|
||||
cachedSnapshot,
|
||||
fetchImpl: async () => {
|
||||
throw new Error('offline');
|
||||
},
|
||||
});
|
||||
|
||||
const snapshot = await api.getContentUpdateSnapshot();
|
||||
|
||||
assert.equal(getFetchCalls(), 1);
|
||||
assert.equal(snapshot.fromCache, true);
|
||||
assert.equal(snapshot.promptVersion, cachedSnapshot.promptVersion);
|
||||
assert.equal(snapshot.errorMessage, 'offline');
|
||||
assert.equal(snapshot.items[0].slug, 'announcement');
|
||||
});
|
||||
@@ -0,0 +1,663 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const source = fs.readFileSync('content/mail-163.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('findMailItems falls back to visible aria-label mail rows when legacy selector is missing', () => {
|
||||
const bundle = [
|
||||
extractFunction('normalizeText'),
|
||||
extractFunction('isVisibleNode'),
|
||||
extractFunction('isLikelyMailItemNode'),
|
||||
extractFunction('findMailItems'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
const mailRow = {
|
||||
hidden: false,
|
||||
textContent: 'Your temporary ChatGPT verification code 911113',
|
||||
getAttribute(name) {
|
||||
if (name === 'aria-label') return 'Your temporary ChatGPT verification code 911113 发件人 OpenAI';
|
||||
return '';
|
||||
},
|
||||
getBoundingClientRect() {
|
||||
return { width: 600, height: 48 };
|
||||
},
|
||||
matches() {
|
||||
return false;
|
||||
},
|
||||
querySelector() {
|
||||
return null;
|
||||
},
|
||||
};
|
||||
|
||||
const document = {
|
||||
querySelectorAll(selector) {
|
||||
if (selector === 'div[sign="letter"]') return [];
|
||||
if (selector === '[role="option"][aria-label]') return [mailRow];
|
||||
return [];
|
||||
},
|
||||
};
|
||||
|
||||
const window = {
|
||||
getComputedStyle() {
|
||||
return { display: 'block', visibility: 'visible' };
|
||||
},
|
||||
};
|
||||
|
||||
${bundle}
|
||||
|
||||
return { findMailItems };
|
||||
`)();
|
||||
|
||||
const rows = api.findMailItems();
|
||||
assert.equal(rows.length, 1);
|
||||
});
|
||||
|
||||
test('getMailTimestamp parses visible hh:mm text even when no title attribute exists', () => {
|
||||
const bundle = [
|
||||
extractFunction('normalizeText'),
|
||||
extractFunction('parseMail163Timestamp'),
|
||||
extractFunction('isLikelyMailTimestampText'),
|
||||
extractFunction('collectMailTimestampCandidates'),
|
||||
extractFunction('getMailTimestamp'),
|
||||
].join('\n');
|
||||
|
||||
const timestamp = new Function(`
|
||||
const item = {
|
||||
getAttribute() {
|
||||
return '';
|
||||
},
|
||||
querySelectorAll(selector) {
|
||||
if (selector === '.e00, [title], [aria-label], time, [class*="time"], [class*="date"]') {
|
||||
return [];
|
||||
}
|
||||
if (selector === 'span, div, td, strong, b') {
|
||||
return [
|
||||
{
|
||||
textContent: '22:22',
|
||||
getAttribute() {
|
||||
return '';
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
};
|
||||
|
||||
${bundle}
|
||||
|
||||
return getMailTimestamp(item);
|
||||
`)();
|
||||
|
||||
const now = new Date();
|
||||
const expected = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 22, 22, 0, 0).getTime();
|
||||
assert.equal(timestamp, expected);
|
||||
});
|
||||
|
||||
test('readOpenedMailText prefers opened body content that contains the verification code', () => {
|
||||
const bundle = [
|
||||
extractFunction('normalizeText'),
|
||||
extractFunction('collectOpenedMailTextCandidates'),
|
||||
extractFunction('selectOpenedMailTextCandidate'),
|
||||
extractFunction('readOpenedMailText'),
|
||||
extractFunction('extractVerificationCode'),
|
||||
].join('\n');
|
||||
|
||||
const text = new Function(`
|
||||
const item = {
|
||||
querySelectorAll() {
|
||||
return [];
|
||||
},
|
||||
};
|
||||
|
||||
function getMailSubjectText() {
|
||||
return 'Your temporary ChatGPT login code';
|
||||
}
|
||||
|
||||
function getMailSenderText() {
|
||||
return 'OpenAI';
|
||||
}
|
||||
|
||||
const document = {
|
||||
querySelectorAll(selector) {
|
||||
if (selector === 'iframe') {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{ innerText: 'Your temporary ChatGPT login code', textContent: 'Your temporary ChatGPT login code' },
|
||||
{ innerText: 'Enter this temporary verification code to continue: 214203', textContent: 'Enter this temporary verification code to continue: 214203' },
|
||||
];
|
||||
},
|
||||
body: {
|
||||
innerText: 'fallback body',
|
||||
textContent: 'fallback body',
|
||||
},
|
||||
};
|
||||
|
||||
${bundle}
|
||||
|
||||
return readOpenedMailText(item);
|
||||
`)();
|
||||
|
||||
assert.match(text, /214203/);
|
||||
});
|
||||
|
||||
test('openMailAndGetMessageText reads opened body text and returns to inbox', async () => {
|
||||
const bundle = [
|
||||
extractFunction('normalizeText'),
|
||||
extractFunction('collectOpenedMailTextCandidates'),
|
||||
extractFunction('selectOpenedMailTextCandidate'),
|
||||
extractFunction('readOpenedMailText'),
|
||||
extractFunction('returnToInbox'),
|
||||
extractFunction('openMailAndGetMessageText'),
|
||||
extractFunction('extractVerificationCode'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
let inInbox = true;
|
||||
let clickCount = 0;
|
||||
const mailItem = {
|
||||
click() {
|
||||
clickCount += 1;
|
||||
inInbox = false;
|
||||
},
|
||||
};
|
||||
const inboxLink = {
|
||||
click() {
|
||||
inInbox = true;
|
||||
},
|
||||
};
|
||||
|
||||
function getMailSubjectText() {
|
||||
return 'Your temporary ChatGPT login code';
|
||||
}
|
||||
|
||||
function getMailSenderText() {
|
||||
return 'OpenAI';
|
||||
}
|
||||
|
||||
const document = {
|
||||
querySelector(selector) {
|
||||
if (selector === '.nui-tree-item-text[title="收件箱"], [title="收件箱"]') return inboxLink;
|
||||
return null;
|
||||
},
|
||||
querySelectorAll(selector) {
|
||||
if (selector === 'iframe') {
|
||||
return [];
|
||||
}
|
||||
return inInbox ? [] : [{ innerText: 'Enter this temporary verification code to continue: 214203', textContent: 'Enter this temporary verification code to continue: 214203' }];
|
||||
},
|
||||
body: {
|
||||
innerText: '',
|
||||
textContent: '',
|
||||
},
|
||||
};
|
||||
|
||||
function findMailItems() {
|
||||
return inInbox ? [mailItem] : [];
|
||||
}
|
||||
|
||||
async function sleep() {}
|
||||
|
||||
${bundle}
|
||||
|
||||
return {
|
||||
openMailAndGetMessageText,
|
||||
getClickCount: () => clickCount,
|
||||
isInInbox: () => inInbox,
|
||||
mailItem,
|
||||
};
|
||||
`)();
|
||||
|
||||
const text = await api.openMailAndGetMessageText(api.mailItem);
|
||||
assert.match(text, /214203/);
|
||||
assert.equal(api.getClickCount(), 1);
|
||||
assert.equal(api.isInInbox(), true);
|
||||
});
|
||||
|
||||
test('openMailAndGetMessageText ignores stale pre-open text that contains an old code', async () => {
|
||||
const bundle = [
|
||||
extractFunction('normalizeText'),
|
||||
extractFunction('collectOpenedMailTextCandidates'),
|
||||
extractFunction('selectOpenedMailTextCandidate'),
|
||||
extractFunction('readOpenedMailText'),
|
||||
extractFunction('returnToInbox'),
|
||||
extractFunction('openMailAndGetMessageText'),
|
||||
extractFunction('extractVerificationCode'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
let stage = 'before';
|
||||
const oldText = 'OpenAI Your temporary ChatGPT login code. Ignore this old code 111111. '.repeat(10);
|
||||
const newText = 'OpenAI Your temporary ChatGPT login code. Your new code is 222222.';
|
||||
const mailItem = {
|
||||
click() {
|
||||
stage = 'after';
|
||||
},
|
||||
};
|
||||
const inboxLink = {
|
||||
click() {
|
||||
stage = 'done';
|
||||
},
|
||||
};
|
||||
|
||||
function getMailSubjectText() {
|
||||
return 'Your temporary ChatGPT login code';
|
||||
}
|
||||
|
||||
function getMailSenderText() {
|
||||
return 'OpenAI';
|
||||
}
|
||||
|
||||
const document = {
|
||||
querySelector(selector) {
|
||||
if (selector === '.nui-tree-item-text[title="收件箱"], [title="收件箱"]') return inboxLink;
|
||||
return null;
|
||||
},
|
||||
querySelectorAll(selector) {
|
||||
if (selector === 'iframe') {
|
||||
return [];
|
||||
}
|
||||
if (stage === 'before') {
|
||||
return [{ innerText: oldText, textContent: oldText }];
|
||||
}
|
||||
if (stage === 'after') {
|
||||
return [
|
||||
{ innerText: oldText, textContent: oldText },
|
||||
{ innerText: newText, textContent: newText },
|
||||
];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
body: {
|
||||
innerText: '',
|
||||
textContent: '',
|
||||
},
|
||||
};
|
||||
|
||||
function findMailItems() {
|
||||
return stage === 'done' ? [mailItem] : [];
|
||||
}
|
||||
|
||||
async function sleep() {}
|
||||
|
||||
${bundle}
|
||||
|
||||
return { openMailAndGetMessageText, mailItem };
|
||||
`)();
|
||||
|
||||
const text = await api.openMailAndGetMessageText(api.mailItem);
|
||||
assert.match(text, /222222/);
|
||||
assert.doesNotMatch(text, /111111/);
|
||||
});
|
||||
|
||||
test('handlePollEmail ignores same-minute old snapshot mail before fallback', async () => {
|
||||
const bundle = [
|
||||
extractFunction('normalizeText'),
|
||||
extractFunction('normalizeMinuteTimestamp'),
|
||||
extractFunction('handlePollEmail'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
let currentItems = [{ id: 'old-mail' }];
|
||||
const seenCodes = new Set();
|
||||
|
||||
function findMailItems() {
|
||||
return currentItems;
|
||||
}
|
||||
|
||||
function getCurrentMailIds(items = []) {
|
||||
return new Set((items.length ? items : currentItems).map((item) => item.id));
|
||||
}
|
||||
|
||||
function getMailItemId(item) {
|
||||
return item.id;
|
||||
}
|
||||
|
||||
function getMailTimestamp() {
|
||||
return new Date(2026, 3, 22, 22, 22, 0, 0).getTime();
|
||||
}
|
||||
|
||||
function getMailSenderText() {
|
||||
return 'OpenAI';
|
||||
}
|
||||
|
||||
function getMailSubjectText() {
|
||||
return 'Your temporary ChatGPT verification code';
|
||||
}
|
||||
|
||||
function getMailRowText() {
|
||||
return 'Your temporary ChatGPT verification code 911113 发件人 OpenAI';
|
||||
}
|
||||
|
||||
function extractVerificationCode() {
|
||||
return '911113';
|
||||
}
|
||||
|
||||
async function waitForElement() {
|
||||
return { click() {} };
|
||||
}
|
||||
async function refreshInbox() {}
|
||||
async function sleep() {}
|
||||
function log() {}
|
||||
function persistSeenCodes() {}
|
||||
function scheduleEmailCleanup() {}
|
||||
|
||||
${bundle}
|
||||
|
||||
return { handlePollEmail };
|
||||
`)();
|
||||
|
||||
await assert.rejects(
|
||||
() => api.handlePollEmail(4, {
|
||||
senderFilters: ['openai'],
|
||||
subjectFilters: ['verification'],
|
||||
maxAttempts: 1,
|
||||
intervalMs: 1,
|
||||
filterAfterTimestamp: new Date(2026, 3, 22, 22, 22, 40, 0).getTime(),
|
||||
}),
|
||||
/未在 163 邮箱中找到新的匹配邮件/
|
||||
);
|
||||
});
|
||||
|
||||
test('handlePollEmail accepts a new same-minute mail that appears after the snapshot', async () => {
|
||||
const bundle = [
|
||||
extractFunction('normalizeText'),
|
||||
extractFunction('normalizeMinuteTimestamp'),
|
||||
extractFunction('handlePollEmail'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
const oldMail = {
|
||||
id: 'old-mail',
|
||||
getAttribute(name) {
|
||||
if (name === 'aria-label') return 'Old verification mail 111111 发件人 OpenAI';
|
||||
return '';
|
||||
},
|
||||
};
|
||||
const newMail = {
|
||||
id: 'new-mail',
|
||||
getAttribute(name) {
|
||||
if (name === 'aria-label') return 'Your temporary ChatGPT verification code 654321 发件人 OpenAI';
|
||||
return '';
|
||||
},
|
||||
};
|
||||
let refreshCount = 0;
|
||||
let currentItems = [oldMail];
|
||||
const seenCodes = new Set();
|
||||
|
||||
function findMailItems() {
|
||||
return currentItems;
|
||||
}
|
||||
|
||||
function getCurrentMailIds(items = []) {
|
||||
return new Set((items.length ? items : currentItems).map((item) => item.id));
|
||||
}
|
||||
|
||||
function getMailItemId(item) {
|
||||
return item.id;
|
||||
}
|
||||
|
||||
function getMailTimestamp() {
|
||||
return new Date(2026, 3, 22, 22, 22, 0, 0).getTime();
|
||||
}
|
||||
|
||||
function getMailSenderText() {
|
||||
return 'OpenAI';
|
||||
}
|
||||
|
||||
function getMailSubjectText(item) {
|
||||
return item.id === 'new-mail' ? 'Your temporary ChatGPT verification code' : 'Old verification mail';
|
||||
}
|
||||
|
||||
function getMailRowText(item) {
|
||||
return item.id === 'new-mail'
|
||||
? 'Your temporary ChatGPT verification code 654321 发件人 OpenAI'
|
||||
: 'Old verification mail 111111 发件人 OpenAI';
|
||||
}
|
||||
|
||||
function extractVerificationCode(text) {
|
||||
const match = String(text || '').match(/(\\d{6})/);
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
async function waitForElement() {
|
||||
return { click() {} };
|
||||
}
|
||||
async function refreshInbox() {
|
||||
refreshCount += 1;
|
||||
if (refreshCount >= 1) {
|
||||
currentItems = [oldMail, newMail];
|
||||
}
|
||||
}
|
||||
async function sleep() {}
|
||||
function log() {}
|
||||
function persistSeenCodes() {}
|
||||
function scheduleEmailCleanup() {}
|
||||
|
||||
${bundle}
|
||||
|
||||
return { handlePollEmail };
|
||||
`)();
|
||||
|
||||
const result = await api.handlePollEmail(4, {
|
||||
senderFilters: ['openai'],
|
||||
subjectFilters: ['verification'],
|
||||
maxAttempts: 2,
|
||||
intervalMs: 1,
|
||||
filterAfterTimestamp: new Date(2026, 3, 22, 22, 22, 40, 0).getTime(),
|
||||
});
|
||||
|
||||
assert.equal(result.code, '654321');
|
||||
assert.equal(result.mailId, 'new-mail');
|
||||
});
|
||||
|
||||
test('handlePollEmail falls back to row text when the subject node is missing', async () => {
|
||||
const bundle = [
|
||||
extractFunction('normalizeText'),
|
||||
extractFunction('normalizeMinuteTimestamp'),
|
||||
extractFunction('handlePollEmail'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
const matchingMail = {
|
||||
id: 'mail-1',
|
||||
getAttribute(name) {
|
||||
if (name === 'aria-label') return 'OpenAI Your temporary ChatGPT verification code 123456';
|
||||
return '';
|
||||
},
|
||||
};
|
||||
const seenCodes = new Set();
|
||||
|
||||
function findMailItems() {
|
||||
return [matchingMail];
|
||||
}
|
||||
|
||||
function getCurrentMailIds() {
|
||||
return new Set();
|
||||
}
|
||||
|
||||
function getMailItemId(item) {
|
||||
return item.id;
|
||||
}
|
||||
|
||||
function getMailTimestamp() {
|
||||
return new Date(2026, 3, 22, 22, 22, 0, 0).getTime();
|
||||
}
|
||||
|
||||
function getMailSenderText() {
|
||||
return '';
|
||||
}
|
||||
|
||||
function getMailSubjectText() {
|
||||
return '';
|
||||
}
|
||||
|
||||
function getMailRowText() {
|
||||
return 'OpenAI Your temporary ChatGPT verification code 123456';
|
||||
}
|
||||
|
||||
function extractVerificationCode(text) {
|
||||
const match = String(text || '').match(/(\\d{6})/);
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
async function waitForElement() {
|
||||
return { click() {} };
|
||||
}
|
||||
async function refreshInbox() {}
|
||||
async function sleep() {}
|
||||
function log() {}
|
||||
function persistSeenCodes() {}
|
||||
function scheduleEmailCleanup() {}
|
||||
async function openMailAndGetMessageText() {
|
||||
return '';
|
||||
}
|
||||
|
||||
${bundle}
|
||||
|
||||
return { handlePollEmail };
|
||||
`)();
|
||||
|
||||
const result = await api.handlePollEmail(8, {
|
||||
senderFilters: ['openai'],
|
||||
subjectFilters: ['verification'],
|
||||
maxAttempts: 1,
|
||||
intervalMs: 1,
|
||||
filterAfterTimestamp: 0,
|
||||
});
|
||||
|
||||
assert.equal(result.code, '123456');
|
||||
assert.equal(result.mailId, 'mail-1');
|
||||
});
|
||||
|
||||
test('handlePollEmail opens matching mail body when preview has no code', async () => {
|
||||
const bundle = [
|
||||
extractFunction('normalizeText'),
|
||||
extractFunction('normalizeMinuteTimestamp'),
|
||||
extractFunction('handlePollEmail'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
const matchingMail = {
|
||||
id: 'mail-body-1',
|
||||
getAttribute(name) {
|
||||
if (name === 'aria-label') return 'OpenAI Your temporary ChatGPT login code';
|
||||
return '';
|
||||
},
|
||||
};
|
||||
const seenCodes = new Set();
|
||||
let openedCount = 0;
|
||||
|
||||
function findMailItems() {
|
||||
return [matchingMail];
|
||||
}
|
||||
|
||||
function getCurrentMailIds() {
|
||||
return new Set();
|
||||
}
|
||||
|
||||
function getMailItemId(item) {
|
||||
return item.id;
|
||||
}
|
||||
|
||||
function getMailTimestamp() {
|
||||
return new Date(2026, 3, 22, 22, 49, 0, 0).getTime();
|
||||
}
|
||||
|
||||
function getMailSenderText() {
|
||||
return 'OpenAI';
|
||||
}
|
||||
|
||||
function getMailSubjectText() {
|
||||
return 'Your temporary ChatGPT login code';
|
||||
}
|
||||
|
||||
function getMailRowText() {
|
||||
return 'OpenAI Your temporary ChatGPT login code';
|
||||
}
|
||||
|
||||
function extractVerificationCode(text) {
|
||||
const match = String(text || '').match(/(\\d{6})/);
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
async function waitForElement() {
|
||||
return { click() {} };
|
||||
}
|
||||
async function refreshInbox() {}
|
||||
async function sleep() {}
|
||||
function log() {}
|
||||
function persistSeenCodes() {}
|
||||
function scheduleEmailCleanup() {}
|
||||
async function openMailAndGetMessageText() {
|
||||
openedCount += 1;
|
||||
return 'Enter this temporary verification code to continue: 214203';
|
||||
}
|
||||
|
||||
${bundle}
|
||||
|
||||
return { handlePollEmail, getOpenedCount: () => openedCount };
|
||||
`)();
|
||||
|
||||
const result = await api.handlePollEmail(8, {
|
||||
senderFilters: ['openai'],
|
||||
subjectFilters: ['verification', 'login'],
|
||||
maxAttempts: 1,
|
||||
intervalMs: 1,
|
||||
filterAfterTimestamp: 0,
|
||||
});
|
||||
|
||||
assert.equal(result.code, '214203');
|
||||
assert.equal(result.mailId, 'mail-body-1');
|
||||
assert.equal(api.getOpenedCount(), 1);
|
||||
});
|
||||
@@ -4,6 +4,77 @@ const fs = require('node:fs');
|
||||
|
||||
const source = fs.readFileSync('content/mail-2925.js', 'utf8');
|
||||
|
||||
test('ensureMail2925Session waits at most 40 seconds for mailbox after clicking login', () => {
|
||||
assert.match(source, /waitForMail2925View\('mailbox',\s*40000\)/);
|
||||
});
|
||||
|
||||
test('ensureMail2925Session waits 1 second after filling credentials before clicking login', () => {
|
||||
assert.match(source, /fillInput\(passwordInput,\s*password\);[\s\S]*?await sleep\(200\);[\s\S]*?await sleep\(1000\);[\s\S]*?simulateClick\(loginButton\);/);
|
||||
});
|
||||
|
||||
test('detectMail2925ViewState treats top mailbox email as mailbox view', () => {
|
||||
const bundle = [
|
||||
extractFunction('normalizeNodeText'),
|
||||
extractFunction('isVisibleNode'),
|
||||
extractFunction('isMailItemNode'),
|
||||
extractFunction('resolveActionTarget'),
|
||||
extractFunction('findMailItems'),
|
||||
extractFunction('extractEmails'),
|
||||
extractFunction('getMail2925DisplayedMailboxEmail'),
|
||||
extractFunction('detectMail2925ViewState'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
const MAIL_ITEM_SELECTORS = ['.mail-item'];
|
||||
const MAIL_ITEM_SELECTOR_GROUP = '.mail-item';
|
||||
const MAIL2925_REMEMBER_LOGIN_PATTERNS = [];
|
||||
const MAIL2925_AGREEMENT_PATTERNS = [];
|
||||
const document = {
|
||||
querySelectorAll(selector) {
|
||||
if (selector === '.mail-item') return [];
|
||||
if (selector === 'body *') return [headerEmail, wrongHeader];
|
||||
if (selector === '.right-header' || selector.includes('right-header')) return [headerEmail];
|
||||
if (selector.includes('[class*="user"]')) return [];
|
||||
return [];
|
||||
},
|
||||
body: {
|
||||
innerText: 'QLHazycoder qlhazycoder@2925.com tm1.openai.com@foo.example',
|
||||
textContent: 'QLHazycoder qlhazycoder@2925.com tm1.openai.com@foo.example',
|
||||
},
|
||||
};
|
||||
const window = {
|
||||
innerHeight: 900,
|
||||
getComputedStyle() {
|
||||
return { display: 'block', visibility: 'visible' };
|
||||
},
|
||||
};
|
||||
const headerEmail = {
|
||||
hidden: false,
|
||||
textContent: 'qlhazycoder@2925.com',
|
||||
innerText: 'qlhazycoder@2925.com',
|
||||
getBoundingClientRect() { return { top: 40, left: 400, width: 120, height: 20 }; },
|
||||
closest() { return null; },
|
||||
};
|
||||
const wrongHeader = {
|
||||
hidden: false,
|
||||
textContent: 'tm1.openai.com@foo.example',
|
||||
innerText: 'tm1.openai.com@foo.example',
|
||||
getBoundingClientRect() { return { top: 48, left: 430, width: 150, height: 20 }; },
|
||||
closest() { return null; },
|
||||
};
|
||||
function detectMail2925LimitMessage() { return ''; }
|
||||
function findMail2925LoginPasswordInput() { return null; }
|
||||
function findMail2925LoginEmailInput() { return null; }
|
||||
function getPageTextSample() { return 'qlhazycoder@2925.com'; }
|
||||
${bundle}
|
||||
return { detectMail2925ViewState };
|
||||
`)();
|
||||
|
||||
const state = api.detectMail2925ViewState();
|
||||
assert.equal(state.view, 'mailbox');
|
||||
assert.equal(state.mailboxEmail, 'qlhazycoder@2925.com');
|
||||
});
|
||||
|
||||
function extractFunction(name) {
|
||||
const markers = [`async function ${name}(`, `function ${name}(`];
|
||||
const start = markers
|
||||
@@ -52,7 +123,10 @@ function extractFunction(name) {
|
||||
}
|
||||
|
||||
test('handlePollEmail establishes a baseline after opening from detail view and only picks mail from a later refresh', async () => {
|
||||
const bundle = extractFunction('handlePollEmail');
|
||||
const bundle = [
|
||||
extractFunction('normalizeMinuteTimestamp'),
|
||||
extractFunction('handlePollEmail'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
let state = 'detail';
|
||||
@@ -60,13 +134,22 @@ let refreshCalls = 0;
|
||||
const clickOrder = [];
|
||||
const readAndDeleteCalls = [];
|
||||
const seenCodes = new Set();
|
||||
const deletedMailIds = new Set();
|
||||
const baselineMail = { id: 'baseline', text: 'OpenAI newsletter without code' };
|
||||
const newMail = { id: 'new', text: 'OpenAI verification code 654321' };
|
||||
|
||||
function findMailItems() {
|
||||
if (state === 'detail') return [];
|
||||
if (state === 'baseline') return [baselineMail];
|
||||
return [baselineMail, newMail];
|
||||
const items = [];
|
||||
if (state === 'detail') return items;
|
||||
if (state === 'baseline' || state === 'with-new') {
|
||||
if (!deletedMailIds.has('baseline')) {
|
||||
items.push(baselineMail);
|
||||
}
|
||||
}
|
||||
if (state === 'with-new' && !deletedMailIds.has('new')) {
|
||||
items.push(newMail);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
function getMailItemId(item) {
|
||||
@@ -99,7 +182,9 @@ async function sleepRandom() {}
|
||||
|
||||
async function returnToInbox() {
|
||||
clickOrder.push('inbox');
|
||||
state = 'baseline';
|
||||
if (state === 'detail') {
|
||||
state = 'baseline';
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -113,6 +198,7 @@ async function refreshInbox() {
|
||||
|
||||
async function openMailAndDeleteAfterRead(item) {
|
||||
readAndDeleteCalls.push(item.id);
|
||||
deletedMailIds.add(item.id);
|
||||
return item.id === 'new' ? 'Your ChatGPT code is 654321' : 'No code here';
|
||||
}
|
||||
|
||||
@@ -142,11 +228,14 @@ return {
|
||||
|
||||
assert.equal(result.code, '654321');
|
||||
assert.deepEqual(api.getClickOrder(), ['inbox', 'refresh', 'inbox', 'refresh']);
|
||||
assert.deepEqual(api.getReadAndDeleteCalls(), ['new']);
|
||||
assert.deepEqual(api.getReadAndDeleteCalls(), ['baseline', 'new']);
|
||||
});
|
||||
|
||||
test('handlePollEmail ignores targetEmail and still tests any matching ChatGPT mail', async () => {
|
||||
const bundle = extractFunction('handlePollEmail');
|
||||
test('handlePollEmail keeps ignoring targetEmail when receive-mode matching is disabled', async () => {
|
||||
const bundle = [
|
||||
extractFunction('normalizeMinuteTimestamp'),
|
||||
extractFunction('handlePollEmail'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
let state = 'empty';
|
||||
@@ -220,12 +309,191 @@ return {
|
||||
maxAttempts: 4,
|
||||
intervalMs: 1,
|
||||
targetEmail: 'expected@example.com',
|
||||
mail2925MatchTargetEmail: false,
|
||||
});
|
||||
|
||||
assert.equal(result.code, '112233');
|
||||
assert.deepEqual(api.getReadAndDeleteCalls(), ['mail-1']);
|
||||
});
|
||||
|
||||
test('handlePollEmail skips explicit mismatched target emails when receive-mode matching is enabled', async () => {
|
||||
const bundle = [
|
||||
extractFunction('extractEmails'),
|
||||
extractFunction('emailMatchesTarget'),
|
||||
extractFunction('getTargetEmailMatchState'),
|
||||
extractFunction('normalizeMinuteTimestamp'),
|
||||
extractFunction('handlePollEmail'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
let state = 'ready';
|
||||
const seenCodes = new Set();
|
||||
const readAndDeleteCalls = [];
|
||||
const mismatchMail = {
|
||||
id: 'mail-1',
|
||||
text: 'ChatGPT verification code 112233 for another.user@example.com',
|
||||
};
|
||||
const targetMail = {
|
||||
id: 'mail-2',
|
||||
text: 'ChatGPT verification code 445566 for expected@example.com',
|
||||
};
|
||||
|
||||
function findMailItems() {
|
||||
return state === 'ready' ? [mismatchMail, targetMail] : [];
|
||||
}
|
||||
|
||||
function getMailItemId(item) {
|
||||
return item.id;
|
||||
}
|
||||
|
||||
function getCurrentMailIds(items = []) {
|
||||
return new Set(items.map((item) => item.id));
|
||||
}
|
||||
|
||||
function parseMailItemTimestamp() {
|
||||
return Date.now();
|
||||
}
|
||||
|
||||
function matchesMailFilters(text) {
|
||||
return /chatgpt|openai|verification/i.test(String(text || ''));
|
||||
}
|
||||
|
||||
function getMailItemText(item) {
|
||||
return item.text;
|
||||
}
|
||||
|
||||
function extractVerificationCode(text) {
|
||||
const match = String(text || '').match(/(\\d{6})/);
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
async function sleep() {}
|
||||
async function sleepRandom() {}
|
||||
async function returnToInbox() {
|
||||
return true;
|
||||
}
|
||||
async function refreshInbox() {}
|
||||
|
||||
async function openMailAndDeleteAfterRead(item) {
|
||||
readAndDeleteCalls.push(item.id);
|
||||
return item.text;
|
||||
}
|
||||
|
||||
async function ensureSeenCodesSession() {}
|
||||
function persistSeenCodes() {}
|
||||
function log() {}
|
||||
|
||||
${bundle}
|
||||
|
||||
return {
|
||||
handlePollEmail,
|
||||
getReadAndDeleteCalls() {
|
||||
return readAndDeleteCalls.slice();
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
const result = await api.handlePollEmail(8, {
|
||||
senderFilters: ['chatgpt'],
|
||||
subjectFilters: ['verification'],
|
||||
maxAttempts: 1,
|
||||
intervalMs: 1,
|
||||
targetEmail: 'expected@example.com',
|
||||
mail2925MatchTargetEmail: true,
|
||||
});
|
||||
|
||||
assert.equal(result.code, '445566');
|
||||
assert.deepEqual(api.getReadAndDeleteCalls(), ['mail-2']);
|
||||
});
|
||||
|
||||
test('handlePollEmail only accepts 2925 mails inside the fixed lookback window', async () => {
|
||||
const bundle = [
|
||||
extractFunction('normalizeMinuteTimestamp'),
|
||||
extractFunction('handlePollEmail'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
let state = 'ready';
|
||||
const seenCodes = new Set();
|
||||
const readAndDeleteCalls = [];
|
||||
const oldMail = {
|
||||
id: 'mail-old',
|
||||
text: 'OpenAI verification code 111111',
|
||||
timestamp: 1000,
|
||||
};
|
||||
const windowMail = {
|
||||
id: 'mail-window',
|
||||
text: 'OpenAI verification code 222222',
|
||||
timestamp: 301000,
|
||||
};
|
||||
|
||||
function findMailItems() {
|
||||
return state === 'ready' ? [oldMail, windowMail] : [];
|
||||
}
|
||||
|
||||
function getMailItemId(item) {
|
||||
return item.id;
|
||||
}
|
||||
|
||||
function getCurrentMailIds(items = []) {
|
||||
return new Set(items.map((item) => item.id));
|
||||
}
|
||||
|
||||
function parseMailItemTimestamp(item) {
|
||||
return item.timestamp;
|
||||
}
|
||||
|
||||
function matchesMailFilters(text) {
|
||||
return /openai|verification/i.test(String(text || ''));
|
||||
}
|
||||
|
||||
function getMailItemText(item) {
|
||||
return item.text;
|
||||
}
|
||||
|
||||
function extractVerificationCode(text) {
|
||||
const match = String(text || '').match(/(\\d{6})/);
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
async function sleep() {}
|
||||
async function sleepRandom() {}
|
||||
async function returnToInbox() {
|
||||
return true;
|
||||
}
|
||||
async function refreshInbox() {}
|
||||
|
||||
async function openMailAndDeleteAfterRead(item) {
|
||||
readAndDeleteCalls.push(item.id);
|
||||
return item.text;
|
||||
}
|
||||
|
||||
async function ensureSeenCodesSession() {}
|
||||
function persistSeenCodes() {}
|
||||
function log() {}
|
||||
|
||||
${bundle}
|
||||
|
||||
return {
|
||||
handlePollEmail,
|
||||
getReadAndDeleteCalls() {
|
||||
return readAndDeleteCalls.slice();
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
const result = await api.handlePollEmail(4, {
|
||||
senderFilters: ['openai'],
|
||||
subjectFilters: ['verification'],
|
||||
maxAttempts: 1,
|
||||
intervalMs: 1,
|
||||
filterAfterTimestamp: 120000,
|
||||
});
|
||||
|
||||
assert.equal(result.code, '222222');
|
||||
assert.deepEqual(api.getReadAndDeleteCalls(), ['mail-window']);
|
||||
});
|
||||
|
||||
test('ensureSeenCodesSession resets tried codes only when a new verification step session starts', async () => {
|
||||
const bundle = [
|
||||
extractFunction('buildSeenCodeSessionKey'),
|
||||
@@ -419,12 +687,17 @@ test('deleteAllMailboxEmails selects all messages and clicks delete', async () =
|
||||
const calls = [];
|
||||
const selectAllControl = { kind: 'select-all' };
|
||||
const deleteButton = { kind: 'delete' };
|
||||
let mailboxCleared = false;
|
||||
|
||||
async function returnToInbox() {
|
||||
calls.push('inbox');
|
||||
return true;
|
||||
}
|
||||
|
||||
function findMailItems() {
|
||||
return mailboxCleared ? [] : [{ id: 'mail-1' }];
|
||||
}
|
||||
|
||||
function findSelectAllControl() {
|
||||
return selectAllControl;
|
||||
}
|
||||
@@ -444,11 +717,13 @@ function simulateClick(node) {
|
||||
}
|
||||
if (node === deleteButton) {
|
||||
calls.push('delete');
|
||||
mailboxCleared = true;
|
||||
return;
|
||||
}
|
||||
throw new Error('unexpected node');
|
||||
}
|
||||
|
||||
async function sleep() {}
|
||||
async function sleepRandom() {}
|
||||
|
||||
const console = { warn() {} };
|
||||
@@ -469,3 +744,187 @@ return {
|
||||
assert.equal(result, true);
|
||||
assert.deepEqual(api.getCalls(), ['inbox', 'select-all', 'delete']);
|
||||
});
|
||||
|
||||
test('findAgreementCheckbox skips 30-day login checkbox and picks agreement checkbox', async () => {
|
||||
const bundle = [
|
||||
extractFunction('normalizeNodeText'),
|
||||
extractFunction('isVisibleNode'),
|
||||
extractFunction('resolveActionTarget'),
|
||||
extractFunction('findAgreementContainer'),
|
||||
extractFunction('isAgreementText'),
|
||||
extractFunction('getCheckboxContextText'),
|
||||
extractFunction('findAgreementCheckbox'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
const MAIL2925_REMEMBER_LOGIN_PATTERNS = [
|
||||
/30天内免登录/,
|
||||
/免登录/,
|
||||
/记住登录/,
|
||||
/保持登录/,
|
||||
];
|
||||
const MAIL2925_AGREEMENT_PATTERNS = [
|
||||
/我已阅读并同意/,
|
||||
/服务协议/,
|
||||
/隐私政策/,
|
||||
];
|
||||
|
||||
const rememberCheckbox = {
|
||||
kind: 'remember-checkbox',
|
||||
disabled: false,
|
||||
readOnly: false,
|
||||
hidden: false,
|
||||
classList: { contains() { return false; } },
|
||||
getBoundingClientRect() { return { width: 14, height: 14 }; },
|
||||
closest(selector) {
|
||||
if (selector === 'button, [role="button"], a, label, .el-checkbox, .el-checkbox__input') return this;
|
||||
if (selector === 'label') return rememberLabel;
|
||||
if (selector === 'label, div, span, p, li, form') return rememberLabel;
|
||||
return null;
|
||||
},
|
||||
};
|
||||
const agreementCheckbox = {
|
||||
kind: 'agreement-checkbox',
|
||||
disabled: false,
|
||||
readOnly: false,
|
||||
hidden: false,
|
||||
classList: { contains() { return false; } },
|
||||
getBoundingClientRect() { return { width: 14, height: 14 }; },
|
||||
closest(selector) {
|
||||
if (selector === 'button, [role="button"], a, label, .el-checkbox, .el-checkbox__input') return this;
|
||||
if (selector === 'label') return agreementLabel;
|
||||
if (selector === 'label, div, span, p, li, form') return agreementLabel;
|
||||
return null;
|
||||
},
|
||||
};
|
||||
const rememberLabel = {
|
||||
innerText: '30天内免登录',
|
||||
textContent: '30天内免登录',
|
||||
hidden: false,
|
||||
getBoundingClientRect() { return { width: 100, height: 20 }; },
|
||||
parentElement: null,
|
||||
};
|
||||
const agreementLabel = {
|
||||
innerText: '我已阅读并同意 《服务协议》 和 《隐私政策》',
|
||||
textContent: '我已阅读并同意 《服务协议》 和 《隐私政策》',
|
||||
hidden: false,
|
||||
getBoundingClientRect() { return { width: 220, height: 24 }; },
|
||||
parentElement: null,
|
||||
querySelector(selector) {
|
||||
return selector.includes('checkbox') ? agreementCheckbox : null;
|
||||
},
|
||||
};
|
||||
rememberCheckbox.parentElement = rememberLabel;
|
||||
agreementCheckbox.parentElement = agreementLabel;
|
||||
|
||||
const document = {
|
||||
querySelectorAll(selector) {
|
||||
if (selector === 'label, div, span, p, form') {
|
||||
return [rememberLabel, agreementLabel];
|
||||
}
|
||||
if (selector === 'input[type="checkbox"], [role="checkbox"], .ivu-checkbox, .el-checkbox') {
|
||||
return [rememberCheckbox, agreementCheckbox];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
};
|
||||
|
||||
const window = {
|
||||
getComputedStyle() {
|
||||
return { display: 'block', visibility: 'visible' };
|
||||
},
|
||||
};
|
||||
|
||||
${bundle}
|
||||
|
||||
return {
|
||||
findAgreementCheckbox,
|
||||
rememberCheckbox,
|
||||
agreementCheckbox,
|
||||
};
|
||||
`)();
|
||||
|
||||
assert.equal(api.findAgreementCheckbox(), api.agreementCheckbox);
|
||||
});
|
||||
|
||||
test('ensureAgreementChecked clicks all visible login checkboxes', async () => {
|
||||
const bundle = [
|
||||
extractFunction('isVisibleNode'),
|
||||
extractFunction('resolveActionTarget'),
|
||||
extractFunction('isCheckboxChecked'),
|
||||
extractFunction('ensureAgreementChecked'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
const rememberCheckbox = {
|
||||
disabled: false,
|
||||
readOnly: false,
|
||||
hidden: false,
|
||||
checked: false,
|
||||
classList: { contains() { return false; } },
|
||||
getBoundingClientRect() { return { width: 14, height: 14 }; },
|
||||
click() { this.checked = true; },
|
||||
closest(selector) {
|
||||
if (selector === 'button, [role="button"], a, label, .el-checkbox, .el-checkbox__input') return this;
|
||||
return null;
|
||||
},
|
||||
querySelector() { return null; },
|
||||
getAttribute(name) {
|
||||
if (name === 'aria-checked') return this.checked ? 'true' : 'false';
|
||||
return '';
|
||||
},
|
||||
};
|
||||
const agreementCheckbox = {
|
||||
disabled: false,
|
||||
readOnly: false,
|
||||
hidden: false,
|
||||
checked: false,
|
||||
classList: { contains() { return false; } },
|
||||
getBoundingClientRect() { return { width: 14, height: 14 }; },
|
||||
click() { this.checked = true; },
|
||||
closest(selector) {
|
||||
if (selector === 'button, [role="button"], a, label, .el-checkbox, .el-checkbox__input') return this;
|
||||
return null;
|
||||
},
|
||||
querySelector() { return null; },
|
||||
getAttribute(name) {
|
||||
if (name === 'aria-checked') return this.checked ? 'true' : 'false';
|
||||
return '';
|
||||
},
|
||||
};
|
||||
|
||||
const document = {
|
||||
querySelectorAll(selector) {
|
||||
if (selector === 'input[type="checkbox"], [role="checkbox"], .ivu-checkbox, .el-checkbox') {
|
||||
return [rememberCheckbox, agreementCheckbox];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
};
|
||||
|
||||
const window = {
|
||||
getComputedStyle() {
|
||||
return { display: 'block', visibility: 'visible' };
|
||||
},
|
||||
};
|
||||
|
||||
async function sleep() {}
|
||||
function simulateClick(node) {
|
||||
node.click();
|
||||
}
|
||||
|
||||
${bundle}
|
||||
|
||||
return {
|
||||
rememberCheckbox,
|
||||
agreementCheckbox,
|
||||
ensureAgreementChecked,
|
||||
};
|
||||
`)();
|
||||
|
||||
const result = await api.ensureAgreementChecked();
|
||||
|
||||
assert.equal(result, true);
|
||||
assert.equal(api.rememberCheckbox.checked, true);
|
||||
assert.equal(api.agreementCheckbox.checked, true);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const utils = require('../mail2925-utils.js');
|
||||
|
||||
test('normalizeMail2925Account normalizes key fields', () => {
|
||||
const account = utils.normalizeMail2925Account({
|
||||
id: 'a-1',
|
||||
email: ' Demo@2925.com ',
|
||||
password: 'secret',
|
||||
enabled: 0,
|
||||
lastUsedAt: '123',
|
||||
disabledUntil: '456',
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(account, {
|
||||
id: 'a-1',
|
||||
email: 'demo@2925.com',
|
||||
password: 'secret',
|
||||
enabled: false,
|
||||
lastUsedAt: 123,
|
||||
lastLoginAt: 0,
|
||||
lastLimitAt: 0,
|
||||
disabledUntil: 456,
|
||||
lastError: '',
|
||||
});
|
||||
});
|
||||
|
||||
test('pickMail2925AccountForRun skips cooldown and picks the least recently used account', () => {
|
||||
const now = 1000;
|
||||
const picked = utils.pickMail2925AccountForRun([
|
||||
{ id: 'cooldown', email: 'cool@2925.com', password: 'x', disabledUntil: now + 10, lastUsedAt: 1 },
|
||||
{ id: 'b', email: 'b@2925.com', password: 'x', lastUsedAt: 50 },
|
||||
{ id: 'a', email: 'a@2925.com', password: 'x', lastUsedAt: 10 },
|
||||
], { now });
|
||||
|
||||
assert.equal(picked.id, 'a');
|
||||
});
|
||||
|
||||
test('getMail2925AccountStatus reports cooldown before error', () => {
|
||||
const status = utils.getMail2925AccountStatus({
|
||||
email: 'demo@2925.com',
|
||||
password: 'secret',
|
||||
enabled: true,
|
||||
disabledUntil: Date.now() + 60_000,
|
||||
lastError: '子邮箱已达上限邮箱',
|
||||
});
|
||||
|
||||
assert.equal(status, 'cooldown');
|
||||
});
|
||||
|
||||
test('parseMail2925ImportText parses 邮箱----密码 rows', () => {
|
||||
const parsed = utils.parseMail2925ImportText(`
|
||||
邮箱----密码
|
||||
demo1@2925.com----pass1
|
||||
demo2@2925.com----pass2
|
||||
`);
|
||||
|
||||
assert.deepStrictEqual(parsed, [
|
||||
{ email: 'demo1@2925.com', password: 'pass1' },
|
||||
{ email: 'demo2@2925.com', password: 'pass2' },
|
||||
]);
|
||||
});
|
||||
@@ -26,3 +26,12 @@ test('managed alias utils validate provider email with or without configured bas
|
||||
assert.equal(api.isManagedAliasEmail('manual@gmail.com', 'gmail', ''), true);
|
||||
assert.equal(api.isManagedAliasEmail('manual@qq.com', 'gmail', ''), false);
|
||||
});
|
||||
|
||||
test('managed alias utils keep 2925 alias generation behind provide mode only', () => {
|
||||
assert.equal(api.normalizeMail2925Mode('provide'), 'provide');
|
||||
assert.equal(api.normalizeMail2925Mode('receive'), 'receive');
|
||||
assert.equal(api.normalizeMail2925Mode('other'), 'provide');
|
||||
assert.equal(api.usesManagedAliasGeneration('gmail'), true);
|
||||
assert.equal(api.usesManagedAliasGeneration('2925', { mail2925Mode: 'provide' }), true);
|
||||
assert.equal(api.usesManagedAliasGeneration('2925', { mail2925Mode: 'receive' }), false);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
function extractFunction(source, 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('sidepanel run count input no longer hardcodes max=50', () => {
|
||||
const html = fs.readFileSync('sidepanel/sidepanel.html', 'utf8');
|
||||
const inputTag = html.match(/<input type="number" id="input-run-count"[^>]+>/);
|
||||
|
||||
assert.ok(inputTag, 'run count input should exist');
|
||||
assert.doesNotMatch(inputTag[0], /\smax="50"/);
|
||||
});
|
||||
|
||||
test('sidepanel getRunCountValue no longer clamps run count to 50', () => {
|
||||
const source = fs.readFileSync('sidepanel/sidepanel.js', 'utf8');
|
||||
const bundle = extractFunction(source, 'getRunCountValue');
|
||||
|
||||
const api = new Function(`
|
||||
const inputRunCount = { value: '88' };
|
||||
${bundle}
|
||||
return {
|
||||
getRunCountValue,
|
||||
setValue(value) {
|
||||
inputRunCount.value = value;
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
assert.equal(api.getRunCountValue(), 88);
|
||||
api.setValue('0');
|
||||
assert.equal(api.getRunCountValue(), 1);
|
||||
});
|
||||
|
||||
test('background normalizeRunCount no longer clamps values to 50', () => {
|
||||
const source = fs.readFileSync('background.js', 'utf8');
|
||||
const bundle = extractFunction(source, 'normalizeRunCount');
|
||||
|
||||
const api = new Function(`
|
||||
${bundle}
|
||||
return { normalizeRunCount };
|
||||
`)();
|
||||
|
||||
assert.equal(api.normalizeRunCount(88), 88);
|
||||
assert.equal(api.normalizeRunCount('120'), 120);
|
||||
assert.equal(api.normalizeRunCount(0), 1);
|
||||
assert.equal(api.normalizeRunCount('bad'), 1);
|
||||
});
|
||||
@@ -207,7 +207,7 @@ test('account records manager supports filter chips and partial multi-select del
|
||||
finalStatus: 'stopped',
|
||||
finishedAt: '2026-04-17T04:28:00.000Z',
|
||||
retryCount: 1,
|
||||
failureLabel: '流程已停止',
|
||||
failureLabel: '步骤 7 停止',
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -303,6 +303,7 @@ test('account records manager supports filter chips and partial multi-select del
|
||||
assert.doesNotMatch(list.innerHTML, /success@example\.com/);
|
||||
assert.match(list.innerHTML, /failed@example\.com/);
|
||||
assert.match(list.innerHTML, /stopped@example\.com/);
|
||||
assert.match(list.innerHTML, /步骤 7 停止/);
|
||||
|
||||
btnToggleAccountRecordsSelection.listeners.click();
|
||||
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const sidepanelSource = fs.readFileSync('sidepanel/sidepanel.js', 'utf8');
|
||||
|
||||
function extractFunction(name) {
|
||||
const markers = [`async function ${name}(`, `function ${name}(`];
|
||||
const start = markers
|
||||
.map((marker) => sidepanelSource.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 < sidepanelSource.length; i += 1) {
|
||||
const ch = sidepanelSource[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 < sidepanelSource.length; end += 1) {
|
||||
const ch = sidepanelSource[end];
|
||||
if (ch === '{') depth += 1;
|
||||
if (ch === '}') {
|
||||
depth -= 1;
|
||||
if (depth === 0) {
|
||||
end += 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sidepanelSource.slice(start, end);
|
||||
}
|
||||
|
||||
function createApi({ refreshImpl } = {}) {
|
||||
const bundle = extractFunction('startAutoRunFromCurrentSettings');
|
||||
|
||||
return new Function(`
|
||||
const events = [];
|
||||
const latestState = { contributionMode: false };
|
||||
const inputAutoSkipFailures = { checked: false };
|
||||
const inputContributionNickname = { value: 'tester' };
|
||||
const inputContributionQq = { value: '123456' };
|
||||
const inputAutoSkipFailuresThreadIntervalMinutes = { value: '5' };
|
||||
const inputAutoDelayEnabled = { checked: false };
|
||||
const inputAutoDelayMinutes = { value: '30' };
|
||||
const btnAutoRun = { disabled: false, innerHTML: '' };
|
||||
const inputRunCount = { disabled: false };
|
||||
const chrome = {
|
||||
runtime: {
|
||||
async sendMessage(message) {
|
||||
events.push({ type: 'send', message });
|
||||
return { ok: true };
|
||||
},
|
||||
},
|
||||
};
|
||||
const console = {
|
||||
warn(...args) {
|
||||
events.push({ type: 'warn', args });
|
||||
},
|
||||
};
|
||||
function getRunCountValue() { return 3; }
|
||||
function normalizeAutoRunThreadIntervalMinutes(value) { return Number(value) || 0; }
|
||||
function shouldOfferAutoModeChoice() { return false; }
|
||||
async function openAutoStartChoiceDialog() { throw new Error('should not be called'); }
|
||||
function getFirstUnfinishedStep() { return 1; }
|
||||
function getRunningSteps() { return []; }
|
||||
function shouldWarnAutoRunFallbackRisk() { return false; }
|
||||
function isAutoRunFallbackRiskPromptDismissed() { return false; }
|
||||
async function openAutoRunFallbackRiskConfirmModal() { throw new Error('should not be called'); }
|
||||
function setAutoRunFallbackRiskPromptDismissed() {}
|
||||
function normalizeAutoDelayMinutes(value) { return Number(value) || 30; }
|
||||
async function refreshContributionContentHint() {
|
||||
events.push({ type: 'refresh' });
|
||||
${refreshImpl ? 'return (' + refreshImpl + ')();' : 'return null;'}
|
||||
}
|
||||
${bundle}
|
||||
return {
|
||||
startAutoRunFromCurrentSettings,
|
||||
getEvents() {
|
||||
return events;
|
||||
},
|
||||
};
|
||||
`)();
|
||||
}
|
||||
|
||||
test('startAutoRunFromCurrentSettings refreshes contribution content hint before starting auto run', async () => {
|
||||
const api = createApi();
|
||||
|
||||
const result = await api.startAutoRunFromCurrentSettings();
|
||||
|
||||
assert.equal(result, true);
|
||||
assert.deepEqual(
|
||||
api.getEvents().map((entry) => entry.type),
|
||||
['refresh', 'send']
|
||||
);
|
||||
assert.equal(api.getEvents()[1].message.type, 'AUTO_RUN');
|
||||
});
|
||||
|
||||
test('startAutoRunFromCurrentSettings continues auto run when contribution content refresh fails', async () => {
|
||||
const api = createApi({
|
||||
refreshImpl: 'async () => { throw new Error("refresh failed"); }',
|
||||
});
|
||||
|
||||
const result = await api.startAutoRunFromCurrentSettings();
|
||||
const events = api.getEvents();
|
||||
|
||||
assert.equal(result, true);
|
||||
assert.deepEqual(
|
||||
events.map((entry) => entry.type),
|
||||
['refresh', 'warn', 'send']
|
||||
);
|
||||
assert.match(String(events[1].args[0]), /Failed to refresh contribution content hint before auto run/);
|
||||
assert.equal(events[2].message.type, 'AUTO_RUN');
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const source = fs.readFileSync('sidepanel/sidepanel.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('auto-run fallback risk warning starts at 3 runs', () => {
|
||||
const bundle = extractFunction('shouldWarnAutoRunFallbackRisk');
|
||||
|
||||
const api = new Function(`
|
||||
const AUTO_RUN_FALLBACK_RISK_WARNING_MIN_RUNS = 3;
|
||||
${bundle}
|
||||
return { shouldWarnAutoRunFallbackRisk };
|
||||
`)();
|
||||
|
||||
assert.equal(api.shouldWarnAutoRunFallbackRisk(2, false), false);
|
||||
assert.equal(api.shouldWarnAutoRunFallbackRisk(3, false), true);
|
||||
assert.equal(api.shouldWarnAutoRunFallbackRisk(10, true), true);
|
||||
});
|
||||
|
||||
test('auto-run fallback risk modal uses the single-node warning copy', async () => {
|
||||
const bundle = extractFunction('openAutoRunFallbackRiskConfirmModal');
|
||||
|
||||
const api = new Function(`
|
||||
let capturedOptions = null;
|
||||
async function openConfirmModalWithOption(options) {
|
||||
capturedOptions = options;
|
||||
return { confirmed: true, optionChecked: false };
|
||||
}
|
||||
${bundle}
|
||||
return {
|
||||
openAutoRunFallbackRiskConfirmModal,
|
||||
getCapturedOptions() {
|
||||
return capturedOptions;
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
const result = await api.openAutoRunFallbackRiskConfirmModal(3);
|
||||
const options = api.getCapturedOptions();
|
||||
|
||||
assert.deepStrictEqual(result, { confirmed: true, dismissPrompt: false });
|
||||
assert.equal(options.title, '自动运行风险提醒');
|
||||
assert.equal(
|
||||
options.message,
|
||||
'当前轮数已经不适合单节点情况,请确保已经配置并打开节点轮询功能(若没有配置,请点击贡献/使用按钮,根据网页中使用教程进行配置),避免连续使用一个节点注册,导致出现手机号验证。'
|
||||
);
|
||||
assert.equal(options.confirmLabel, '继续');
|
||||
});
|
||||
@@ -0,0 +1,297 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const source = fs.readFileSync('sidepanel/sidepanel.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);
|
||||
}
|
||||
|
||||
function createRow(initialDisplay = 'none') {
|
||||
return {
|
||||
style: { display: initialDisplay },
|
||||
};
|
||||
}
|
||||
|
||||
test('sidepanel html places cloudflare temp email controls in a standalone section', () => {
|
||||
const html = fs.readFileSync('sidepanel/sidepanel.html', 'utf8');
|
||||
assert.match(html, /id="cloudflare-temp-email-section"/);
|
||||
assert.match(html, /id="btn-cloudflare-temp-email-usage-guide"/);
|
||||
assert.match(html, /id="btn-cloudflare-temp-email-github"/);
|
||||
assert.match(html, /id="row-temp-email-random-subdomain-toggle"/);
|
||||
assert.match(html, /id="input-temp-email-use-random-subdomain"/);
|
||||
assert.doesNotMatch(html, /id="row-temp-email-random-subdomain-domain"/);
|
||||
});
|
||||
|
||||
test('sidepanel modal message preserves line breaks and supports inline links', () => {
|
||||
const css = fs.readFileSync('sidepanel/sidepanel.css', 'utf8');
|
||||
assert.match(css, /\.modal-message\s*\{[\s\S]*white-space:\s*pre-line;/);
|
||||
assert.match(css, /\.modal-message a,\s*[\s\S]*\.modal-alert a/);
|
||||
});
|
||||
|
||||
test('buildCloudflareTempEmailUsageGuideModalConfig returns a modal payload with inline links for generator mode', () => {
|
||||
const bundle = extractFunction('buildCloudflareTempEmailUsageGuideModalConfig');
|
||||
|
||||
const api = new Function(`
|
||||
const selectMailProvider = { value: '163' };
|
||||
const selectEmailGenerator = { value: 'cloudflare-temp-email' };
|
||||
const CLOUDFLARE_TEMP_EMAIL_BUILD_TUTORIAL_URL = 'https://linux.do/t/topic/316819';
|
||||
const CLOUDFLARE_TEMP_EMAIL_RANDOM_SUBDOMAIN_ISSUE_URL = 'https://github.com/dreamhunter2333/cloudflare_temp_email/issues/942';
|
||||
function getSelectedEmailGenerator() { return String(selectEmailGenerator.value || '').trim().toLowerCase(); }
|
||||
${bundle}
|
||||
return {
|
||||
buildCloudflareTempEmailUsageGuideModalConfig,
|
||||
};
|
||||
`)();
|
||||
|
||||
const modalConfig = api.buildCloudflareTempEmailUsageGuideModalConfig();
|
||||
assert.equal(typeof modalConfig.title, 'string');
|
||||
assert.equal(typeof modalConfig.messageHtml, 'string');
|
||||
assert.equal(typeof modalConfig.alert?.text, 'string');
|
||||
assert.equal(modalConfig.title.length > 0, true);
|
||||
assert.equal(modalConfig.messageHtml.length > 0, true);
|
||||
assert.equal(modalConfig.alert.text.length > 0, true);
|
||||
assert.equal(modalConfig.messageHtml.includes('<a '), true);
|
||||
assert.equal(modalConfig.messageHtml.includes('Issue #942'), true);
|
||||
assert.equal(modalConfig.messageHtml.includes('LINUX DO 教程'), true);
|
||||
});
|
||||
|
||||
test('buildCloudflareTempEmailUsageGuideModalConfig returns a distinct alert for provider mode', () => {
|
||||
const bundle = extractFunction('buildCloudflareTempEmailUsageGuideModalConfig');
|
||||
|
||||
const api = new Function(`
|
||||
const selectMailProvider = { value: 'cloudflare-temp-email' };
|
||||
const selectEmailGenerator = { value: 'duck' };
|
||||
const CLOUDFLARE_TEMP_EMAIL_BUILD_TUTORIAL_URL = 'https://linux.do/t/topic/316819';
|
||||
const CLOUDFLARE_TEMP_EMAIL_RANDOM_SUBDOMAIN_ISSUE_URL = 'https://github.com/dreamhunter2333/cloudflare_temp_email/issues/942';
|
||||
function getSelectedEmailGenerator() { return String(selectEmailGenerator.value || '').trim().toLowerCase(); }
|
||||
${bundle}
|
||||
return {
|
||||
buildCloudflareTempEmailUsageGuideModalConfig,
|
||||
};
|
||||
`)();
|
||||
|
||||
const providerConfig = api.buildCloudflareTempEmailUsageGuideModalConfig();
|
||||
|
||||
const generatorApi = new Function(`
|
||||
const selectMailProvider = { value: '163' };
|
||||
const selectEmailGenerator = { value: 'cloudflare-temp-email' };
|
||||
const CLOUDFLARE_TEMP_EMAIL_BUILD_TUTORIAL_URL = 'https://linux.do/t/topic/316819';
|
||||
const CLOUDFLARE_TEMP_EMAIL_RANDOM_SUBDOMAIN_ISSUE_URL = 'https://github.com/dreamhunter2333/cloudflare_temp_email/issues/942';
|
||||
function getSelectedEmailGenerator() { return String(selectEmailGenerator.value || '').trim().toLowerCase(); }
|
||||
${bundle}
|
||||
return {
|
||||
buildCloudflareTempEmailUsageGuideModalConfig,
|
||||
};
|
||||
`)();
|
||||
|
||||
const generatorConfig = generatorApi.buildCloudflareTempEmailUsageGuideModalConfig();
|
||||
assert.equal(typeof providerConfig.alert?.text, 'string');
|
||||
assert.equal(typeof providerConfig.messageHtml, 'string');
|
||||
assert.equal(providerConfig.alert.text.length > 0, true);
|
||||
assert.equal(providerConfig.messageHtml.length > 0, true);
|
||||
assert.notEqual(providerConfig.alert.text, generatorConfig.alert.text);
|
||||
});
|
||||
|
||||
test('openCloudflareTempEmailRepositoryPage opens the upstream repository', () => {
|
||||
const bundle = extractFunction('openCloudflareTempEmailRepositoryPage');
|
||||
|
||||
const api = new Function(`
|
||||
const calls = [];
|
||||
const CLOUDFLARE_TEMP_EMAIL_REPOSITORY_URL = 'https://github.com/dreamhunter2333/cloudflare_temp_email';
|
||||
function openExternalUrl(url) { calls.push(url); }
|
||||
${bundle}
|
||||
return {
|
||||
calls,
|
||||
openCloudflareTempEmailRepositoryPage,
|
||||
};
|
||||
`)();
|
||||
|
||||
api.openCloudflareTempEmailRepositoryPage();
|
||||
assert.deepEqual(api.calls, ['https://github.com/dreamhunter2333/cloudflare_temp_email']);
|
||||
});
|
||||
|
||||
test('applyCloudflareTempEmailSettingsState restores the random subdomain toggle and temp domain list', () => {
|
||||
const bundle = extractFunction('applyCloudflareTempEmailSettingsState');
|
||||
|
||||
const api = new Function(`
|
||||
const inputTempEmailBaseUrl = { value: '' };
|
||||
const inputTempEmailAdminAuth = { value: '' };
|
||||
const inputTempEmailCustomAuth = { value: '' };
|
||||
const inputTempEmailReceiveMailbox = { value: '' };
|
||||
const inputTempEmailUseRandomSubdomain = { checked: false };
|
||||
const calls = {
|
||||
domainOptions: [],
|
||||
domainEditMode: [],
|
||||
};
|
||||
function renderCloudflareTempEmailDomainOptions(value) { calls.domainOptions.push(value); }
|
||||
function setCloudflareTempEmailDomainEditMode(editing, options) { calls.domainEditMode.push({ editing, options }); }
|
||||
${bundle}
|
||||
return {
|
||||
applyCloudflareTempEmailSettingsState,
|
||||
calls,
|
||||
inputTempEmailBaseUrl,
|
||||
inputTempEmailAdminAuth,
|
||||
inputTempEmailCustomAuth,
|
||||
inputTempEmailReceiveMailbox,
|
||||
inputTempEmailUseRandomSubdomain,
|
||||
};
|
||||
`)();
|
||||
|
||||
api.applyCloudflareTempEmailSettingsState({
|
||||
cloudflareTempEmailBaseUrl: 'https://temp.example.com',
|
||||
cloudflareTempEmailAdminAuth: 'admin-secret',
|
||||
cloudflareTempEmailCustomAuth: 'custom-secret',
|
||||
cloudflareTempEmailReceiveMailbox: 'relay@example.com',
|
||||
cloudflareTempEmailUseRandomSubdomain: true,
|
||||
cloudflareTempEmailDomain: 'mail.example.com',
|
||||
});
|
||||
|
||||
assert.equal(api.inputTempEmailBaseUrl.value, 'https://temp.example.com');
|
||||
assert.equal(api.inputTempEmailAdminAuth.value, 'admin-secret');
|
||||
assert.equal(api.inputTempEmailCustomAuth.value, 'custom-secret');
|
||||
assert.equal(api.inputTempEmailReceiveMailbox.value, 'relay@example.com');
|
||||
assert.equal(api.inputTempEmailUseRandomSubdomain.checked, true);
|
||||
assert.deepEqual(api.calls.domainOptions, ['mail.example.com']);
|
||||
assert.deepEqual(api.calls.domainEditMode, [{ editing: false, options: { clearInput: true } }]);
|
||||
});
|
||||
|
||||
test('updateMailProviderUI keeps the temp domain selector visible and updates the hint when random subdomain is enabled', () => {
|
||||
const bundle = extractFunction('updateMailProviderUI');
|
||||
|
||||
const api = new Function(`
|
||||
let latestState = {
|
||||
cloudflareTempEmailDomains: ['mail.example.com'],
|
||||
};
|
||||
let cloudflareTempEmailDomainEditMode = false;
|
||||
const ICLOUD_PROVIDER = 'icloud';
|
||||
const GMAIL_PROVIDER = 'gmail';
|
||||
const LUCKMAIL_PROVIDER = 'luckmail-api';
|
||||
const rowMail2925Mode = ${JSON.stringify(createRow('none'))};
|
||||
const rowMail2925PoolSettings = ${JSON.stringify(createRow('none'))};
|
||||
const rowEmailPrefix = ${JSON.stringify(createRow('none'))};
|
||||
const rowInbucketHost = ${JSON.stringify(createRow('none'))};
|
||||
const rowInbucketMailbox = ${JSON.stringify(createRow('none'))};
|
||||
const rowEmailGenerator = ${JSON.stringify(createRow(''))};
|
||||
const rowCfDomain = ${JSON.stringify(createRow('none'))};
|
||||
const rowTempEmailBaseUrl = ${JSON.stringify(createRow('none'))};
|
||||
const rowTempEmailAdminAuth = ${JSON.stringify(createRow('none'))};
|
||||
const rowTempEmailCustomAuth = ${JSON.stringify(createRow('none'))};
|
||||
const rowTempEmailReceiveMailbox = ${JSON.stringify(createRow('none'))};
|
||||
const rowTempEmailRandomSubdomainToggle = ${JSON.stringify(createRow('none'))};
|
||||
const rowTempEmailDomain = ${JSON.stringify(createRow('none'))};
|
||||
const cloudflareTempEmailSection = ${JSON.stringify(createRow('none'))};
|
||||
const hotmailSection = ${JSON.stringify(createRow('none'))};
|
||||
const mail2925Section = ${JSON.stringify(createRow('none'))};
|
||||
const luckmailSection = ${JSON.stringify(createRow('none'))};
|
||||
const icloudSection = ${JSON.stringify(createRow('none'))};
|
||||
const labelEmailPrefix = { textContent: '' };
|
||||
const inputEmailPrefix = { placeholder: '', style: { display: '' }, readOnly: false };
|
||||
const labelMail2925UseAccountPool = ${JSON.stringify(createRow('none'))};
|
||||
const selectMail2925PoolAccount = { style: { display: 'none' }, disabled: false };
|
||||
const btnFetchEmail = { hidden: false, disabled: false, textContent: '' };
|
||||
const btnMailLogin = { disabled: false, textContent: '', title: '' };
|
||||
const inputEmail = { readOnly: false, placeholder: '', value: '' };
|
||||
const autoHintText = { textContent: '' };
|
||||
const rowHotmailServiceMode = ${JSON.stringify(createRow('none'))};
|
||||
const rowHotmailRemoteBaseUrl = ${JSON.stringify(createRow('none'))};
|
||||
const rowHotmailLocalBaseUrl = ${JSON.stringify(createRow('none'))};
|
||||
const inputMail2925UseAccountPool = { checked: false };
|
||||
const selectMailProvider = { value: '163' };
|
||||
const selectEmailGenerator = { value: 'cloudflare-temp-email', disabled: false };
|
||||
const inputTempEmailUseRandomSubdomain = { checked: false };
|
||||
const calls = {
|
||||
tempDomainEditMode: [],
|
||||
};
|
||||
function isLuckmailProvider() { return false; }
|
||||
function isCustomMailProvider() { return false; }
|
||||
function isIcloudMailProvider() { return false; }
|
||||
function usesGeneratedAliasMailProvider() { return false; }
|
||||
function getSelectedMail2925Mode() { return 'provide'; }
|
||||
function getManagedAliasProviderUiCopy() { return null; }
|
||||
function getCurrentRegistrationEmailUiCopy() {
|
||||
return {
|
||||
buttonLabel: '生成 Temp',
|
||||
placeholder: '点击生成 Cloudflare Temp Email,或手动粘贴邮箱',
|
||||
label: 'Cloudflare Temp Email',
|
||||
};
|
||||
}
|
||||
function updateMailLoginButtonState() {}
|
||||
function getSelectedHotmailServiceMode() { return 'local'; }
|
||||
function getCloudflareDomainsFromState() { return { domains: [], activeDomain: '' }; }
|
||||
function setCloudflareDomainEditMode() {}
|
||||
function getCloudflareTempEmailDomainsFromState() { return { domains: ['mail.example.com'], activeDomain: 'mail.example.com' }; }
|
||||
function setCloudflareTempEmailDomainEditMode(editing) { calls.tempDomainEditMode.push(editing); }
|
||||
function queueIcloudAliasRefresh() {}
|
||||
function hideIcloudLoginHelp() {}
|
||||
function syncMail2925PoolAccountOptions() {}
|
||||
function getMail2925Accounts() { return []; }
|
||||
function renderHotmailAccounts() {}
|
||||
function renderMail2925Accounts() {}
|
||||
function renderLuckmailPurchases() {}
|
||||
function getSelectedEmailGenerator() { return String(selectEmailGenerator.value || '').trim().toLowerCase(); }
|
||||
function isAutoRunLockedPhase() { return false; }
|
||||
${bundle}
|
||||
return {
|
||||
updateMailProviderUI,
|
||||
cloudflareTempEmailSection,
|
||||
rowTempEmailRandomSubdomainToggle,
|
||||
rowTempEmailDomain,
|
||||
inputTempEmailUseRandomSubdomain,
|
||||
autoHintText,
|
||||
calls,
|
||||
};
|
||||
`)();
|
||||
|
||||
api.updateMailProviderUI();
|
||||
assert.equal(api.cloudflareTempEmailSection.style.display, '');
|
||||
assert.equal(api.rowTempEmailRandomSubdomainToggle.style.display, '');
|
||||
assert.equal(api.rowTempEmailDomain.style.display, '');
|
||||
|
||||
api.inputTempEmailUseRandomSubdomain.checked = true;
|
||||
api.updateMailProviderUI();
|
||||
assert.equal(api.cloudflareTempEmailSection.style.display, '');
|
||||
assert.equal(api.rowTempEmailDomain.style.display, '');
|
||||
assert.match(api.autoHintText.textContent, /RANDOM_SUBDOMAIN_DOMAINS/);
|
||||
});
|
||||
@@ -2,113 +2,28 @@ const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const sidepanelSource = fs.readFileSync('sidepanel/sidepanel.js', 'utf8');
|
||||
|
||||
function extractFunction(name) {
|
||||
const markers = [`async function ${name}(`, `function ${name}(`];
|
||||
const start = markers
|
||||
.map((marker) => sidepanelSource.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 < sidepanelSource.length; i += 1) {
|
||||
const ch = sidepanelSource[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 < sidepanelSource.length; end += 1) {
|
||||
const ch = sidepanelSource[end];
|
||||
if (ch === '{') depth += 1;
|
||||
if (ch === '}') {
|
||||
depth -= 1;
|
||||
if (depth === 0) {
|
||||
end += 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sidepanelSource.slice(start, end);
|
||||
}
|
||||
|
||||
test('sidepanel html contains contribution button in header', () => {
|
||||
test('sidepanel html keeps a single contribution mode button in header', () => {
|
||||
const html = fs.readFileSync('sidepanel/sidepanel.html', 'utf8');
|
||||
assert.match(html, /id="btn-contribution-mode"/);
|
||||
assert.match(html, />贡献</);
|
||||
const matches = html.match(/id="btn-contribution-mode"/g) || [];
|
||||
const serviceIndex = html.indexOf('<script src="contribution-content-update-service.js"></script>');
|
||||
const sidepanelIndex = html.indexOf('<script src="sidepanel.js"></script>');
|
||||
|
||||
assert.equal(matches.length, 1);
|
||||
assert.match(html, /id="btn-contribution-mode"[^>]*title="进入贡献模式并打开上传页"/);
|
||||
assert.match(html, />贡献\/使用<\/button>/);
|
||||
assert.match(html, /<\/header>\s*<div id="contribution-update-layer"/);
|
||||
assert.match(html, /id="contribution-update-layer"/);
|
||||
assert.match(html, /id="contribution-update-hint"/);
|
||||
assert.match(html, /id="contribution-update-hint-text"/);
|
||||
assert.match(html, /id="btn-dismiss-contribution-update-hint"/);
|
||||
assert.notEqual(serviceIndex, -1);
|
||||
assert.notEqual(sidepanelIndex, -1);
|
||||
assert.ok(serviceIndex < sidepanelIndex);
|
||||
});
|
||||
|
||||
test('openContributionUploadPage opens upload page in a new tab directly', async () => {
|
||||
const bundle = [
|
||||
extractFunction('openContributionUploadPage'),
|
||||
].join('\n');
|
||||
test('sidepanel source no longer keeps the legacy upload-page handler on the header contribution button', () => {
|
||||
const source = fs.readFileSync('sidepanel/sidepanel.js', 'utf8');
|
||||
|
||||
const api = new Function(`
|
||||
const calls = [];
|
||||
const CONTRIBUTION_UPLOAD_URL = 'https://apikey.qzz.io/';
|
||||
function isContributionButtonLocked() {
|
||||
return false;
|
||||
}
|
||||
function openExternalUrl(url) {
|
||||
calls.push({ type: 'open', url });
|
||||
}
|
||||
${bundle}
|
||||
return {
|
||||
openContributionUploadPage,
|
||||
getCalls() {
|
||||
return calls;
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
const result = await api.openContributionUploadPage();
|
||||
assert.equal(result, true);
|
||||
assert.deepStrictEqual(api.getCalls(), [
|
||||
{
|
||||
type: 'open',
|
||||
url: 'https://apikey.qzz.io/',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('openContributionUploadPage blocks while flow is running', async () => {
|
||||
const bundle = [
|
||||
extractFunction('openContributionUploadPage'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
const CONTRIBUTION_UPLOAD_URL = 'https://apikey.qzz.io/';
|
||||
function isContributionButtonLocked() {
|
||||
return true;
|
||||
}
|
||||
async function openConfirmModal() {
|
||||
throw new Error('should not open modal');
|
||||
}
|
||||
function openExternalUrl() {
|
||||
throw new Error('should not open url');
|
||||
}
|
||||
${bundle}
|
||||
return { openContributionUploadPage };
|
||||
`)();
|
||||
|
||||
await assert.rejects(
|
||||
() => api.openContributionUploadPage(),
|
||||
/当前流程运行中/
|
||||
);
|
||||
assert.doesNotMatch(source, /openContributionUploadPage/);
|
||||
assert.doesNotMatch(source, /await openContributionUploadPage\(\)/);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,488 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const sidepanelSource = fs.readFileSync('sidepanel/sidepanel.js', 'utf8');
|
||||
|
||||
function extractFunction(name) {
|
||||
const markers = [`async function ${name}(`, `function ${name}(`];
|
||||
const start = markers
|
||||
.map((marker) => sidepanelSource.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 < sidepanelSource.length; i += 1) {
|
||||
const ch = sidepanelSource[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 < sidepanelSource.length; end += 1) {
|
||||
const ch = sidepanelSource[end];
|
||||
if (ch === '{') depth += 1;
|
||||
if (ch === '}') {
|
||||
depth -= 1;
|
||||
if (depth === 0) {
|
||||
end += 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sidepanelSource.slice(start, end);
|
||||
}
|
||||
|
||||
function createClassList() {
|
||||
const values = new Set();
|
||||
return {
|
||||
add(name) {
|
||||
values.add(name);
|
||||
},
|
||||
remove(name) {
|
||||
values.delete(name);
|
||||
},
|
||||
toggle(name, force) {
|
||||
if (force === undefined) {
|
||||
if (values.has(name)) {
|
||||
values.delete(name);
|
||||
return false;
|
||||
}
|
||||
values.add(name);
|
||||
return true;
|
||||
}
|
||||
if (force) {
|
||||
values.add(name);
|
||||
return true;
|
||||
}
|
||||
values.delete(name);
|
||||
return false;
|
||||
},
|
||||
contains(name) {
|
||||
return values.has(name);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createElement(initial = {}) {
|
||||
return {
|
||||
disabled: Boolean(initial.disabled),
|
||||
hidden: Boolean(initial.hidden),
|
||||
value: initial.value || '',
|
||||
title: '',
|
||||
textContent: initial.textContent || '',
|
||||
listeners: {},
|
||||
attributes: {},
|
||||
classList: createClassList(),
|
||||
addEventListener(type, handler) {
|
||||
this.listeners[type] = handler;
|
||||
},
|
||||
setAttribute(name, value) {
|
||||
this.attributes[name] = String(value);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('sidepanel html contains contribution mode runtime UI and loads the module before sidepanel bootstrap', () => {
|
||||
const html = fs.readFileSync('sidepanel/sidepanel.html', 'utf8');
|
||||
const moduleIndex = html.indexOf('<script src="contribution-mode.js"></script>');
|
||||
const sidepanelIndex = html.indexOf('<script src="sidepanel.js"></script>');
|
||||
|
||||
assert.match(html, /id="btn-contribution-mode"/);
|
||||
assert.match(html, /id="contribution-mode-panel"/);
|
||||
assert.match(html, /id="contribution-oauth-status"/);
|
||||
assert.match(html, /id="contribution-callback-status"/);
|
||||
assert.match(html, /id="contribution-mode-summary"/);
|
||||
assert.match(html, /id="btn-start-contribution"/);
|
||||
assert.match(html, /id="btn-open-contribution-upload"/);
|
||||
assert.match(html, /id="btn-exit-contribution-mode"/);
|
||||
assert.match(html, /id="input-contribution-nickname"/);
|
||||
assert.match(html, /id="input-contribution-qq"/);
|
||||
assert.notEqual(moduleIndex, -1);
|
||||
assert.notEqual(sidepanelIndex, -1);
|
||||
assert.ok(moduleIndex < sidepanelIndex);
|
||||
});
|
||||
|
||||
test('collectSettingsPayload omits custom password and local sync settings in contribution mode', () => {
|
||||
const bundle = extractFunction('collectSettingsPayload');
|
||||
|
||||
const api = new Function(`
|
||||
let latestState = { contributionMode: true };
|
||||
let cloudflareDomainEditMode = false;
|
||||
let cloudflareTempEmailDomainEditMode = false;
|
||||
const selectCfDomain = { value: 'example.com' };
|
||||
const selectTempEmailDomain = { value: 'mail.example.com' };
|
||||
const selectPanelMode = { value: 'cpa' };
|
||||
const inputVpsUrl = { value: 'https://panel.example.com' };
|
||||
const inputVpsPassword = { value: 'panel-secret' };
|
||||
const inputSub2ApiUrl = { value: 'https://sub.example.com' };
|
||||
const inputSub2ApiEmail = { value: 'user@example.com' };
|
||||
const inputSub2ApiPassword = { value: 'sub-secret' };
|
||||
const inputSub2ApiGroup = { value: ' codex ' };
|
||||
const inputSub2ApiDefaultProxy = { value: ' proxy-a ' };
|
||||
const inputCodex2ApiUrl = { value: 'http://localhost:8080/admin/accounts' };
|
||||
const inputCodex2ApiAdminKey = { value: 'codex-admin-secret' };
|
||||
const inputPassword = { value: 'Secret123!' };
|
||||
const selectMailProvider = { value: '163' };
|
||||
const selectEmailGenerator = { value: 'duck' };
|
||||
const checkboxAutoDeleteIcloud = { checked: true };
|
||||
const selectIcloudHostPreference = { value: 'auto' };
|
||||
const inputAccountRunHistoryTextEnabled = { checked: true };
|
||||
const inputAccountRunHistoryHelperBaseUrl = { value: 'http://127.0.0.1:17373' };
|
||||
const inputInbucketHost = { value: 'inbucket.local' };
|
||||
const inputInbucketMailbox = { value: 'demo' };
|
||||
const inputHotmailRemoteBaseUrl = { value: 'https://hotmail.example.com' };
|
||||
const inputHotmailLocalBaseUrl = { value: 'http://127.0.0.1:17373' };
|
||||
const inputLuckmailApiKey = { value: 'lk-api-key' };
|
||||
const inputLuckmailBaseUrl = { value: 'https://mails.example.com' };
|
||||
const selectLuckmailEmailType = { value: 'ms_graph' };
|
||||
const inputLuckmailDomain = { value: 'luckmail.example.com' };
|
||||
const inputTempEmailBaseUrl = { value: 'https://temp.example.com' };
|
||||
const inputTempEmailAdminAuth = { value: 'admin-secret' };
|
||||
const inputTempEmailCustomAuth = { value: 'custom-secret' };
|
||||
const inputTempEmailReceiveMailbox = { value: 'relay@example.com' };
|
||||
const inputTempEmailUseRandomSubdomain = { checked: true };
|
||||
const inputAutoSkipFailures = { checked: false };
|
||||
const inputAutoSkipFailuresThreadIntervalMinutes = { value: '5' };
|
||||
const inputAutoDelayEnabled = { checked: true };
|
||||
const inputAutoDelayMinutes = { value: '30' };
|
||||
const inputAutoStepDelaySeconds = { value: '10' };
|
||||
const inputVerificationResendCount = { value: '6' };
|
||||
const DEFAULT_VERIFICATION_RESEND_COUNT = 4;
|
||||
|
||||
function getCloudflareDomainsFromState() { return { domains: ['example.com'], activeDomain: 'example.com' }; }
|
||||
function normalizeCloudflareDomainValue(value) { return String(value || '').trim(); }
|
||||
function getCloudflareTempEmailDomainsFromState() { return { domains: ['mail.example.com'], activeDomain: 'mail.example.com' }; }
|
||||
function normalizeCloudflareTempEmailDomainValue(value) { return String(value || '').trim(); }
|
||||
function getSelectedLocalCpaStep9Mode() { return 'submit'; }
|
||||
function getSelectedMail2925Mode() { return 'provide'; }
|
||||
function normalizeAccountRunHistoryHelperBaseUrlValue(value) { return String(value || '').trim(); }
|
||||
function buildManagedAliasBaseEmailPayload() { return { gmailBaseEmail: '', mail2925BaseEmail: '', emailPrefix: '' }; }
|
||||
function getSelectedHotmailServiceMode() { return 'local'; }
|
||||
function normalizeLuckmailBaseUrl(value) { return String(value || '').trim(); }
|
||||
function normalizeLuckmailEmailType(value) { return String(value || '').trim(); }
|
||||
function normalizeCloudflareTempEmailBaseUrlValue(value) { return String(value || '').trim(); }
|
||||
function normalizeCloudflareTempEmailReceiveMailboxValue(value) { return String(value || '').trim(); }
|
||||
function normalizeAutoRunThreadIntervalMinutes(value) { return Number(value) || 0; }
|
||||
function normalizeAutoDelayMinutes(value) { return Number(value) || 30; }
|
||||
function normalizeAutoStepDelaySeconds(value) { return value === '' ? null : Number(value); }
|
||||
function normalizeVerificationResendCount(value, fallback) { return Number.isFinite(Number(value)) ? Number(value) : fallback; }
|
||||
${bundle}
|
||||
return {
|
||||
collectSettingsPayload,
|
||||
setLatestState(nextState) { latestState = nextState; },
|
||||
};
|
||||
`)();
|
||||
|
||||
const contributionPayload = api.collectSettingsPayload();
|
||||
assert.equal('customPassword' in contributionPayload, false);
|
||||
assert.equal('accountRunHistoryTextEnabled' in contributionPayload, false);
|
||||
assert.equal('accountRunHistoryHelperBaseUrl' in contributionPayload, false);
|
||||
assert.equal(contributionPayload.cloudflareTempEmailUseRandomSubdomain, true);
|
||||
|
||||
api.setLatestState({ contributionMode: false });
|
||||
const normalPayload = api.collectSettingsPayload();
|
||||
assert.equal(normalPayload.customPassword, 'Secret123!');
|
||||
assert.equal(normalPayload.accountRunHistoryTextEnabled, true);
|
||||
assert.equal(normalPayload.accountRunHistoryHelperBaseUrl, 'http://127.0.0.1:17373');
|
||||
assert.equal(normalPayload.codex2apiUrl, 'http://localhost:8080/admin/accounts');
|
||||
assert.equal(normalPayload.codex2apiAdminKey, 'codex-admin-secret');
|
||||
assert.equal(normalPayload.cloudflareTempEmailUseRandomSubdomain, true);
|
||||
});
|
||||
|
||||
test('contribution mode manager enters mode, starts main auto flow, polls contribution status, and exits cleanly', async () => {
|
||||
const source = fs.readFileSync('sidepanel/contribution-mode.js', 'utf8');
|
||||
const windowObject = {};
|
||||
const timers = [];
|
||||
|
||||
const api = new Function('window', 'setTimeout', 'clearTimeout', `${source}; return window.SidepanelContributionMode;`)(
|
||||
windowObject,
|
||||
(handler) => {
|
||||
timers.push(handler);
|
||||
return timers.length;
|
||||
},
|
||||
(id) => {
|
||||
if (timers[id - 1]) {
|
||||
timers[id - 1] = null;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
assert.equal(typeof api?.createContributionModeManager, 'function');
|
||||
|
||||
let latestState = {
|
||||
contributionMode: false,
|
||||
panelMode: 'sub2api',
|
||||
contributionSessionId: '',
|
||||
contributionStatus: '',
|
||||
contributionStatusMessage: '',
|
||||
contributionCallbackStatus: 'idle',
|
||||
contributionCallbackMessage: '',
|
||||
email: 'user@example.com',
|
||||
};
|
||||
let blocked = false;
|
||||
let appliedState = null;
|
||||
let statusState = null;
|
||||
let closeConfigMenuCount = 0;
|
||||
let closeAccountRecordsCount = 0;
|
||||
let contributionAutoRunStartCount = 0;
|
||||
let updatePanelModeCount = 0;
|
||||
let updateSyncUiCount = 0;
|
||||
let updateConfigMenuCount = 0;
|
||||
const toasts = [];
|
||||
const openedUrls = [];
|
||||
const sentMessages = [];
|
||||
|
||||
const dom = {
|
||||
btnConfigMenu: createElement(),
|
||||
btnContributionMode: createElement(),
|
||||
btnExitContributionMode: createElement(),
|
||||
btnOpenAccountRecords: createElement(),
|
||||
btnOpenContributionUpload: createElement(),
|
||||
btnStartContribution: createElement(),
|
||||
inputContributionNickname: createElement({ value: '贡献者昵称' }),
|
||||
inputContributionQq: createElement({ value: '123456' }),
|
||||
contributionCallbackStatus: createElement(),
|
||||
contributionModePanel: createElement({ hidden: true }),
|
||||
contributionModeSummary: createElement(),
|
||||
contributionModeText: createElement(),
|
||||
contributionOauthStatus: createElement(),
|
||||
rowAccountRunHistoryHelperBaseUrl: createElement(),
|
||||
rowAccountRunHistoryTextEnabled: createElement(),
|
||||
rowCustomPassword: createElement(),
|
||||
rowLocalCpaStep9Mode: createElement(),
|
||||
rowSub2ApiDefaultProxy: createElement(),
|
||||
rowSub2ApiEmail: createElement(),
|
||||
rowSub2ApiGroup: createElement(),
|
||||
rowSub2ApiPassword: createElement(),
|
||||
rowSub2ApiUrl: createElement(),
|
||||
rowCodex2ApiUrl: createElement(),
|
||||
rowCodex2ApiAdminKey: createElement(),
|
||||
rowVpsPassword: createElement(),
|
||||
rowVpsUrl: createElement(),
|
||||
selectPanelMode: createElement({ value: 'sub2api' }),
|
||||
};
|
||||
|
||||
const manager = api.createContributionModeManager({
|
||||
state: {
|
||||
getLatestState: () => latestState,
|
||||
},
|
||||
dom,
|
||||
helpers: {
|
||||
applySettingsState(nextState) {
|
||||
latestState = nextState;
|
||||
appliedState = nextState;
|
||||
},
|
||||
closeAccountRecordsPanel() {
|
||||
closeAccountRecordsCount += 1;
|
||||
},
|
||||
closeConfigMenu() {
|
||||
closeConfigMenuCount += 1;
|
||||
},
|
||||
getContributionNickname() {
|
||||
return latestState.email;
|
||||
},
|
||||
getContributionProfile() {
|
||||
return {
|
||||
nickname: dom.inputContributionNickname.value,
|
||||
qq: dom.inputContributionQq.value,
|
||||
};
|
||||
},
|
||||
isModeSwitchBlocked() {
|
||||
return blocked;
|
||||
},
|
||||
openConfirmModal: async () => {
|
||||
throw new Error('should not ask for confirmation before entering contribution mode');
|
||||
},
|
||||
openExternalUrl(url) {
|
||||
openedUrls.push(url);
|
||||
},
|
||||
showToast(message, type) {
|
||||
toasts.push({ message, type });
|
||||
},
|
||||
async startContributionAutoRun() {
|
||||
contributionAutoRunStartCount += 1;
|
||||
latestState = {
|
||||
...latestState,
|
||||
contributionSessionId: 'session-002',
|
||||
contributionAuthUrl: 'https://auth.example.com/oauth?state=oauth-state-002',
|
||||
contributionAuthState: 'oauth-state-002',
|
||||
contributionStatus: 'started',
|
||||
contributionStatusMessage: '\u5df2\u751f\u6210\u767b\u5f55\u5730\u5740',
|
||||
contributionCallbackStatus: 'waiting',
|
||||
contributionCallbackMessage: '\u7b49\u5f85\u56de\u8c03',
|
||||
};
|
||||
return true;
|
||||
},
|
||||
updateAccountRunHistorySettingsUI() {
|
||||
updateSyncUiCount += 1;
|
||||
},
|
||||
updateConfigMenuControls() {
|
||||
updateConfigMenuCount += 1;
|
||||
},
|
||||
updatePanelModeUI() {
|
||||
updatePanelModeCount += 1;
|
||||
},
|
||||
updateStatusDisplay(nextState) {
|
||||
statusState = nextState;
|
||||
},
|
||||
},
|
||||
runtime: {
|
||||
sendMessage: async (message) => {
|
||||
sentMessages.push(message);
|
||||
if (message.type === 'SET_CONTRIBUTION_MODE') {
|
||||
return {
|
||||
state: message.payload.enabled
|
||||
? {
|
||||
contributionMode: true,
|
||||
panelMode: 'cpa',
|
||||
contributionNickname: '',
|
||||
contributionQq: '',
|
||||
contributionSessionId: '',
|
||||
contributionAuthUrl: '',
|
||||
contributionAuthState: '',
|
||||
contributionStatus: '',
|
||||
contributionStatusMessage: '',
|
||||
contributionCallbackStatus: 'idle',
|
||||
contributionCallbackMessage: '',
|
||||
email: latestState.email,
|
||||
}
|
||||
: {
|
||||
contributionMode: false,
|
||||
panelMode: 'cpa',
|
||||
contributionNickname: '',
|
||||
contributionQq: '',
|
||||
contributionSessionId: '',
|
||||
contributionAuthUrl: '',
|
||||
contributionAuthState: '',
|
||||
contributionCallbackUrl: '',
|
||||
contributionStatus: '',
|
||||
contributionStatusMessage: '',
|
||||
contributionCallbackStatus: 'idle',
|
||||
contributionCallbackMessage: '',
|
||||
email: latestState.email,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (message.type === 'POLL_CONTRIBUTION_STATUS') {
|
||||
return {
|
||||
state: {
|
||||
...latestState,
|
||||
contributionStatus: 'processing',
|
||||
contributionStatusMessage: '已提交回调,等待 CPA 确认',
|
||||
contributionCallbackStatus: 'submitted',
|
||||
contributionCallbackMessage: '已提交回调',
|
||||
},
|
||||
};
|
||||
}
|
||||
if (message.type === 'SET_CONTRIBUTION_PROFILE') {
|
||||
latestState = {
|
||||
...latestState,
|
||||
contributionNickname: message.payload.nickname,
|
||||
contributionQq: message.payload.qq,
|
||||
};
|
||||
return { state: latestState };
|
||||
}
|
||||
return {};
|
||||
},
|
||||
},
|
||||
constants: {
|
||||
contributionUploadUrl: 'https://apikey.qzz.io',
|
||||
pollIntervalMs: 2500,
|
||||
},
|
||||
});
|
||||
|
||||
manager.render();
|
||||
assert.equal(dom.contributionModePanel.hidden, true);
|
||||
assert.equal(dom.btnContributionMode.disabled, false);
|
||||
|
||||
manager.bindEvents();
|
||||
await dom.btnContributionMode.listeners.click();
|
||||
|
||||
assert.equal(dom.contributionModePanel.hidden, false);
|
||||
assert.equal(dom.selectPanelMode.value, 'cpa');
|
||||
assert.equal(dom.selectPanelMode.disabled, true);
|
||||
assert.equal(dom.btnOpenAccountRecords.disabled, true);
|
||||
assert.equal(dom.contributionOauthStatus.textContent, '\u672a\u751f\u6210\u767b\u5f55\u5730\u5740');
|
||||
assert.equal(dom.contributionCallbackStatus.textContent, '\u7b49\u5f85\u56de\u8c03');
|
||||
assert.equal(dom.contributionModeSummary.textContent.length > 0, true);
|
||||
assert.equal(dom.btnContributionMode.classList.contains('is-active'), true);
|
||||
assert.equal(dom.rowVpsUrl.classList.contains('is-contribution-hidden'), true);
|
||||
assert.equal(dom.rowCodex2ApiUrl.classList.contains('is-contribution-hidden'), true);
|
||||
assert.equal(dom.rowCodex2ApiAdminKey.classList.contains('is-contribution-hidden'), true);
|
||||
assert.ok(closeConfigMenuCount >= 1);
|
||||
assert.ok(closeAccountRecordsCount >= 1);
|
||||
assert.ok(updatePanelModeCount >= 1);
|
||||
assert.ok(updateSyncUiCount >= 1);
|
||||
assert.ok(updateConfigMenuCount >= 1);
|
||||
assert.equal(timers.length, 0);
|
||||
assert.deepStrictEqual(openedUrls, ['https://apikey.qzz.io']);
|
||||
|
||||
dom.inputContributionNickname.value = '贡献者昵称';
|
||||
dom.inputContributionQq.value = '123456';
|
||||
|
||||
await dom.btnStartContribution.listeners.click();
|
||||
assert.equal(contributionAutoRunStartCount, 1);
|
||||
assert.equal(appliedState.contributionSessionId, '');
|
||||
assert.equal(latestState.contributionSessionId, 'session-002');
|
||||
assert.equal(latestState.contributionStatus, 'started');
|
||||
const contributionProfileMessage = sentMessages.find((message) => message.type === 'SET_CONTRIBUTION_PROFILE');
|
||||
assert.deepStrictEqual(contributionProfileMessage?.payload, { nickname: '贡献者昵称', qq: '123456' });
|
||||
assert.equal(timers.length > 0, true);
|
||||
|
||||
await manager.pollOnce({ reason: 'test_poll' });
|
||||
assert.equal(statusState.contributionStatus, 'processing');
|
||||
assert.equal(dom.contributionOauthStatus.textContent, '\u5df2\u63d0\u4ea4\u56de\u8c03');
|
||||
assert.equal(dom.contributionCallbackStatus.textContent, '\u5df2\u63d0\u4ea4\u56de\u8c03');
|
||||
assert.equal(dom.contributionModeSummary.textContent, '\u5df2\u63d0\u4ea4\u56de\u8c03\uff0c\u7b49\u5f85 CPA \u786e\u8ba4');
|
||||
|
||||
dom.btnOpenContributionUpload.listeners.click();
|
||||
assert.deepStrictEqual(openedUrls, ['https://apikey.qzz.io', 'https://apikey.qzz.io']);
|
||||
|
||||
await dom.btnExitContributionMode.listeners.click();
|
||||
manager.render();
|
||||
assert.equal(dom.contributionModePanel.hidden, true);
|
||||
assert.equal(dom.btnContributionMode.classList.contains('is-active'), false);
|
||||
assert.equal(dom.selectPanelMode.disabled, false);
|
||||
assert.equal(dom.rowVpsUrl.classList.contains('is-contribution-hidden'), false);
|
||||
assert.deepStrictEqual(
|
||||
sentMessages.map((message) => message.type),
|
||||
['SET_CONTRIBUTION_MODE', 'SET_CONTRIBUTION_PROFILE', 'POLL_CONTRIBUTION_STATUS', 'SET_CONTRIBUTION_MODE']
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
toasts.map((item) => item.message),
|
||||
['\u5df2\u8fdb\u5165\u8d21\u732e\u6a21\u5f0f\u3002', '\u8d21\u732e\u81ea\u52a8\u6d41\u7a0b\u5df2\u542f\u52a8\u3002', '\u5df2\u9000\u51fa\u8d21\u732e\u6a21\u5f0f\u3002']
|
||||
);
|
||||
|
||||
blocked = true;
|
||||
latestState = {
|
||||
contributionMode: true,
|
||||
panelMode: 'cpa',
|
||||
contributionNickname: '贡献者昵称',
|
||||
contributionQq: '123456',
|
||||
contributionSessionId: 'session-002',
|
||||
contributionAuthUrl: 'https://auth.example.com/oauth?state=oauth-state-002',
|
||||
contributionStatus: 'waiting',
|
||||
contributionStatusMessage: '\u7b49\u5f85\u6388\u6743\u5b8c\u6210',
|
||||
contributionCallbackStatus: 'waiting',
|
||||
contributionCallbackMessage: '\u7b49\u5f85\u56de\u8c03',
|
||||
};
|
||||
manager.render();
|
||||
assert.equal(dom.btnExitContributionMode.disabled, true);
|
||||
manager.stopPolling();
|
||||
});
|
||||
@@ -2,19 +2,74 @@ const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
function createAccountPoolUiStub() {
|
||||
return {
|
||||
createAccountPoolFormController({
|
||||
formShell,
|
||||
toggleButton,
|
||||
hiddenLabel = '添加账号',
|
||||
visibleLabel = '取消添加',
|
||||
onClear,
|
||||
onFocus,
|
||||
} = {}) {
|
||||
let visible = false;
|
||||
|
||||
function sync() {
|
||||
if (formShell) {
|
||||
formShell.hidden = !visible;
|
||||
}
|
||||
if (toggleButton) {
|
||||
toggleButton.textContent = visible ? visibleLabel : hiddenLabel;
|
||||
toggleButton.setAttribute?.('aria-expanded', String(visible));
|
||||
}
|
||||
}
|
||||
|
||||
function setVisible(nextVisible, options = {}) {
|
||||
visible = Boolean(nextVisible);
|
||||
if (options.clearForm) {
|
||||
onClear?.();
|
||||
}
|
||||
sync();
|
||||
if (visible && options.focusField) {
|
||||
onFocus?.();
|
||||
}
|
||||
}
|
||||
|
||||
sync();
|
||||
return {
|
||||
isVisible: () => visible,
|
||||
setVisible,
|
||||
sync,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('sidepanel loads hotmail manager before sidepanel bootstrap', () => {
|
||||
const html = fs.readFileSync('sidepanel/sidepanel.html', 'utf8');
|
||||
const helperIndex = html.indexOf('<script src="account-pool-ui.js"></script>');
|
||||
const hotmailManagerIndex = html.indexOf('<script src="hotmail-manager.js"></script>');
|
||||
const sidepanelIndex = html.indexOf('<script src="sidepanel.js"></script>');
|
||||
|
||||
assert.notEqual(helperIndex, -1);
|
||||
assert.notEqual(hotmailManagerIndex, -1);
|
||||
assert.notEqual(sidepanelIndex, -1);
|
||||
assert.ok(helperIndex < hotmailManagerIndex);
|
||||
assert.ok(hotmailManagerIndex < sidepanelIndex);
|
||||
});
|
||||
|
||||
test('sidepanel html contains collapsible hotmail form controls', () => {
|
||||
const html = fs.readFileSync('sidepanel/sidepanel.html', 'utf8');
|
||||
assert.match(html, /id="btn-toggle-hotmail-form"/);
|
||||
assert.match(html, /id="hotmail-form-shell"/);
|
||||
assert.match(html, /id="btn-import-hotmail-accounts"[^>]*>批量导入</);
|
||||
});
|
||||
|
||||
test('hotmail manager exposes a factory and renders empty state', () => {
|
||||
const source = fs.readFileSync('sidepanel/hotmail-manager.js', 'utf8');
|
||||
const windowObject = {};
|
||||
const windowObject = {
|
||||
SidepanelAccountPoolUi: createAccountPoolUiStub(),
|
||||
};
|
||||
const localStorageMock = {
|
||||
getItem() {
|
||||
return null;
|
||||
@@ -77,3 +132,199 @@ test('hotmail manager exposes a factory and renders empty state', () => {
|
||||
manager.renderHotmailAccounts();
|
||||
assert.match(hotmailAccountsList.innerHTML, /还没有 Hotmail 账号/);
|
||||
});
|
||||
|
||||
test('hotmail manager toggles form container from header button', () => {
|
||||
const source = fs.readFileSync('sidepanel/hotmail-manager.js', 'utf8');
|
||||
const windowObject = {
|
||||
SidepanelAccountPoolUi: createAccountPoolUiStub(),
|
||||
};
|
||||
const localStorageMock = {
|
||||
getItem() {
|
||||
return null;
|
||||
},
|
||||
setItem() {},
|
||||
};
|
||||
|
||||
const api = new Function('window', 'localStorage', `${source}; return window.SidepanelHotmailManager;`)(
|
||||
windowObject,
|
||||
localStorageMock
|
||||
);
|
||||
|
||||
const handlers = {};
|
||||
const toggleFormButton = {
|
||||
textContent: '',
|
||||
disabled: false,
|
||||
setAttribute(name, value) {
|
||||
this[name] = value;
|
||||
},
|
||||
addEventListener(type, handler) {
|
||||
if (type === 'click') handlers.toggleForm = handler;
|
||||
},
|
||||
};
|
||||
const formShell = { hidden: true };
|
||||
|
||||
const manager = api.createHotmailManager({
|
||||
state: {
|
||||
getLatestState: () => ({ currentHotmailAccountId: null }),
|
||||
syncLatestState() {},
|
||||
},
|
||||
dom: {
|
||||
btnAddHotmailAccount: { textContent: '', disabled: false, addEventListener() {} },
|
||||
btnClearUsedHotmailAccounts: { textContent: '', disabled: false, addEventListener() {} },
|
||||
btnDeleteAllHotmailAccounts: { textContent: '', disabled: false, addEventListener() {} },
|
||||
btnHotmailUsageGuide: { addEventListener() {} },
|
||||
btnImportHotmailAccounts: { disabled: false, addEventListener() {} },
|
||||
btnToggleHotmailForm: toggleFormButton,
|
||||
btnToggleHotmailList: { textContent: '', disabled: false, setAttribute() {}, addEventListener() {} },
|
||||
hotmailAccountsList: { innerHTML: '', addEventListener() {} },
|
||||
hotmailFormShell: formShell,
|
||||
hotmailListShell: { classList: { toggle() {} } },
|
||||
inputEmail: { value: '' },
|
||||
inputHotmailClientId: { value: '' },
|
||||
inputHotmailEmail: { value: '', focus() { this.focused = true; } },
|
||||
inputHotmailImport: { value: '' },
|
||||
inputHotmailPassword: { value: '' },
|
||||
inputHotmailRefreshToken: { value: '' },
|
||||
selectMailProvider: { value: 'hotmail-api' },
|
||||
},
|
||||
helpers: {
|
||||
getHotmailAccounts: () => [],
|
||||
getCurrentHotmailEmail: () => '',
|
||||
escapeHtml: (value) => String(value || ''),
|
||||
showToast() {},
|
||||
openConfirmModal: async () => true,
|
||||
copyTextToClipboard: async () => {},
|
||||
},
|
||||
runtime: {
|
||||
sendMessage: async () => ({}),
|
||||
},
|
||||
constants: {
|
||||
copyIcon: '',
|
||||
displayTimeZone: 'Asia/Shanghai',
|
||||
expandedStorageKey: 'multipage-hotmail-list-expanded',
|
||||
},
|
||||
hotmailUtils: {},
|
||||
});
|
||||
|
||||
manager.bindHotmailEvents();
|
||||
assert.equal(formShell.hidden, true);
|
||||
assert.equal(toggleFormButton.textContent, '添加账号');
|
||||
|
||||
handlers.toggleForm();
|
||||
assert.equal(formShell.hidden, false);
|
||||
assert.equal(toggleFormButton.textContent, '取消添加');
|
||||
|
||||
handlers.toggleForm();
|
||||
assert.equal(formShell.hidden, true);
|
||||
assert.equal(toggleFormButton.textContent, '添加账号');
|
||||
});
|
||||
|
||||
test('hotmail manager hides form after save succeeds', async () => {
|
||||
const source = fs.readFileSync('sidepanel/hotmail-manager.js', 'utf8');
|
||||
const windowObject = {
|
||||
SidepanelAccountPoolUi: createAccountPoolUiStub(),
|
||||
};
|
||||
const localStorageMock = {
|
||||
getItem() {
|
||||
return null;
|
||||
},
|
||||
setItem() {},
|
||||
};
|
||||
|
||||
const api = new Function('window', 'localStorage', `${source}; return window.SidepanelHotmailManager;`)(
|
||||
windowObject,
|
||||
localStorageMock
|
||||
);
|
||||
|
||||
const handlers = {};
|
||||
const formShell = { hidden: true };
|
||||
const toggleFormButton = {
|
||||
textContent: '',
|
||||
disabled: false,
|
||||
setAttribute() {},
|
||||
addEventListener(type, handler) {
|
||||
if (type === 'click') handlers.toggleForm = handler;
|
||||
},
|
||||
};
|
||||
const addButton = {
|
||||
textContent: '',
|
||||
disabled: false,
|
||||
addEventListener(type, handler) {
|
||||
if (type === 'click') handlers.add = handler;
|
||||
},
|
||||
};
|
||||
const inputHotmailEmail = { value: '', focus() {} };
|
||||
const inputHotmailClientId = { value: '' };
|
||||
const inputHotmailPassword = { value: '' };
|
||||
const inputHotmailRefreshToken = { value: '' };
|
||||
const toastMessages = [];
|
||||
|
||||
const manager = api.createHotmailManager({
|
||||
state: {
|
||||
getLatestState: () => ({ currentHotmailAccountId: null }),
|
||||
syncLatestState() {},
|
||||
},
|
||||
dom: {
|
||||
btnAddHotmailAccount: addButton,
|
||||
btnClearUsedHotmailAccounts: { textContent: '', disabled: false, addEventListener() {} },
|
||||
btnDeleteAllHotmailAccounts: { textContent: '', disabled: false, addEventListener() {} },
|
||||
btnHotmailUsageGuide: { addEventListener() {} },
|
||||
btnImportHotmailAccounts: { disabled: false, addEventListener() {} },
|
||||
btnToggleHotmailForm: toggleFormButton,
|
||||
btnToggleHotmailList: { textContent: '', disabled: false, setAttribute() {}, addEventListener() {} },
|
||||
hotmailAccountsList: { innerHTML: '', addEventListener() {} },
|
||||
hotmailFormShell: formShell,
|
||||
hotmailListShell: { classList: { toggle() {} } },
|
||||
inputEmail: { value: '' },
|
||||
inputHotmailClientId,
|
||||
inputHotmailEmail,
|
||||
inputHotmailImport: { value: '' },
|
||||
inputHotmailPassword,
|
||||
inputHotmailRefreshToken,
|
||||
selectMailProvider: { value: 'hotmail-api' },
|
||||
},
|
||||
helpers: {
|
||||
getHotmailAccounts: () => [],
|
||||
getCurrentHotmailEmail: () => '',
|
||||
escapeHtml: (value) => String(value || ''),
|
||||
showToast(message) {
|
||||
toastMessages.push(message);
|
||||
},
|
||||
openConfirmModal: async () => true,
|
||||
copyTextToClipboard: async () => {},
|
||||
},
|
||||
runtime: {
|
||||
sendMessage: async () => ({
|
||||
account: {
|
||||
id: 'acc-1',
|
||||
email: 'demo@hotmail.com',
|
||||
clientId: 'client-id',
|
||||
refreshToken: 'refresh-token',
|
||||
},
|
||||
}),
|
||||
},
|
||||
constants: {
|
||||
copyIcon: '',
|
||||
displayTimeZone: 'Asia/Shanghai',
|
||||
expandedStorageKey: 'multipage-hotmail-list-expanded',
|
||||
},
|
||||
hotmailUtils: {},
|
||||
});
|
||||
|
||||
manager.bindHotmailEvents();
|
||||
handlers.toggleForm();
|
||||
inputHotmailEmail.value = 'demo@hotmail.com';
|
||||
inputHotmailClientId.value = 'client-id';
|
||||
inputHotmailPassword.value = 'secret';
|
||||
inputHotmailRefreshToken.value = 'refresh-token';
|
||||
|
||||
await handlers.add();
|
||||
|
||||
assert.equal(formShell.hidden, true);
|
||||
assert.equal(toggleFormButton.textContent, '添加账号');
|
||||
assert.equal(inputHotmailEmail.value, '');
|
||||
assert.equal(inputHotmailClientId.value, '');
|
||||
assert.equal(inputHotmailPassword.value, '');
|
||||
assert.equal(inputHotmailRefreshToken.value, '');
|
||||
assert.match(toastMessages.at(-1) || '', /已保存 Hotmail 账号/);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const sidepanelSource = fs.readFileSync('sidepanel/sidepanel.js', 'utf8');
|
||||
|
||||
function extractFunction(name) {
|
||||
const markers = [`async function ${name}(`, `function ${name}(`];
|
||||
const start = markers
|
||||
.map((marker) => sidepanelSource.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 < sidepanelSource.length; i += 1) {
|
||||
const ch = sidepanelSource[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 < sidepanelSource.length; end += 1) {
|
||||
const ch = sidepanelSource[end];
|
||||
if (ch === '{') depth += 1;
|
||||
if (ch === '}') {
|
||||
depth -= 1;
|
||||
if (depth === 0) {
|
||||
end += 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sidepanelSource.slice(start, end);
|
||||
}
|
||||
|
||||
test('syncSelectedMail2925PoolAccount writes selected pool email back to mail2925BaseEmail', async () => {
|
||||
const bundle = [
|
||||
extractFunction('getMail2925Accounts'),
|
||||
extractFunction('getCurrentMail2925Account'),
|
||||
extractFunction('getCurrentMail2925Email'),
|
||||
extractFunction('isMail2925AccountPoolEnabled'),
|
||||
extractFunction('syncMail2925PoolAccountOptions'),
|
||||
extractFunction('getPreferredMail2925PoolAccountId'),
|
||||
extractFunction('syncSelectedMail2925PoolAccount'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
let latestState = {
|
||||
mail2925UseAccountPool: true,
|
||||
mail2925BaseEmail: 'old@2925.com',
|
||||
currentMail2925AccountId: '',
|
||||
mail2925Accounts: [{ id: 'acc-1', email: 'new@2925.com' }],
|
||||
};
|
||||
const selectMail2925PoolAccount = { value: 'acc-1', innerHTML: '' };
|
||||
const chrome = {
|
||||
runtime: {
|
||||
async sendMessage() {
|
||||
return { account: { id: 'acc-1', email: 'new@2925.com' } };
|
||||
},
|
||||
},
|
||||
};
|
||||
const toastEvents = [];
|
||||
function syncLatestState(patch) {
|
||||
latestState = { ...latestState, ...patch };
|
||||
}
|
||||
function setManagedAliasBaseEmailInputForProvider() {}
|
||||
function showToast(message) {
|
||||
toastEvents.push(message);
|
||||
}
|
||||
function escapeHtml(value) {
|
||||
return String(value || '');
|
||||
}
|
||||
${bundle}
|
||||
return {
|
||||
syncSelectedMail2925PoolAccount,
|
||||
getLatestState() {
|
||||
return latestState;
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
await api.syncSelectedMail2925PoolAccount({ silent: true });
|
||||
|
||||
assert.equal(api.getLatestState().currentMail2925AccountId, 'acc-1');
|
||||
assert.equal(api.getLatestState().mail2925BaseEmail, 'new@2925.com');
|
||||
});
|
||||
|
||||
test('syncMail2925BaseEmailFromCurrentAccount reuses current pool account email for manual base email field', async () => {
|
||||
const bundle = [
|
||||
extractFunction('getMail2925Accounts'),
|
||||
extractFunction('getCurrentMail2925Account'),
|
||||
extractFunction('getCurrentMail2925Email'),
|
||||
extractFunction('isMail2925AccountPoolEnabled'),
|
||||
extractFunction('syncMail2925BaseEmailFromCurrentAccount'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
let latestState = {
|
||||
mail2925UseAccountPool: true,
|
||||
mail2925BaseEmail: 'old@2925.com',
|
||||
currentMail2925AccountId: 'acc-1',
|
||||
mail2925Accounts: [{ id: 'acc-1', email: 'new@2925.com' }],
|
||||
};
|
||||
let saveCalls = 0;
|
||||
function syncLatestState(patch) {
|
||||
latestState = { ...latestState, ...patch };
|
||||
}
|
||||
async function saveSettings() {
|
||||
saveCalls += 1;
|
||||
}
|
||||
${bundle}
|
||||
return {
|
||||
syncMail2925BaseEmailFromCurrentAccount,
|
||||
getLatestState() {
|
||||
return latestState;
|
||||
},
|
||||
getSaveCalls() {
|
||||
return saveCalls;
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
const changed = api.syncMail2925BaseEmailFromCurrentAccount(undefined, { persist: true });
|
||||
await Promise.resolve();
|
||||
|
||||
assert.equal(changed, true);
|
||||
assert.equal(api.getLatestState().mail2925BaseEmail, 'new@2925.com');
|
||||
assert.equal(api.getSaveCalls(), 1);
|
||||
});
|
||||
|
||||
test('collectSettingsPayload persists currentMail2925AccountId for 2925 account pool restore', () => {
|
||||
const bundle = [
|
||||
extractFunction('collectSettingsPayload'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
let latestState = {
|
||||
contributionMode: false,
|
||||
mail2925UseAccountPool: true,
|
||||
currentMail2925AccountId: 'acc-2',
|
||||
};
|
||||
let cloudflareDomainEditMode = false;
|
||||
let cloudflareTempEmailDomainEditMode = false;
|
||||
const selectCfDomain = { value: 'example.com' };
|
||||
const selectTempEmailDomain = { value: 'mail.example.com' };
|
||||
const selectPanelMode = { value: 'cpa' };
|
||||
const inputVpsUrl = { value: '' };
|
||||
const inputVpsPassword = { value: '' };
|
||||
const inputSub2ApiUrl = { value: '' };
|
||||
const inputSub2ApiEmail = { value: '' };
|
||||
const inputSub2ApiPassword = { value: '' };
|
||||
const inputSub2ApiGroup = { value: '' };
|
||||
const inputSub2ApiDefaultProxy = { value: '' };
|
||||
const inputCodex2ApiUrl = { value: '' };
|
||||
const inputCodex2ApiAdminKey = { value: '' };
|
||||
const inputPassword = { value: '' };
|
||||
const selectMailProvider = { value: '2925' };
|
||||
const selectEmailGenerator = { value: 'duck' };
|
||||
const checkboxAutoDeleteIcloud = { checked: false };
|
||||
const selectIcloudHostPreference = { value: 'auto' };
|
||||
const inputAccountRunHistoryTextEnabled = { checked: false };
|
||||
const inputAccountRunHistoryHelperBaseUrl = { value: '' };
|
||||
const inputMail2925UseAccountPool = { checked: true };
|
||||
const inputInbucketHost = { value: '' };
|
||||
const inputInbucketMailbox = { value: '' };
|
||||
const inputHotmailRemoteBaseUrl = { value: '' };
|
||||
const inputHotmailLocalBaseUrl = { value: '' };
|
||||
const inputLuckmailApiKey = { value: '' };
|
||||
const inputLuckmailBaseUrl = { value: '' };
|
||||
const selectLuckmailEmailType = { value: 'ms_graph' };
|
||||
const inputLuckmailDomain = { value: '' };
|
||||
const inputTempEmailBaseUrl = { value: '' };
|
||||
const inputTempEmailAdminAuth = { value: '' };
|
||||
const inputTempEmailCustomAuth = { value: '' };
|
||||
const inputTempEmailReceiveMailbox = { value: '' };
|
||||
const inputTempEmailUseRandomSubdomain = { checked: false };
|
||||
const inputAutoSkipFailures = { checked: false };
|
||||
const inputAutoSkipFailuresThreadIntervalMinutes = { value: '0' };
|
||||
const inputAutoDelayEnabled = { checked: false };
|
||||
const inputAutoDelayMinutes = { value: '30' };
|
||||
const inputAutoStepDelaySeconds = { value: '' };
|
||||
const inputVerificationResendCount = { value: '4' };
|
||||
const DEFAULT_VERIFICATION_RESEND_COUNT = 4;
|
||||
function getCloudflareDomainsFromState() {
|
||||
return { domains: [], activeDomain: '' };
|
||||
}
|
||||
function normalizeCloudflareDomainValue(value) { return String(value || '').trim(); }
|
||||
function getCloudflareTempEmailDomainsFromState() {
|
||||
return { domains: [], activeDomain: '' };
|
||||
}
|
||||
function normalizeCloudflareTempEmailDomainValue(value) { return String(value || '').trim(); }
|
||||
function getSelectedLocalCpaStep9Mode() { return 'submit'; }
|
||||
function getSelectedMail2925Mode() { return 'provide'; }
|
||||
function getSelectedHotmailServiceMode() { return 'local'; }
|
||||
function buildManagedAliasBaseEmailPayload() {
|
||||
return { gmailBaseEmail: '', mail2925BaseEmail: 'demo@2925.com', emailPrefix: '' };
|
||||
}
|
||||
function normalizeLuckmailBaseUrl(value) { return String(value || '').trim(); }
|
||||
function normalizeLuckmailEmailType(value) { return String(value || '').trim() || 'ms_graph'; }
|
||||
function normalizeCloudflareTempEmailBaseUrlValue(value) { return String(value || '').trim(); }
|
||||
function normalizeCloudflareTempEmailReceiveMailboxValue(value) { return String(value || '').trim(); }
|
||||
function normalizeAccountRunHistoryHelperBaseUrlValue(value) { return String(value || '').trim(); }
|
||||
function normalizeAutoRunThreadIntervalMinutes(value) { return Number(value) || 0; }
|
||||
function normalizeAutoDelayMinutes(value) { return Number(value) || 30; }
|
||||
function normalizeAutoStepDelaySeconds(value) { return value === '' ? null : Number(value); }
|
||||
function normalizeVerificationResendCount(value, fallback) { return Number(value) || fallback; }
|
||||
${bundle}
|
||||
return { collectSettingsPayload };
|
||||
`)();
|
||||
|
||||
const payload = api.collectSettingsPayload();
|
||||
|
||||
assert.equal(payload.currentMail2925AccountId, 'acc-2');
|
||||
assert.equal(payload.mail2925UseAccountPool, true);
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
function createAccountPoolUiStub() {
|
||||
return {
|
||||
createAccountPoolFormController({
|
||||
formShell,
|
||||
toggleButton,
|
||||
hiddenLabel = '添加账号',
|
||||
visibleLabel = '取消添加',
|
||||
onClear,
|
||||
onFocus,
|
||||
} = {}) {
|
||||
let visible = false;
|
||||
|
||||
function sync() {
|
||||
if (formShell) {
|
||||
formShell.hidden = !visible;
|
||||
}
|
||||
if (toggleButton) {
|
||||
toggleButton.textContent = visible ? visibleLabel : hiddenLabel;
|
||||
toggleButton.setAttribute?.('aria-expanded', String(visible));
|
||||
}
|
||||
}
|
||||
|
||||
function setVisible(nextVisible, options = {}) {
|
||||
visible = Boolean(nextVisible);
|
||||
if (options.clearForm) {
|
||||
onClear?.();
|
||||
}
|
||||
sync();
|
||||
if (visible && options.focusField) {
|
||||
onFocus?.();
|
||||
}
|
||||
}
|
||||
|
||||
sync();
|
||||
return {
|
||||
isVisible: () => visible,
|
||||
setVisible,
|
||||
sync,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('sidepanel html contains collapsible mail2925 form controls', () => {
|
||||
const html = fs.readFileSync('sidepanel/sidepanel.html', 'utf8');
|
||||
assert.match(html, /id="btn-toggle-mail2925-form"/);
|
||||
assert.match(html, /id="mail2925-form-shell"/);
|
||||
assert.doesNotMatch(html, /id="btn-cancel-mail2925-edit"/);
|
||||
});
|
||||
|
||||
test('mail2925 manager renders edit action for existing accounts', () => {
|
||||
const source = fs.readFileSync('sidepanel/mail-2925-manager.js', 'utf8');
|
||||
const windowObject = {
|
||||
SidepanelAccountPoolUi: createAccountPoolUiStub(),
|
||||
};
|
||||
const localStorageMock = {
|
||||
getItem() {
|
||||
return null;
|
||||
},
|
||||
setItem() {},
|
||||
};
|
||||
|
||||
const api = new Function('window', 'localStorage', `${source}; return window.SidepanelMail2925Manager;`)(
|
||||
windowObject,
|
||||
localStorageMock
|
||||
);
|
||||
|
||||
const mail2925AccountsList = { innerHTML: '', addEventListener() {} };
|
||||
const manager = api.createMail2925Manager({
|
||||
state: {
|
||||
getLatestState: () => ({
|
||||
currentMail2925AccountId: 'acc-1',
|
||||
mail2925Accounts: [{
|
||||
id: 'acc-1',
|
||||
email: 'demo@2925.com',
|
||||
password: 'secret',
|
||||
enabled: true,
|
||||
lastLoginAt: 0,
|
||||
lastUsedAt: 0,
|
||||
lastLimitAt: 0,
|
||||
disabledUntil: 0,
|
||||
lastError: '',
|
||||
}],
|
||||
}),
|
||||
syncLatestState() {},
|
||||
},
|
||||
dom: {
|
||||
btnAddMail2925Account: { textContent: '', disabled: false, addEventListener() {} },
|
||||
btnDeleteAllMail2925Accounts: { textContent: '', disabled: false, addEventListener() {} },
|
||||
btnImportMail2925Accounts: { disabled: false, addEventListener() {} },
|
||||
btnToggleMail2925Form: { textContent: '', setAttribute() {}, addEventListener() {} },
|
||||
btnToggleMail2925List: { textContent: '', disabled: false, setAttribute() {}, addEventListener() {} },
|
||||
inputMail2925Email: { value: '' },
|
||||
inputMail2925Import: { value: '' },
|
||||
inputMail2925Password: { value: '' },
|
||||
mail2925AccountsList,
|
||||
mail2925FormShell: { hidden: true },
|
||||
mail2925ListShell: { classList: { toggle() {} } },
|
||||
},
|
||||
helpers: {
|
||||
getMail2925Accounts: (state) => state.mail2925Accounts || [],
|
||||
escapeHtml: (value) => String(value || ''),
|
||||
showToast() {},
|
||||
openConfirmModal: async () => true,
|
||||
copyTextToClipboard: async () => {},
|
||||
refreshManagedAliasBaseEmail() {},
|
||||
},
|
||||
runtime: {
|
||||
sendMessage: async () => ({}),
|
||||
},
|
||||
constants: {
|
||||
copyIcon: '',
|
||||
displayTimeZone: 'Asia/Shanghai',
|
||||
expandedStorageKey: 'multipage-mail2925-list-expanded',
|
||||
},
|
||||
mail2925Utils: {
|
||||
getMail2925AccountStatus: () => 'ready',
|
||||
getMail2925ListToggleLabel: () => '展开列表(1)',
|
||||
upsertMail2925AccountInList: (_accounts, nextAccount) => [nextAccount],
|
||||
},
|
||||
});
|
||||
|
||||
manager.renderMail2925Accounts();
|
||||
assert.match(mail2925AccountsList.innerHTML, /data-account-action="edit"/);
|
||||
});
|
||||
@@ -0,0 +1,342 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
function createAccountPoolUiStub() {
|
||||
return {
|
||||
createAccountPoolFormController({
|
||||
formShell,
|
||||
toggleButton,
|
||||
hiddenLabel = '添加账号',
|
||||
visibleLabel = '取消添加',
|
||||
onClear,
|
||||
onFocus,
|
||||
} = {}) {
|
||||
let visible = false;
|
||||
|
||||
function sync() {
|
||||
if (formShell) {
|
||||
formShell.hidden = !visible;
|
||||
}
|
||||
if (toggleButton) {
|
||||
toggleButton.textContent = visible ? visibleLabel : hiddenLabel;
|
||||
toggleButton.setAttribute?.('aria-expanded', String(visible));
|
||||
}
|
||||
}
|
||||
|
||||
function setVisible(nextVisible, options = {}) {
|
||||
visible = Boolean(nextVisible);
|
||||
if (options.clearForm) {
|
||||
onClear?.();
|
||||
}
|
||||
sync();
|
||||
if (visible && options.focusField) {
|
||||
onFocus?.();
|
||||
}
|
||||
}
|
||||
|
||||
sync();
|
||||
return {
|
||||
isVisible: () => visible,
|
||||
setVisible,
|
||||
sync,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('sidepanel loads mail2925 manager before sidepanel bootstrap', () => {
|
||||
const html = fs.readFileSync('sidepanel/sidepanel.html', 'utf8');
|
||||
const helperIndex = html.indexOf('<script src="account-pool-ui.js"></script>');
|
||||
const managerIndex = html.indexOf('<script src="mail-2925-manager.js"></script>');
|
||||
const sidepanelIndex = html.indexOf('<script src="sidepanel.js"></script>');
|
||||
|
||||
assert.notEqual(helperIndex, -1);
|
||||
assert.notEqual(managerIndex, -1);
|
||||
assert.notEqual(sidepanelIndex, -1);
|
||||
assert.ok(helperIndex < managerIndex);
|
||||
assert.ok(managerIndex < sidepanelIndex);
|
||||
});
|
||||
|
||||
test('sidepanel html contains mail2925 pool toggle and selector controls', () => {
|
||||
const html = fs.readFileSync('sidepanel/sidepanel.html', 'utf8');
|
||||
|
||||
assert.match(html, /id="input-mail2925-use-account-pool"/);
|
||||
assert.match(html, /id="select-mail2925-pool-account"/);
|
||||
assert.match(html, /id="btn-toggle-mail2925-form"/);
|
||||
assert.match(html, /id="mail2925-form-shell"/);
|
||||
assert.doesNotMatch(html, /id="btn-cancel-mail2925-edit"/);
|
||||
});
|
||||
|
||||
test('sidepanel css keeps collapsed shared mailbox list near a single card height', () => {
|
||||
const css = fs.readFileSync('sidepanel/sidepanel.css', 'utf8');
|
||||
assert.match(css, /\.hotmail-list-shell\.is-collapsed\s*\{\s*max-height:\s*176px;\s*\}/);
|
||||
});
|
||||
|
||||
test('mail2925 manager exposes a factory and renders empty state', () => {
|
||||
const source = fs.readFileSync('sidepanel/mail-2925-manager.js', 'utf8');
|
||||
const windowObject = {
|
||||
SidepanelAccountPoolUi: createAccountPoolUiStub(),
|
||||
};
|
||||
const localStorageMock = {
|
||||
getItem() {
|
||||
return null;
|
||||
},
|
||||
setItem() {},
|
||||
};
|
||||
|
||||
const api = new Function('window', 'localStorage', `${source}; return window.SidepanelMail2925Manager;`)(
|
||||
windowObject,
|
||||
localStorageMock
|
||||
);
|
||||
|
||||
assert.equal(typeof api?.createMail2925Manager, 'function');
|
||||
|
||||
const mail2925AccountsList = { innerHTML: '', addEventListener() {} };
|
||||
const formToggleButton = {
|
||||
textContent: '',
|
||||
disabled: false,
|
||||
setAttribute() {},
|
||||
addEventListener() {},
|
||||
};
|
||||
const toggleButton = {
|
||||
textContent: '',
|
||||
disabled: false,
|
||||
setAttribute() {},
|
||||
addEventListener() {},
|
||||
};
|
||||
const noopClassList = { toggle() {} };
|
||||
|
||||
const manager = api.createMail2925Manager({
|
||||
state: {
|
||||
getLatestState: () => ({ currentMail2925AccountId: null, mail2925Accounts: [] }),
|
||||
syncLatestState() {},
|
||||
},
|
||||
dom: {
|
||||
btnAddMail2925Account: { disabled: false, addEventListener() {} },
|
||||
btnDeleteAllMail2925Accounts: { textContent: '', disabled: false, addEventListener() {} },
|
||||
btnImportMail2925Accounts: { disabled: false, addEventListener() {} },
|
||||
btnToggleMail2925Form: formToggleButton,
|
||||
btnToggleMail2925List: toggleButton,
|
||||
inputMail2925Email: { value: '' },
|
||||
inputMail2925Import: { value: '' },
|
||||
inputMail2925Password: { value: '' },
|
||||
mail2925AccountsList,
|
||||
mail2925FormShell: { hidden: true },
|
||||
mail2925ListShell: { classList: noopClassList },
|
||||
},
|
||||
helpers: {
|
||||
getMail2925Accounts: () => [],
|
||||
escapeHtml: (value) => String(value || ''),
|
||||
showToast() {},
|
||||
openConfirmModal: async () => true,
|
||||
copyTextToClipboard: async () => {},
|
||||
refreshManagedAliasBaseEmail() {},
|
||||
},
|
||||
runtime: {
|
||||
sendMessage: async () => ({}),
|
||||
},
|
||||
constants: {
|
||||
copyIcon: '',
|
||||
displayTimeZone: 'Asia/Shanghai',
|
||||
expandedStorageKey: 'multipage-mail2925-list-expanded',
|
||||
},
|
||||
mail2925Utils: {},
|
||||
});
|
||||
|
||||
assert.equal(typeof manager.renderMail2925Accounts, 'function');
|
||||
assert.equal(typeof manager.bindMail2925Events, 'function');
|
||||
assert.equal(typeof manager.initMail2925ListExpandedState, 'function');
|
||||
|
||||
manager.renderMail2925Accounts();
|
||||
assert.match(mail2925AccountsList.innerHTML, /还没有 2925 账号/);
|
||||
});
|
||||
|
||||
test('mail2925 manager toggles form container from header button', () => {
|
||||
const source = fs.readFileSync('sidepanel/mail-2925-manager.js', 'utf8');
|
||||
const windowObject = {
|
||||
SidepanelAccountPoolUi: createAccountPoolUiStub(),
|
||||
};
|
||||
const localStorageMock = {
|
||||
getItem() {
|
||||
return null;
|
||||
},
|
||||
setItem() {},
|
||||
};
|
||||
|
||||
const api = new Function('window', 'localStorage', `${source}; return window.SidepanelMail2925Manager;`)(
|
||||
windowObject,
|
||||
localStorageMock
|
||||
);
|
||||
|
||||
const clickHandlers = {};
|
||||
const formToggleButton = {
|
||||
textContent: '',
|
||||
disabled: false,
|
||||
setAttribute(name, value) {
|
||||
this[name] = value;
|
||||
},
|
||||
addEventListener(type, handler) {
|
||||
clickHandlers[type] = handler;
|
||||
},
|
||||
};
|
||||
const formShell = { hidden: true };
|
||||
|
||||
const manager = api.createMail2925Manager({
|
||||
state: {
|
||||
getLatestState: () => ({ currentMail2925AccountId: null, mail2925Accounts: [] }),
|
||||
syncLatestState() {},
|
||||
},
|
||||
dom: {
|
||||
btnAddMail2925Account: { textContent: '', disabled: false, addEventListener() {} },
|
||||
btnDeleteAllMail2925Accounts: { textContent: '', disabled: false, addEventListener() {} },
|
||||
btnImportMail2925Accounts: { disabled: false, addEventListener() {} },
|
||||
btnToggleMail2925Form: formToggleButton,
|
||||
btnToggleMail2925List: { textContent: '', disabled: false, setAttribute() {}, addEventListener() {} },
|
||||
inputMail2925Email: { value: '', focus() { this.focused = true; } },
|
||||
inputMail2925Import: { value: '' },
|
||||
inputMail2925Password: { value: '' },
|
||||
mail2925AccountsList: { innerHTML: '', addEventListener() {} },
|
||||
mail2925FormShell: formShell,
|
||||
mail2925ListShell: { classList: { toggle() {} } },
|
||||
},
|
||||
helpers: {
|
||||
getMail2925Accounts: () => [],
|
||||
escapeHtml: (value) => String(value || ''),
|
||||
showToast() {},
|
||||
openConfirmModal: async () => true,
|
||||
copyTextToClipboard: async () => {},
|
||||
refreshManagedAliasBaseEmail() {},
|
||||
},
|
||||
runtime: {
|
||||
sendMessage: async () => ({}),
|
||||
},
|
||||
constants: {
|
||||
copyIcon: '',
|
||||
displayTimeZone: 'Asia/Shanghai',
|
||||
expandedStorageKey: 'multipage-mail2925-list-expanded',
|
||||
},
|
||||
mail2925Utils: {},
|
||||
});
|
||||
|
||||
manager.bindMail2925Events();
|
||||
assert.equal(formShell.hidden, true);
|
||||
assert.equal(formToggleButton.textContent, '添加账号');
|
||||
|
||||
clickHandlers.click();
|
||||
assert.equal(formShell.hidden, false);
|
||||
assert.equal(formToggleButton.textContent, '取消添加');
|
||||
|
||||
clickHandlers.click();
|
||||
assert.equal(formShell.hidden, true);
|
||||
assert.equal(formToggleButton.textContent, '添加账号');
|
||||
});
|
||||
|
||||
test('mail2925 manager hides form after save succeeds', async () => {
|
||||
const source = fs.readFileSync('sidepanel/mail-2925-manager.js', 'utf8');
|
||||
const windowObject = {
|
||||
SidepanelAccountPoolUi: createAccountPoolUiStub(),
|
||||
};
|
||||
const localStorageMock = {
|
||||
getItem() {
|
||||
return null;
|
||||
},
|
||||
setItem() {},
|
||||
};
|
||||
|
||||
const api = new Function('window', 'localStorage', `${source}; return window.SidepanelMail2925Manager;`)(
|
||||
windowObject,
|
||||
localStorageMock
|
||||
);
|
||||
|
||||
let latestState = { currentMail2925AccountId: null, mail2925Accounts: [] };
|
||||
const handlers = {};
|
||||
const formToggleButton = {
|
||||
textContent: '',
|
||||
disabled: false,
|
||||
setAttribute() {},
|
||||
addEventListener(type, handler) {
|
||||
if (type === 'click') handlers.toggle = handler;
|
||||
},
|
||||
};
|
||||
const addButton = {
|
||||
textContent: '',
|
||||
disabled: false,
|
||||
addEventListener(type, handler) {
|
||||
if (type === 'click') handlers.add = handler;
|
||||
},
|
||||
};
|
||||
const formShell = { hidden: true };
|
||||
const inputMail2925Email = { value: '', focus() {} };
|
||||
const inputMail2925Password = { value: '' };
|
||||
const toastMessages = [];
|
||||
|
||||
const manager = api.createMail2925Manager({
|
||||
state: {
|
||||
getLatestState: () => latestState,
|
||||
syncLatestState(patch) {
|
||||
latestState = { ...latestState, ...patch };
|
||||
},
|
||||
},
|
||||
dom: {
|
||||
btnAddMail2925Account: addButton,
|
||||
btnDeleteAllMail2925Accounts: { textContent: '', disabled: false, addEventListener() {} },
|
||||
btnImportMail2925Accounts: { disabled: false, addEventListener() {} },
|
||||
btnToggleMail2925Form: formToggleButton,
|
||||
btnToggleMail2925List: { textContent: '', disabled: false, setAttribute() {}, addEventListener() {} },
|
||||
inputMail2925Email,
|
||||
inputMail2925Import: { value: '' },
|
||||
inputMail2925Password,
|
||||
mail2925AccountsList: { innerHTML: '', addEventListener() {} },
|
||||
mail2925FormShell: formShell,
|
||||
mail2925ListShell: { classList: { toggle() {} } },
|
||||
},
|
||||
helpers: {
|
||||
getMail2925Accounts: (state) => state.mail2925Accounts || [],
|
||||
escapeHtml: (value) => String(value || ''),
|
||||
showToast(message) {
|
||||
toastMessages.push(message);
|
||||
},
|
||||
openConfirmModal: async () => true,
|
||||
copyTextToClipboard: async () => {},
|
||||
refreshManagedAliasBaseEmail() {},
|
||||
},
|
||||
runtime: {
|
||||
sendMessage: async () => ({
|
||||
account: {
|
||||
id: 'acc-1',
|
||||
email: 'demo@2925.com',
|
||||
password: 'secret',
|
||||
enabled: true,
|
||||
lastLoginAt: 0,
|
||||
lastUsedAt: 0,
|
||||
lastLimitAt: 0,
|
||||
disabledUntil: 0,
|
||||
lastError: '',
|
||||
},
|
||||
}),
|
||||
},
|
||||
constants: {
|
||||
copyIcon: '',
|
||||
displayTimeZone: 'Asia/Shanghai',
|
||||
expandedStorageKey: 'multipage-mail2925-list-expanded',
|
||||
},
|
||||
mail2925Utils: {
|
||||
upsertMail2925AccountInList: (accounts, nextAccount) => accounts.concat(nextAccount),
|
||||
},
|
||||
});
|
||||
|
||||
manager.bindMail2925Events();
|
||||
handlers.toggle();
|
||||
inputMail2925Email.value = 'demo@2925.com';
|
||||
inputMail2925Password.value = 'secret';
|
||||
|
||||
await handlers.add();
|
||||
|
||||
assert.equal(formShell.hidden, true);
|
||||
assert.equal(formToggleButton.textContent, '添加账号');
|
||||
assert.equal(addButton.textContent, '添加账号');
|
||||
assert.equal(inputMail2925Email.value, '');
|
||||
assert.equal(inputMail2925Password.value, '');
|
||||
assert.match(toastMessages.at(-1) || '', /已保存 2925 账号/);
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const source = fs.readFileSync('sidepanel/sidepanel.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('sidepanel html keeps 2925 mode row and standalone pool settings row', () => {
|
||||
const html = fs.readFileSync('sidepanel/sidepanel.html', 'utf8');
|
||||
|
||||
assert.match(html, /id="row-mail-2925-mode"/);
|
||||
assert.match(html, /data-mail2925-mode="provide"/);
|
||||
assert.match(html, /data-mail2925-mode="receive"/);
|
||||
assert.match(html, /id="row-mail2925-pool-settings"/);
|
||||
});
|
||||
|
||||
test('sidepanel only treats 2925 as generated alias provider in provide mode', () => {
|
||||
const bundle = [
|
||||
extractFunction('isManagedAliasProvider'),
|
||||
extractFunction('usesGeneratedAliasMailProvider'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
const GMAIL_PROVIDER = 'gmail';
|
||||
const MAIL_2925_MODE_PROVIDE = 'provide';
|
||||
const MAIL_2925_MODE_RECEIVE = 'receive';
|
||||
const DEFAULT_MAIL_2925_MODE = MAIL_2925_MODE_PROVIDE;
|
||||
const selectMailProvider = { value: '2925' };
|
||||
|
||||
function normalizeMail2925Mode(value = '') {
|
||||
return String(value || '').trim().toLowerCase() === MAIL_2925_MODE_RECEIVE
|
||||
? MAIL_2925_MODE_RECEIVE
|
||||
: DEFAULT_MAIL_2925_MODE;
|
||||
}
|
||||
|
||||
function getSelectedMail2925Mode() {
|
||||
return MAIL_2925_MODE_PROVIDE;
|
||||
}
|
||||
|
||||
function getManagedAliasUtils() {
|
||||
return {
|
||||
usesManagedAliasGeneration(provider, options = {}) {
|
||||
return String(provider || '').trim().toLowerCase() === 'gmail'
|
||||
|| (String(provider || '').trim().toLowerCase() === '2925'
|
||||
&& normalizeMail2925Mode(options.mail2925Mode) === MAIL_2925_MODE_PROVIDE);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
${bundle}
|
||||
|
||||
return {
|
||||
isManagedAliasProvider,
|
||||
usesGeneratedAliasMailProvider,
|
||||
};
|
||||
`)();
|
||||
|
||||
assert.equal(api.isManagedAliasProvider('2925', 'provide'), true);
|
||||
assert.equal(api.isManagedAliasProvider('2925', 'receive'), false);
|
||||
assert.equal(api.usesGeneratedAliasMailProvider('2925', 'provide'), true);
|
||||
assert.equal(api.usesGeneratedAliasMailProvider('2925', 'receive'), false);
|
||||
assert.equal(api.usesGeneratedAliasMailProvider('gmail', 'receive'), true);
|
||||
});
|
||||
@@ -0,0 +1,182 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const source = fs.readFileSync('sidepanel/sidepanel.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('new user guide prompt is only eligible before the one-time dismissal is set', () => {
|
||||
const bundle = [
|
||||
extractFunction('isPromptDismissed'),
|
||||
extractFunction('setPromptDismissed'),
|
||||
extractFunction('isNewUserGuidePromptDismissed'),
|
||||
extractFunction('setNewUserGuidePromptDismissed'),
|
||||
extractFunction('shouldPromptNewUserGuide'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
const NEW_USER_GUIDE_PROMPT_DISMISSED_STORAGE_KEY = 'multipage-new-user-guide-prompt-dismissed';
|
||||
const storage = new Map();
|
||||
const localStorage = {
|
||||
getItem(key) {
|
||||
return storage.has(key) ? storage.get(key) : null;
|
||||
},
|
||||
setItem(key, value) {
|
||||
storage.set(key, String(value));
|
||||
},
|
||||
removeItem(key) {
|
||||
storage.delete(key);
|
||||
},
|
||||
};
|
||||
const btnContributionMode = { disabled: false };
|
||||
let latestState = { contributionMode: false };
|
||||
${bundle}
|
||||
return {
|
||||
shouldPromptNewUserGuide,
|
||||
setDismissed(value) {
|
||||
setNewUserGuidePromptDismissed(value);
|
||||
},
|
||||
setButtonDisabled(value) {
|
||||
btnContributionMode.disabled = Boolean(value);
|
||||
},
|
||||
setContributionMode(value) {
|
||||
latestState = { contributionMode: Boolean(value) };
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
assert.equal(api.shouldPromptNewUserGuide(), true);
|
||||
|
||||
api.setDismissed(true);
|
||||
assert.equal(api.shouldPromptNewUserGuide(), false);
|
||||
|
||||
api.setDismissed(false);
|
||||
api.setButtonDisabled(true);
|
||||
assert.equal(api.shouldPromptNewUserGuide(), false);
|
||||
|
||||
api.setButtonDisabled(false);
|
||||
api.setContributionMode(true);
|
||||
assert.equal(api.shouldPromptNewUserGuide(), false);
|
||||
});
|
||||
|
||||
test('new user guide prompt persists dismissal before awaiting the user choice and opens the contribution page on confirm', async () => {
|
||||
const bundle = [
|
||||
extractFunction('isPromptDismissed'),
|
||||
extractFunction('setPromptDismissed'),
|
||||
extractFunction('isNewUserGuidePromptDismissed'),
|
||||
extractFunction('setNewUserGuidePromptDismissed'),
|
||||
extractFunction('shouldPromptNewUserGuide'),
|
||||
extractFunction('getContributionPortalUrl'),
|
||||
extractFunction('openNewUserGuidePrompt'),
|
||||
extractFunction('maybeShowNewUserGuidePrompt'),
|
||||
].join('\n');
|
||||
|
||||
const api = new Function(`
|
||||
const NEW_USER_GUIDE_PROMPT_DISMISSED_STORAGE_KEY = 'multipage-new-user-guide-prompt-dismissed';
|
||||
const storage = new Map();
|
||||
const localStorage = {
|
||||
getItem(key) {
|
||||
return storage.has(key) ? storage.get(key) : null;
|
||||
},
|
||||
setItem(key, value) {
|
||||
storage.set(key, String(value));
|
||||
},
|
||||
removeItem(key) {
|
||||
storage.delete(key);
|
||||
},
|
||||
};
|
||||
const btnContributionMode = { disabled: false };
|
||||
const latestState = { contributionMode: false };
|
||||
const contributionContentService = { portalUrl: 'https://apikey.qzz.io' };
|
||||
const openedUrls = [];
|
||||
let modalOptions = null;
|
||||
let nextChoice = 'confirm';
|
||||
function openExternalUrl(url) {
|
||||
openedUrls.push(url);
|
||||
}
|
||||
function openActionModal(options) {
|
||||
modalOptions = options;
|
||||
return Promise.resolve(nextChoice);
|
||||
}
|
||||
${bundle}
|
||||
return {
|
||||
maybeShowNewUserGuidePrompt,
|
||||
getDismissed() {
|
||||
return localStorage.getItem(NEW_USER_GUIDE_PROMPT_DISMISSED_STORAGE_KEY);
|
||||
},
|
||||
getOpenedUrls() {
|
||||
return openedUrls.slice();
|
||||
},
|
||||
getModalOptions() {
|
||||
return modalOptions;
|
||||
},
|
||||
setNextChoice(choice) {
|
||||
nextChoice = choice;
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
const confirmed = await api.maybeShowNewUserGuidePrompt();
|
||||
const modalOptions = api.getModalOptions();
|
||||
|
||||
assert.equal(confirmed, true);
|
||||
assert.equal(api.getDismissed(), '1');
|
||||
assert.deepStrictEqual(api.getOpenedUrls(), ['https://apikey.qzz.io']);
|
||||
assert.equal(modalOptions.title, '新手引导');
|
||||
assert.equal(modalOptions.alert.text, '本提示仅出现一次。');
|
||||
assert.deepStrictEqual(
|
||||
modalOptions.actions.map((item) => ({ id: item.id, label: item.label })),
|
||||
[
|
||||
{ id: null, label: '取消' },
|
||||
{ id: 'confirm', label: '查看引导' },
|
||||
]
|
||||
);
|
||||
|
||||
api.setNextChoice(null);
|
||||
const skipped = await api.maybeShowNewUserGuidePrompt();
|
||||
assert.equal(skipped, false);
|
||||
assert.deepStrictEqual(api.getOpenedUrls(), ['https://apikey.qzz.io']);
|
||||
});
|
||||
@@ -144,3 +144,317 @@ return {
|
||||
]);
|
||||
assert.match(result.bodyTextPreview, /Welcome to ChatGPT/);
|
||||
});
|
||||
|
||||
test('signup entry diagnostics captures hidden signup button style and blocking ancestor details', () => {
|
||||
const api = new Function(`
|
||||
const SIGNUP_ENTRY_TRIGGER_PATTERN = /免费注册|立即注册|注册|sign\\s*up|register|create\\s*account|create\\s+account/i;
|
||||
const location = { href: 'https://chatgpt.com/' };
|
||||
const hiddenSection = {
|
||||
tagName: 'DIV',
|
||||
id: 'mobile-cta',
|
||||
className: 'max-xs:hidden',
|
||||
hidden: false,
|
||||
parentElement: null,
|
||||
hasAttribute() {
|
||||
return false;
|
||||
},
|
||||
getAttribute(name) {
|
||||
if (name === 'aria-hidden') return '';
|
||||
return '';
|
||||
},
|
||||
getBoundingClientRect() {
|
||||
return { width: 0, height: 0 };
|
||||
},
|
||||
_style: {
|
||||
display: 'none',
|
||||
visibility: 'visible',
|
||||
opacity: '1',
|
||||
pointerEvents: 'auto',
|
||||
},
|
||||
};
|
||||
const hiddenSignupButton = {
|
||||
tagName: 'BUTTON',
|
||||
textContent: 'Sign up for free',
|
||||
disabled: false,
|
||||
className: 'signup-button',
|
||||
hidden: false,
|
||||
parentElement: hiddenSection,
|
||||
hasAttribute() {
|
||||
return false;
|
||||
},
|
||||
getBoundingClientRect() {
|
||||
return { width: 0, height: 0 };
|
||||
},
|
||||
getAttribute(name) {
|
||||
if (name === 'type') return '';
|
||||
if (name === 'aria-hidden') return '';
|
||||
return '';
|
||||
},
|
||||
_style: {
|
||||
display: 'block',
|
||||
visibility: 'visible',
|
||||
opacity: '1',
|
||||
pointerEvents: 'auto',
|
||||
},
|
||||
};
|
||||
const document = {
|
||||
title: 'ChatGPT',
|
||||
readyState: 'complete',
|
||||
querySelector() {
|
||||
return null;
|
||||
},
|
||||
querySelectorAll(selector) {
|
||||
if (selector === 'a, button, [role="button"], [role="link"], input[type="button"], input[type="submit"]') {
|
||||
return [hiddenSignupButton];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
};
|
||||
const window = {
|
||||
innerWidth: 390,
|
||||
innerHeight: 844,
|
||||
outerWidth: 390,
|
||||
outerHeight: 844,
|
||||
devicePixelRatio: 3,
|
||||
getComputedStyle(el) {
|
||||
return el?._style || {
|
||||
display: 'block',
|
||||
visibility: 'visible',
|
||||
opacity: '1',
|
||||
pointerEvents: 'auto',
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
function isVisibleElement(el) {
|
||||
const style = window.getComputedStyle(el);
|
||||
const rect = el.getBoundingClientRect();
|
||||
return style.display !== 'none'
|
||||
&& style.visibility !== 'hidden'
|
||||
&& rect.width > 0
|
||||
&& rect.height > 0;
|
||||
}
|
||||
|
||||
function getActionText(el) {
|
||||
return [el?.textContent, el?.value, el?.getAttribute?.('aria-label'), el?.getAttribute?.('title')]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.replace(/\\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function isActionEnabled(el) {
|
||||
return Boolean(el) && !el.disabled && el.getAttribute('aria-disabled') !== 'true';
|
||||
}
|
||||
|
||||
function getSignupEmailInput() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function getSignupPasswordInput() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function getPageTextSnapshot() {
|
||||
return 'ChatGPT 登录';
|
||||
}
|
||||
|
||||
${extractFunction('getSignupEntryDiagnostics')}
|
||||
|
||||
return {
|
||||
run() {
|
||||
return getSignupEntryDiagnostics();
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
const result = api.run();
|
||||
|
||||
assert.deepStrictEqual(result.viewport, {
|
||||
innerWidth: 390,
|
||||
innerHeight: 844,
|
||||
outerWidth: 390,
|
||||
outerHeight: 844,
|
||||
devicePixelRatio: 3,
|
||||
});
|
||||
assert.deepStrictEqual(result.signupLikeActionCounts, {
|
||||
total: 1,
|
||||
visible: 0,
|
||||
hidden: 1,
|
||||
});
|
||||
assert.equal(result.signupLikeActions[0]?.text, 'Sign up for free');
|
||||
assert.equal(result.signupLikeActions[0]?.className, 'signup-button');
|
||||
assert.equal(result.signupLikeActions[0]?.display, 'block');
|
||||
assert.equal(result.signupLikeActions[0]?.blockingAncestor?.className, 'max-xs:hidden');
|
||||
assert.equal(result.signupLikeActions[0]?.blockingAncestor?.display, 'none');
|
||||
});
|
||||
|
||||
test('signup password diagnostics summarizes password inputs, submit button, and alternate code entry', () => {
|
||||
const api = new Function(`
|
||||
const location = { href: 'https://auth.openai.com/create-account/password' };
|
||||
const form = { action: 'https://auth.openai.com/u/signup/password' };
|
||||
const passwordInput = {
|
||||
tagName: 'INPUT',
|
||||
type: 'password',
|
||||
name: 'new-password',
|
||||
id: 'password-field',
|
||||
value: 'SecretLength14',
|
||||
className: 'password-input',
|
||||
disabled: false,
|
||||
form,
|
||||
getBoundingClientRect() {
|
||||
return { width: 320, height: 44 };
|
||||
},
|
||||
getAttribute(name) {
|
||||
if (name === 'type') return 'password';
|
||||
if (name === 'name') return 'new-password';
|
||||
if (name === 'autocomplete') return 'new-password';
|
||||
if (name === 'placeholder') return 'Password';
|
||||
if (name === 'aria-disabled') return 'false';
|
||||
return '';
|
||||
},
|
||||
_style: {
|
||||
display: 'block',
|
||||
visibility: 'visible',
|
||||
opacity: '1',
|
||||
pointerEvents: 'auto',
|
||||
},
|
||||
};
|
||||
const submitButton = {
|
||||
tagName: 'BUTTON',
|
||||
textContent: 'Continue',
|
||||
className: 'submit-btn',
|
||||
disabled: false,
|
||||
form,
|
||||
getBoundingClientRect() {
|
||||
return { width: 160, height: 40 };
|
||||
},
|
||||
getAttribute(name) {
|
||||
if (name === 'type') return 'submit';
|
||||
if (name === 'aria-disabled') return 'false';
|
||||
if (name === 'data-dd-action-name') return 'Continue';
|
||||
return '';
|
||||
},
|
||||
_style: {
|
||||
display: 'block',
|
||||
visibility: 'visible',
|
||||
opacity: '1',
|
||||
pointerEvents: 'auto',
|
||||
},
|
||||
};
|
||||
const oneTimeCodeButton = {
|
||||
tagName: 'BUTTON',
|
||||
textContent: 'Use a one-time code instead',
|
||||
className: 'switch-btn',
|
||||
disabled: false,
|
||||
getBoundingClientRect() {
|
||||
return { width: 220, height: 36 };
|
||||
},
|
||||
getAttribute(name) {
|
||||
if (name === 'type') return 'button';
|
||||
if (name === 'aria-disabled') return 'false';
|
||||
return '';
|
||||
},
|
||||
_style: {
|
||||
display: 'block',
|
||||
visibility: 'visible',
|
||||
opacity: '1',
|
||||
pointerEvents: 'auto',
|
||||
},
|
||||
};
|
||||
const document = {
|
||||
title: 'Create your account',
|
||||
readyState: 'complete',
|
||||
querySelectorAll(selector) {
|
||||
if (selector === 'input[type="password"], input[name*="password" i], input[autocomplete="new-password"], input[autocomplete="current-password"]') {
|
||||
return [passwordInput];
|
||||
}
|
||||
if (selector === 'button, a, [role="button"], [role="link"], input[type="button"], input[type="submit"]') {
|
||||
return [submitButton, oneTimeCodeButton];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
};
|
||||
const window = {
|
||||
getComputedStyle(el) {
|
||||
return el?._style || {
|
||||
display: 'block',
|
||||
visibility: 'visible',
|
||||
opacity: '1',
|
||||
pointerEvents: 'auto',
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
function isVisibleElement(el) {
|
||||
const style = window.getComputedStyle(el);
|
||||
const rect = el.getBoundingClientRect();
|
||||
return style.display !== 'none'
|
||||
&& style.visibility !== 'hidden'
|
||||
&& rect.width > 0
|
||||
&& rect.height > 0;
|
||||
}
|
||||
|
||||
function isActionEnabled(el) {
|
||||
return Boolean(el) && !el.disabled && el.getAttribute('aria-disabled') !== 'true';
|
||||
}
|
||||
|
||||
function getActionText(el) {
|
||||
return [el?.textContent, el?.value, el?.getAttribute?.('aria-label'), el?.getAttribute?.('title')]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.replace(/\\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function getPageTextSnapshot() {
|
||||
return 'Create your account Use a one-time code instead';
|
||||
}
|
||||
|
||||
function getSignupPasswordInput() {
|
||||
return passwordInput;
|
||||
}
|
||||
|
||||
function getSignupPasswordSubmitButton() {
|
||||
return submitButton;
|
||||
}
|
||||
|
||||
function getSignupPasswordDisplayedEmail() {
|
||||
return 'user@example.com';
|
||||
}
|
||||
|
||||
function findOneTimeCodeLoginTrigger() {
|
||||
return oneTimeCodeButton;
|
||||
}
|
||||
|
||||
function getSignupPasswordTimeoutErrorPageState() {
|
||||
return {
|
||||
retryEnabled: true,
|
||||
userAlreadyExistsBlocked: false,
|
||||
};
|
||||
}
|
||||
|
||||
${extractFunction('getSignupPasswordDiagnostics')}
|
||||
|
||||
return {
|
||||
run() {
|
||||
return getSignupPasswordDiagnostics();
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
const result = api.run();
|
||||
|
||||
assert.equal(result.url, 'https://auth.openai.com/create-account/password');
|
||||
assert.equal(result.displayedEmail, 'user@example.com');
|
||||
assert.equal(result.hasVisiblePasswordInput, true);
|
||||
assert.equal(result.passwordInputCount, 1);
|
||||
assert.equal(result.visiblePasswordInputCount, 1);
|
||||
assert.equal(result.passwordInputs[0]?.name, 'new-password');
|
||||
assert.equal(result.passwordInputs[0]?.valueLength, 14);
|
||||
assert.equal(result.submitButton?.text, 'Continue');
|
||||
assert.equal(result.oneTimeCodeTrigger?.text, 'Use a one-time code instead');
|
||||
assert.equal(result.retryPage, true);
|
||||
assert.equal(result.retryEnabled, true);
|
||||
assert.match(result.bodyTextPreview, /one-time code/);
|
||||
});
|
||||
|
||||
@@ -138,5 +138,57 @@ return {
|
||||
assert.deepStrictEqual(api.run(), {
|
||||
state: 'error',
|
||||
retryButton: { textContent: 'Try again' },
|
||||
userAlreadyExistsBlocked: false,
|
||||
});
|
||||
});
|
||||
|
||||
test('signup verification state treats email-verification retry page as error instead of verification', () => {
|
||||
const api = new Function(`
|
||||
const location = {
|
||||
pathname: '/email-verification',
|
||||
};
|
||||
|
||||
function getAuthTimeoutErrorPageState(options) {
|
||||
return options.pathPatterns.some((pattern) => pattern.test(location.pathname))
|
||||
? { retryButton: { textContent: 'Try again' } }
|
||||
: null;
|
||||
}
|
||||
|
||||
function isStep5Ready() {
|
||||
return false;
|
||||
}
|
||||
|
||||
function isVerificationPageStillVisible() {
|
||||
return true;
|
||||
}
|
||||
|
||||
function isSignupEmailAlreadyExistsPage() {
|
||||
return false;
|
||||
}
|
||||
|
||||
function getSignupPasswordInput() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function getSignupPasswordSubmitButton() {
|
||||
return null;
|
||||
}
|
||||
|
||||
${extractFunction('getSignupAuthRetryPathPatterns')}
|
||||
${extractFunction('getSignupPasswordTimeoutErrorPageState')}
|
||||
${extractFunction('isSignupPasswordErrorPage')}
|
||||
${extractFunction('inspectSignupVerificationState')}
|
||||
|
||||
return {
|
||||
run() {
|
||||
return inspectSignupVerificationState();
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
assert.deepStrictEqual(api.run(), {
|
||||
state: 'error',
|
||||
retryButton: { textContent: 'Try again' },
|
||||
userAlreadyExistsBlocked: false,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const source = fs.readFileSync('content/signup-page.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('fillVerificationCode submits after split inputs are stably filled', async () => {
|
||||
const api = new Function(`
|
||||
const logs = [];
|
||||
const clicks = [];
|
||||
const filledValues = [];
|
||||
let submitClicked = false;
|
||||
const VERIFICATION_CODE_INPUT_SELECTOR = 'input[data-verification-code]';
|
||||
const location = { href: 'https://auth.openai.com/email-verification' };
|
||||
function KeyboardEvent(type, init = {}) {
|
||||
this.type = type;
|
||||
Object.assign(this, init);
|
||||
}
|
||||
|
||||
const submitBtn = {
|
||||
tagName: 'BUTTON',
|
||||
textContent: 'Continue',
|
||||
disabled: false,
|
||||
getAttribute(name) {
|
||||
if (name === 'type') return 'submit';
|
||||
if (name === 'aria-disabled') return 'false';
|
||||
return '';
|
||||
},
|
||||
click() {
|
||||
submitClicked = true;
|
||||
},
|
||||
};
|
||||
|
||||
const inputs = Array.from({ length: 6 }, () => ({
|
||||
value: '',
|
||||
maxLength: 1,
|
||||
getAttribute(name) {
|
||||
if (name === 'maxlength') return '1';
|
||||
if (name === 'aria-disabled') return 'false';
|
||||
return '';
|
||||
},
|
||||
focus() {},
|
||||
dispatchEvent() {},
|
||||
closest() { return null; },
|
||||
}));
|
||||
|
||||
const document = {
|
||||
querySelector(selector) {
|
||||
if (selector === VERIFICATION_CODE_INPUT_SELECTOR) return inputs[0];
|
||||
return null;
|
||||
},
|
||||
querySelectorAll(selector) {
|
||||
if (selector === 'input[maxlength="1"]') return inputs;
|
||||
if (selector === 'button[type="submit"], input[type="submit"]') return [submitBtn];
|
||||
if (selector === 'button, [role="button"], input[type="button"], input[type="submit"]') return [submitBtn];
|
||||
return [];
|
||||
},
|
||||
};
|
||||
|
||||
function throwIfStopped() {}
|
||||
function log(message, level = 'info') { logs.push({ message, level }); }
|
||||
async function waitForLoginVerificationPageReady() {}
|
||||
function is405MethodNotAllowedPage() { return false; }
|
||||
async function handle405ResendError() {}
|
||||
function fillInput(el, value) {
|
||||
el.value = value;
|
||||
filledValues.push(value);
|
||||
}
|
||||
async function sleep() {}
|
||||
function isVisibleElement() { return true; }
|
||||
function isActionEnabled(el) { return Boolean(el) && !el.disabled; }
|
||||
function getActionText(el) { return el.textContent || ''; }
|
||||
async function humanPause() {}
|
||||
function simulateClick(el) { el.click(); clicks.push(el.textContent); }
|
||||
async function waitForVerificationSubmitOutcome() { return { success: true }; }
|
||||
|
||||
${extractFunction('getVisibleSplitVerificationInputs')}
|
||||
${extractFunction('getVerificationCodeTarget')}
|
||||
${extractFunction('getVerificationSubmitButtonForTarget')}
|
||||
${extractFunction('waitForVerificationSubmitButton')}
|
||||
${extractFunction('waitForVerificationCodeTarget')}
|
||||
${extractFunction('waitForSplitVerificationInputsFilled')}
|
||||
${extractFunction('fillVerificationCode')}
|
||||
|
||||
return {
|
||||
run() {
|
||||
return fillVerificationCode(4, { code: '123456' });
|
||||
},
|
||||
snapshot() {
|
||||
return {
|
||||
logs,
|
||||
clicks,
|
||||
filledValues,
|
||||
submitClicked,
|
||||
currentValue: inputs.map((input) => input.value).join(''),
|
||||
};
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
const result = await api.run();
|
||||
const snapshot = api.snapshot();
|
||||
|
||||
assert.deepStrictEqual(result, { success: true });
|
||||
assert.equal(snapshot.currentValue, '123456');
|
||||
assert.equal(snapshot.submitClicked, true);
|
||||
assert.deepStrictEqual(snapshot.clicks, ['Continue']);
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const source = fs.readFileSync('content/signup-page.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('waitForVerificationSubmitOutcome recovers signup retry page after submit', async () => {
|
||||
const api = new Function(`
|
||||
let retryVisible = true;
|
||||
let step5Ready = false;
|
||||
let recoverCalls = 0;
|
||||
const location = { href: 'https://auth.openai.com/email-verification' };
|
||||
|
||||
function throwIfStopped() {}
|
||||
function log() {}
|
||||
function getVerificationErrorText() { return ''; }
|
||||
function isStep5Ready() { return step5Ready; }
|
||||
function isStep8Ready() { return false; }
|
||||
function isAddPhonePageReady() { return false; }
|
||||
function isVerificationPageStillVisible() { return false; }
|
||||
function createSignupUserAlreadyExistsError() {
|
||||
return new Error('SIGNUP_USER_ALREADY_EXISTS::步骤 4:检测到 user_already_exists,说明当前用户已存在,当前轮将直接停止。');
|
||||
}
|
||||
function getCurrentAuthRetryPageState(flow) {
|
||||
if (flow === 'signup' && retryVisible) {
|
||||
return {
|
||||
retryEnabled: true,
|
||||
userAlreadyExistsBlocked: false,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
async function recoverCurrentAuthRetryPage() {
|
||||
recoverCalls += 1;
|
||||
retryVisible = false;
|
||||
step5Ready = true;
|
||||
}
|
||||
async function sleep() {}
|
||||
|
||||
${extractFunction('waitForVerificationSubmitOutcome')}
|
||||
|
||||
return {
|
||||
run() {
|
||||
return waitForVerificationSubmitOutcome(4, 1000);
|
||||
},
|
||||
snapshot() {
|
||||
return { recoverCalls };
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
const result = await api.run();
|
||||
|
||||
assert.deepStrictEqual(result, { success: true });
|
||||
assert.equal(api.snapshot().recoverCalls, 1);
|
||||
});
|
||||
|
||||
test('waitForVerificationSubmitOutcome does not assume success after repeated signup retry pages', async () => {
|
||||
const api = new Function(`
|
||||
let recoverCalls = 0;
|
||||
const location = { href: 'https://auth.openai.com/email-verification' };
|
||||
|
||||
function throwIfStopped() {}
|
||||
function log() {}
|
||||
function getVerificationErrorText() { return ''; }
|
||||
function isStep5Ready() { return false; }
|
||||
function isStep8Ready() { return false; }
|
||||
function isAddPhonePageReady() { return false; }
|
||||
function isVerificationPageStillVisible() { return false; }
|
||||
function createSignupUserAlreadyExistsError() {
|
||||
return new Error('SIGNUP_USER_ALREADY_EXISTS::步骤 4:检测到 user_already_exists,说明当前用户已存在,当前轮将直接停止。');
|
||||
}
|
||||
function getCurrentAuthRetryPageState(flow) {
|
||||
if (flow === 'signup') {
|
||||
return {
|
||||
retryEnabled: true,
|
||||
userAlreadyExistsBlocked: false,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
async function recoverCurrentAuthRetryPage() {
|
||||
recoverCalls += 1;
|
||||
}
|
||||
async function sleep() {}
|
||||
|
||||
${extractFunction('waitForVerificationSubmitOutcome')}
|
||||
|
||||
return {
|
||||
run() {
|
||||
return waitForVerificationSubmitOutcome(4, 1000);
|
||||
},
|
||||
snapshot() {
|
||||
return { recoverCalls };
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
await assert.rejects(
|
||||
api.run(),
|
||||
/连续进入认证重试页 2 次,页面仍未恢复/
|
||||
);
|
||||
assert.equal(api.snapshot().recoverCalls, 2);
|
||||
});
|
||||
@@ -146,6 +146,27 @@ return {
|
||||
assert.strictEqual(snapshot.displayedEmail, 'display.user@example.com');
|
||||
}
|
||||
|
||||
{
|
||||
const api = createApi({
|
||||
pathname: '/email-verification',
|
||||
retryState: {
|
||||
retryEnabled: true,
|
||||
titleMatched: false,
|
||||
detailMatched: false,
|
||||
routeErrorMatched: true,
|
||||
},
|
||||
verificationTarget: { id: 'otp' },
|
||||
verificationVisible: true,
|
||||
});
|
||||
|
||||
const snapshot = api.inspectLoginAuthState();
|
||||
assert.strictEqual(
|
||||
snapshot.state,
|
||||
'login_timeout_error_page',
|
||||
'第七步在 /email-verification 的登录重试页应优先识别为登录超时报错页'
|
||||
);
|
||||
}
|
||||
|
||||
{
|
||||
const api = createApi({
|
||||
oauthConsentPage: true,
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const source = fs.readFileSync('content/signup-page.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);
|
||||
}
|
||||
|
||||
const bundle = extractFunction('step6LoginFromPasswordPage');
|
||||
|
||||
function createApi() {
|
||||
return new Function(`
|
||||
${bundle}
|
||||
return { step6LoginFromPasswordPage };
|
||||
`)();
|
||||
}
|
||||
|
||||
function cleanupGlobals() {
|
||||
delete globalThis.normalizeStep6Snapshot;
|
||||
delete globalThis.inspectLoginAuthState;
|
||||
delete globalThis.log;
|
||||
delete globalThis.step6SwitchToOneTimeCodeLogin;
|
||||
delete globalThis.createStep6RecoverableResult;
|
||||
delete globalThis.fillInput;
|
||||
delete globalThis.humanPause;
|
||||
delete globalThis.sleep;
|
||||
delete globalThis.triggerLoginSubmitAction;
|
||||
delete globalThis.waitForStep6PasswordSubmitTransition;
|
||||
}
|
||||
|
||||
test('step6LoginFromPasswordPage switches to one-time-code login when password is missing but switch trigger exists', async () => {
|
||||
const api = createApi();
|
||||
const logs = [];
|
||||
const snapshot = {
|
||||
state: 'password_page',
|
||||
passwordInput: { id: 'password' },
|
||||
switchTrigger: { id: 'otp' },
|
||||
};
|
||||
|
||||
globalThis.normalizeStep6Snapshot = (value) => value;
|
||||
globalThis.inspectLoginAuthState = () => snapshot;
|
||||
globalThis.log = (message, level = 'info') => {
|
||||
logs.push({ message, level });
|
||||
};
|
||||
globalThis.step6SwitchToOneTimeCodeLogin = async (payload, value) => {
|
||||
assert.deepStrictEqual(payload, { email: 'user@example.com', password: '' });
|
||||
assert.strictEqual(value, snapshot);
|
||||
return { step6Outcome: 'success', via: 'switch_to_one_time_code_login' };
|
||||
};
|
||||
globalThis.createStep6RecoverableResult = () => {
|
||||
throw new Error('should not create recoverable result when switch trigger exists');
|
||||
};
|
||||
globalThis.fillInput = () => {
|
||||
throw new Error('should not fill password when password is missing');
|
||||
};
|
||||
globalThis.humanPause = async () => {};
|
||||
globalThis.sleep = async () => {};
|
||||
globalThis.triggerLoginSubmitAction = async () => {};
|
||||
globalThis.waitForStep6PasswordSubmitTransition = async () => {
|
||||
throw new Error('should not submit password when password is missing');
|
||||
};
|
||||
|
||||
try {
|
||||
const result = await api.step6LoginFromPasswordPage({ email: 'user@example.com', password: '' }, snapshot);
|
||||
|
||||
assert.deepStrictEqual(result, { step6Outcome: 'success', via: 'switch_to_one_time_code_login' });
|
||||
assert.deepStrictEqual(logs, [
|
||||
{ message: '步骤 7:当前未提供密码,改走一次性验证码登录。', level: 'warn' },
|
||||
]);
|
||||
} finally {
|
||||
cleanupGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
test('step6LoginFromPasswordPage returns a recoverable result when password is missing and no one-time-code trigger exists', async () => {
|
||||
const api = createApi();
|
||||
const snapshot = {
|
||||
state: 'password_page',
|
||||
passwordInput: { id: 'password' },
|
||||
switchTrigger: null,
|
||||
};
|
||||
|
||||
globalThis.normalizeStep6Snapshot = (value) => value;
|
||||
globalThis.inspectLoginAuthState = () => snapshot;
|
||||
globalThis.log = () => {};
|
||||
globalThis.step6SwitchToOneTimeCodeLogin = async () => {
|
||||
throw new Error('should not switch without a one-time-code trigger');
|
||||
};
|
||||
globalThis.createStep6RecoverableResult = (reason, stateSnapshot, details) => ({
|
||||
step6Outcome: 'recoverable',
|
||||
reason,
|
||||
stateSnapshot,
|
||||
...details,
|
||||
});
|
||||
globalThis.fillInput = () => {
|
||||
throw new Error('should not fill password when password is missing');
|
||||
};
|
||||
globalThis.humanPause = async () => {};
|
||||
globalThis.sleep = async () => {};
|
||||
globalThis.triggerLoginSubmitAction = async () => {};
|
||||
globalThis.waitForStep6PasswordSubmitTransition = async () => {
|
||||
throw new Error('should not submit password when password is missing');
|
||||
};
|
||||
|
||||
try {
|
||||
const result = await api.step6LoginFromPasswordPage({ email: 'user@example.com', password: '' }, snapshot);
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
step6Outcome: 'recoverable',
|
||||
reason: 'missing_password_and_one_time_code_trigger',
|
||||
stateSnapshot: snapshot,
|
||||
message: '登录时未提供密码,且当前页面没有可用的一次性验证码登录入口。',
|
||||
});
|
||||
} finally {
|
||||
cleanupGlobals();
|
||||
}
|
||||
});
|
||||
@@ -72,12 +72,18 @@ async function recoverCurrentAuthRetryPage() {
|
||||
return { recovered: true };
|
||||
}
|
||||
|
||||
function throwIfStopped() {}
|
||||
async function sleep() {}
|
||||
|
||||
function log(message, level = 'info') {
|
||||
logs.push({ message, level });
|
||||
}
|
||||
|
||||
${extractFunction('createStep6SuccessResult')}
|
||||
${extractFunction('createStep6RecoverableResult')}
|
||||
${extractFunction('normalizeStep6Snapshot')}
|
||||
${extractFunction('waitForKnownLoginAuthState')}
|
||||
${extractFunction('createStep6LoginTimeoutRecoveryTransition')}
|
||||
${extractFunction('createStep6LoginTimeoutRecoverableResult')}
|
||||
|
||||
return {
|
||||
@@ -103,3 +109,248 @@ return {
|
||||
assert.equal(result.state, 'login_timeout_error_page');
|
||||
assert.equal(result.message, '当前页面处于登录超时报错页。');
|
||||
});
|
||||
|
||||
test('step 7 timeout recovery transition continues from password page after retry succeeds', async () => {
|
||||
const api = new Function(`
|
||||
const logs = [];
|
||||
let recoverCalls = 0;
|
||||
let currentState = 'login_timeout_error_page';
|
||||
|
||||
const location = {
|
||||
href: 'https://auth.openai.com/log-in',
|
||||
};
|
||||
|
||||
function inspectLoginAuthState() {
|
||||
return {
|
||||
state: currentState,
|
||||
url: location.href,
|
||||
};
|
||||
}
|
||||
|
||||
async function recoverCurrentAuthRetryPage() {
|
||||
recoverCalls += 1;
|
||||
currentState = 'password_page';
|
||||
return { recovered: true };
|
||||
}
|
||||
|
||||
function throwIfStopped() {}
|
||||
async function sleep() {}
|
||||
|
||||
function log(message, level = 'info') {
|
||||
logs.push({ message, level });
|
||||
}
|
||||
|
||||
${extractFunction('createStep6SuccessResult')}
|
||||
${extractFunction('createStep6RecoverableResult')}
|
||||
${extractFunction('normalizeStep6Snapshot')}
|
||||
${extractFunction('waitForKnownLoginAuthState')}
|
||||
${extractFunction('createStep6LoginTimeoutRecoveryTransition')}
|
||||
|
||||
return {
|
||||
async run() {
|
||||
return createStep6LoginTimeoutRecoveryTransition(
|
||||
'login_timeout_error_page',
|
||||
{ state: 'login_timeout_error_page', url: location.href },
|
||||
'当前页面处于登录超时报错页。',
|
||||
{
|
||||
via: 'login_timeout_initial_recovered',
|
||||
}
|
||||
);
|
||||
},
|
||||
snapshot() {
|
||||
return { logs, recoverCalls };
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
const result = await api.run();
|
||||
const snapshot = api.snapshot();
|
||||
|
||||
assert.equal(snapshot.recoverCalls, 1);
|
||||
assert.equal(result.action, 'password');
|
||||
assert.equal(result.snapshot.state, 'password_page');
|
||||
assert.equal(snapshot.logs.some(({ message }) => /密码页/.test(message)), true);
|
||||
});
|
||||
|
||||
test('step 7 entry resumes password flow after retry page recovery reaches password page', async () => {
|
||||
const api = new Function(`
|
||||
const logs = [];
|
||||
let recoverCalls = 0;
|
||||
let currentState = 'login_timeout_error_page';
|
||||
|
||||
const location = {
|
||||
href: 'https://auth.openai.com/log-in',
|
||||
};
|
||||
|
||||
function inspectLoginAuthState() {
|
||||
return {
|
||||
state: currentState,
|
||||
url: location.href,
|
||||
};
|
||||
}
|
||||
|
||||
async function recoverCurrentAuthRetryPage() {
|
||||
recoverCalls += 1;
|
||||
currentState = 'password_page';
|
||||
return { recovered: true };
|
||||
}
|
||||
|
||||
function throwIfStopped() {}
|
||||
async function sleep() {}
|
||||
|
||||
function log(message, level = 'info') {
|
||||
logs.push({ message, level });
|
||||
}
|
||||
|
||||
async function step6LoginFromPasswordPage(payload, snapshot) {
|
||||
return { branch: 'password', payload, snapshot };
|
||||
}
|
||||
|
||||
async function step6LoginFromEmailPage(payload, snapshot) {
|
||||
return { branch: 'email', payload, snapshot };
|
||||
}
|
||||
|
||||
async function finalizeStep6VerificationReady(options) {
|
||||
return { branch: 'verification', options };
|
||||
}
|
||||
|
||||
function throwForStep6FatalState() {}
|
||||
|
||||
${extractFunction('createStep6SuccessResult')}
|
||||
${extractFunction('createStep6RecoverableResult')}
|
||||
${extractFunction('normalizeStep6Snapshot')}
|
||||
${extractFunction('waitForKnownLoginAuthState')}
|
||||
${extractFunction('createStep6LoginTimeoutRecoveryTransition')}
|
||||
${extractFunction('step6_login')}
|
||||
|
||||
return {
|
||||
async run() {
|
||||
return step6_login({
|
||||
email: 'user@example.com',
|
||||
password: 'secret',
|
||||
});
|
||||
},
|
||||
snapshot() {
|
||||
return { logs, recoverCalls };
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
const result = await api.run();
|
||||
const snapshot = api.snapshot();
|
||||
|
||||
assert.equal(snapshot.recoverCalls, 1);
|
||||
assert.equal(result.branch, 'password');
|
||||
assert.equal(result.snapshot.state, 'password_page');
|
||||
assert.equal(snapshot.logs.some(({ message }) => /密码页/.test(message)), true);
|
||||
});
|
||||
|
||||
test('step 7 finalize converts verification page that falls into retry page into recoverable result', async () => {
|
||||
const api = new Function(`
|
||||
const logs = [];
|
||||
let recoverCalls = 0;
|
||||
let currentState = 'verification_page';
|
||||
|
||||
const location = {
|
||||
href: 'https://auth.openai.com/email-verification',
|
||||
};
|
||||
|
||||
function inspectLoginAuthState() {
|
||||
return {
|
||||
state: currentState,
|
||||
url: location.href,
|
||||
};
|
||||
}
|
||||
|
||||
async function recoverCurrentAuthRetryPage() {
|
||||
recoverCalls += 1;
|
||||
return { recovered: true };
|
||||
}
|
||||
|
||||
async function sleep() {
|
||||
currentState = 'login_timeout_error_page';
|
||||
}
|
||||
|
||||
function log(message, level = 'info') {
|
||||
logs.push({ message, level });
|
||||
}
|
||||
|
||||
function throwIfStopped() {}
|
||||
|
||||
function getLoginAuthStateLabel(snapshot) {
|
||||
switch (snapshot?.state) {
|
||||
case 'verification_page':
|
||||
return '登录验证码页';
|
||||
case 'login_timeout_error_page':
|
||||
return '登录超时报错页';
|
||||
default:
|
||||
return '未知页面';
|
||||
}
|
||||
}
|
||||
|
||||
${extractFunction('createStep6SuccessResult')}
|
||||
${extractFunction('createStep6RecoverableResult')}
|
||||
${extractFunction('normalizeStep6Snapshot')}
|
||||
${extractFunction('waitForKnownLoginAuthState')}
|
||||
${extractFunction('createStep6LoginTimeoutRecoveryTransition')}
|
||||
${extractFunction('createStep6LoginTimeoutRecoverableResult')}
|
||||
${extractFunction('finalizeStep6VerificationReady')}
|
||||
|
||||
return {
|
||||
async run() {
|
||||
return finalizeStep6VerificationReady({
|
||||
logLabel: '步骤 7 收尾',
|
||||
loginVerificationRequestedAt: 123,
|
||||
via: 'password_submit',
|
||||
});
|
||||
},
|
||||
snapshot() {
|
||||
return { logs, recoverCalls };
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
const result = await api.run();
|
||||
const snapshot = api.snapshot();
|
||||
|
||||
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');
|
||||
assert.equal(result.message, '登录验证码页面准备就绪前进入登录超时报错页。');
|
||||
});
|
||||
|
||||
test('waitForLoginVerificationPageReady reports login timeout page without step8 restart prefix', async () => {
|
||||
const api = new Function(`
|
||||
const location = {
|
||||
href: 'https://auth.openai.com/email-verification',
|
||||
};
|
||||
|
||||
function inspectLoginAuthState() {
|
||||
return {
|
||||
state: 'login_timeout_error_page',
|
||||
url: location.href,
|
||||
};
|
||||
}
|
||||
|
||||
function throwIfStopped() {}
|
||||
async function sleep() {}
|
||||
|
||||
function getLoginAuthStateLabel(snapshot) {
|
||||
return snapshot?.state === 'login_timeout_error_page' ? '登录超时报错页' : '未知页面';
|
||||
}
|
||||
|
||||
${extractFunction('waitForLoginVerificationPageReady')}
|
||||
|
||||
return {
|
||||
run() {
|
||||
return waitForLoginVerificationPageReady(10);
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
await assert.rejects(
|
||||
() => api.run(),
|
||||
/当前未进入登录验证码页面,请先重新完成步骤 7。当前状态:登录超时报错页。URL: https:\/\/auth\.openai\.com\/email-verification/
|
||||
);
|
||||
});
|
||||
|
||||
@@ -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 重新发起登录流程...',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -51,10 +51,8 @@ function extractFunction(name) {
|
||||
return source.slice(start, end);
|
||||
}
|
||||
|
||||
test('step 8 click effect returns restart_current_step when retry page is recovered', async () => {
|
||||
test('step 8 click effect throws when retry page appears after clicking continue', async () => {
|
||||
const api = new Function(`
|
||||
let recoverCalls = 0;
|
||||
|
||||
const chrome = {
|
||||
tabs: {
|
||||
async get() {
|
||||
@@ -69,10 +67,6 @@ const chrome = {
|
||||
function throwIfStopped() {}
|
||||
async function sleepWithStop() {}
|
||||
async function ensureStep8SignupPageReady() {}
|
||||
async function recoverAuthRetryPageOnTab() {
|
||||
recoverCalls += 1;
|
||||
return { recovered: true };
|
||||
}
|
||||
async function getStep8PageState() {
|
||||
return {
|
||||
url: 'https://auth.openai.com/authorize',
|
||||
@@ -89,20 +83,51 @@ return {
|
||||
async run() {
|
||||
return waitForStep8ClickEffect(88, 'https://auth.openai.com/authorize', 1000);
|
||||
},
|
||||
snapshot() {
|
||||
return { recoverCalls };
|
||||
};
|
||||
`)();
|
||||
|
||||
await assert.rejects(
|
||||
() => api.run(),
|
||||
/点击“继续”后页面进入认证页重试页/
|
||||
);
|
||||
});
|
||||
|
||||
test('step 8 ready check throws when consent page is already a retry page before clicking', async () => {
|
||||
const api = new Function(`
|
||||
const chrome = {
|
||||
tabs: {
|
||||
async get() {
|
||||
return {
|
||||
id: 88,
|
||||
url: 'https://auth.openai.com/authorize',
|
||||
};
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
function throwIfStopped() {}
|
||||
async function sleepWithStop() {}
|
||||
async function ensureStep8SignupPageReady() {}
|
||||
async function getStep8PageState() {
|
||||
return {
|
||||
url: 'https://auth.openai.com/authorize',
|
||||
retryPage: true,
|
||||
addPhonePage: false,
|
||||
consentReady: false,
|
||||
};
|
||||
}
|
||||
|
||||
${extractFunction('waitForStep8Ready')}
|
||||
|
||||
return {
|
||||
async run() {
|
||||
return waitForStep8Ready(88, 1000);
|
||||
},
|
||||
};
|
||||
`)();
|
||||
|
||||
const result = await api.run();
|
||||
const snapshot = api.snapshot();
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
progressed: false,
|
||||
reason: 'retry_page_recovered',
|
||||
restartCurrentStep: true,
|
||||
url: 'https://auth.openai.com/authorize',
|
||||
});
|
||||
assert.equal(snapshot.recoverCalls, 1);
|
||||
await assert.rejects(
|
||||
() => api.run(),
|
||||
/当前认证页已进入重试页/
|
||||
);
|
||||
});
|
||||
|
||||
@@ -58,6 +58,8 @@ const helperBundle = [
|
||||
extractFunction(helperSource, 'cleanupStep8NavigationListeners'),
|
||||
extractFunction(helperSource, 'rejectPendingStep8'),
|
||||
extractFunction(helperSource, 'throwIfStep8SettledOrStopped'),
|
||||
extractFunction(helperSource, 'getRunningSteps'),
|
||||
extractFunction(helperSource, 'inferStoppedRecordStep'),
|
||||
extractFunction(helperSource, 'requestStop'),
|
||||
].join('\n');
|
||||
|
||||
@@ -75,6 +77,9 @@ let autoRunTotalRuns = 3;
|
||||
let autoRunAttemptRun = 4;
|
||||
let autoRunSessionId = 99;
|
||||
const AUTO_RUN_TIMER_KIND_SCHEDULED_START = 'scheduled_start';
|
||||
const DEFAULT_STATE = {
|
||||
stepStatuses: Object.fromEntries([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((step) => [step, 'pending'])),
|
||||
};
|
||||
const STEP8_CLICK_RETRY_DELAY_MS = 500;
|
||||
const STEP8_MAX_ROUNDS = 5;
|
||||
const STEP8_READY_WAIT_TIMEOUT_MS = 30000;
|
||||
@@ -137,6 +142,7 @@ async function addLog() {}
|
||||
async function broadcastStopToContentScripts() {}
|
||||
async function markRunningStepsStopped() {}
|
||||
async function broadcastAutoRunStatus() {}
|
||||
async function appendAndBroadcastAccountRunRecord() {}
|
||||
async function getState() {
|
||||
return { autoRunning: false };
|
||||
}
|
||||
|
||||
@@ -58,23 +58,36 @@ const bundle = [
|
||||
extractFunction('summarizeStatusBadgeEntries'),
|
||||
extractFunction('normalizeStep9StatusText'),
|
||||
extractFunction('isOAuthCallbackTimeoutFailure'),
|
||||
extractFunction('isStep10CallbackSubmittedStatus'),
|
||||
extractFunction('isStep10CallbackFailureText'),
|
||||
extractFunction('isStep10MainWaitingStatus'),
|
||||
extractFunction('isStep10MainFailureText'),
|
||||
extractFunction('isStep9FailureText'),
|
||||
extractFunction('isStep9SuccessStatus'),
|
||||
extractFunction('isStep9SuccessLikeStatus'),
|
||||
extractFunction('formatStep10StatusSummaryValue'),
|
||||
extractFunction('isStep10BrowserSwitchRequiredConflict'),
|
||||
extractFunction('getStep10BrowserSwitchRequiredMessage'),
|
||||
extractFunction('buildStep9StatusDiagnostics'),
|
||||
extractFunction('extractStep10FailureDetail'),
|
||||
extractFunction('explainStep10Failure'),
|
||||
].join('\n');
|
||||
|
||||
function createApi() {
|
||||
return new Function(`
|
||||
function isRecoverableStep9AuthFailure(text) {
|
||||
return /(?:认证失败|回调 URL 提交失败):\\s*/i.test(String(text || '').trim())
|
||||
|| /oauth flow is not pending/i.test(String(text || '').trim());
|
||||
const normalized = String(text || '').trim();
|
||||
return /(?:认证失败|回调\\s*url\\s*提交失败|回调url提交失败|提交回调失败)\\s*[::]?/i.test(normalized)
|
||||
|| /oauth flow is not pending|请更新\\s*cli\\s*proxy\\s*api\\s*或检查连接|bad request|state code error|failed to exchange authorization code for tokens|failed to save authentication tokens|unknown or expired state|invalid state|state is required|code or error is required|invalid redirect_url|provider does not match state|failed to persist oauth callback|timeout waiting for oauth callback|oauth flow timed out/i.test(normalized);
|
||||
}
|
||||
|
||||
${bundle}
|
||||
|
||||
return {
|
||||
buildStep9StatusDiagnostics,
|
||||
explainStep10Failure,
|
||||
isStep10BrowserSwitchRequiredConflict,
|
||||
getStep10BrowserSwitchRequiredMessage,
|
||||
};
|
||||
`)();
|
||||
}
|
||||
@@ -86,6 +99,7 @@ test('step 9 does not treat red success badges as exact success', () => {
|
||||
visible: true,
|
||||
text: '认证成功!',
|
||||
className: 'status-badge text-danger',
|
||||
location: 'main',
|
||||
hasErrorVisualSignal: true,
|
||||
errorVisualSummary: 'color=rgb(220, 38, 38)',
|
||||
},
|
||||
@@ -104,23 +118,118 @@ test('step 9 keeps failure state dominant when success badge and error banner co
|
||||
visible: true,
|
||||
text: '认证成功!',
|
||||
className: 'status-badge',
|
||||
location: 'main',
|
||||
hasErrorVisualSignal: false,
|
||||
errorVisualSummary: '',
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
visible: true,
|
||||
text: '回调 URL 提交失败: oauth flow is not pending',
|
||||
className: 'alert alert-danger',
|
||||
className: 'status-badge error',
|
||||
location: 'callback',
|
||||
hasErrorVisualSignal: true,
|
||||
errorVisualSummary: 'color=rgb(220, 38, 38)',
|
||||
},
|
||||
],
|
||||
[],
|
||||
'page'
|
||||
);
|
||||
|
||||
assert.equal(diagnostics.hasExactSuccessVisibleBadge, true);
|
||||
assert.equal(diagnostics.hasFailureVisibleBadge, true);
|
||||
assert.equal(diagnostics.failureText, '回调 URL 提交失败: oauth flow is not pending');
|
||||
assert.equal(diagnostics.failureSource, 'callback');
|
||||
});
|
||||
|
||||
test('step 10 treats plain 认证成功 as success when no failure is visible', () => {
|
||||
const api = createApi();
|
||||
const diagnostics = api.buildStep9StatusDiagnostics(
|
||||
[
|
||||
{
|
||||
visible: true,
|
||||
text: '认证成功',
|
||||
className: 'status-badge',
|
||||
location: 'main',
|
||||
hasErrorVisualSignal: false,
|
||||
errorVisualSummary: '',
|
||||
},
|
||||
],
|
||||
[],
|
||||
'page'
|
||||
);
|
||||
|
||||
assert.equal(diagnostics.hasExactSuccessVisibleBadge, true);
|
||||
assert.equal(diagnostics.exactSuccessText, '认证成功');
|
||||
});
|
||||
|
||||
test('step 10 recognizes callback accepted badge as in-progress signal', () => {
|
||||
const api = createApi();
|
||||
const diagnostics = api.buildStep9StatusDiagnostics(
|
||||
[
|
||||
{
|
||||
visible: true,
|
||||
text: '回调 URL 已提交,等待认证中...',
|
||||
className: 'status-badge success',
|
||||
location: 'callback',
|
||||
hasErrorVisualSignal: false,
|
||||
errorVisualSummary: '',
|
||||
},
|
||||
{
|
||||
visible: true,
|
||||
text: '等待认证中...',
|
||||
className: 'status-badge',
|
||||
location: 'main',
|
||||
hasErrorVisualSignal: false,
|
||||
errorVisualSummary: '',
|
||||
},
|
||||
],
|
||||
[],
|
||||
'page'
|
||||
);
|
||||
|
||||
assert.equal(diagnostics.hasCallbackSubmittedBadge, true);
|
||||
assert.equal(diagnostics.callbackSubmittedText, '回调 URL 已提交,等待认证中...');
|
||||
assert.equal(diagnostics.mainWaitingText, '等待认证中...');
|
||||
assert.equal(diagnostics.hasExactSuccessVisibleBadge, false);
|
||||
});
|
||||
|
||||
test('step 10 explains callback upgrade hint with user-friendly reason', () => {
|
||||
const api = createApi();
|
||||
const explanation = api.explainStep10Failure(
|
||||
'回调 URL 提交失败: 请更新CLI Proxy API或检查连接',
|
||||
'callback'
|
||||
);
|
||||
|
||||
assert.equal(explanation.code, 'callback_submit_api_unavailable');
|
||||
assert.match(explanation.userMessage, /CLI Proxy API 版本过旧|管理接口未启动|连接异常/);
|
||||
assert.match(explanation.userMessage, /回调提交阶段/);
|
||||
});
|
||||
|
||||
test('step 10 requests browser switch when success badge and callback upgrade failure coexist', () => {
|
||||
const api = createApi();
|
||||
const diagnostics = api.buildStep9StatusDiagnostics(
|
||||
[
|
||||
{
|
||||
visible: true,
|
||||
text: '认证成功',
|
||||
className: 'status-badge success',
|
||||
location: 'main',
|
||||
hasErrorVisualSignal: false,
|
||||
errorVisualSummary: '',
|
||||
},
|
||||
{
|
||||
visible: true,
|
||||
text: '回调 URL 提交失败: 请更新CLI Proxy API或检查连接',
|
||||
className: 'status-badge error',
|
||||
location: 'callback',
|
||||
hasErrorVisualSignal: true,
|
||||
errorVisualSummary: 'color=rgb(220, 38, 38)',
|
||||
},
|
||||
],
|
||||
[],
|
||||
'page'
|
||||
);
|
||||
|
||||
assert.equal(api.isStep10BrowserSwitchRequiredConflict(diagnostics), true);
|
||||
assert.match(api.getStep10BrowserSwitchRequiredMessage(diagnostics), /更换浏览器后重新进行注册登录/);
|
||||
});
|
||||
|
||||
@@ -6,7 +6,7 @@ const source = fs.readFileSync('background/verification-flow.js', 'utf8');
|
||||
const globalScope = {};
|
||||
const api = new Function('self', `${source}; return self.MultiPageBackgroundVerificationFlow;`)(globalScope);
|
||||
|
||||
test('verification flow extends 2925 polling window', () => {
|
||||
test('verification flow keeps 2925 polling cadence in the default payload', () => {
|
||||
const helpers = api.createVerificationFlowHelpers({
|
||||
addLog: async () => {},
|
||||
chrome: { tabs: { update: async () => {} } },
|
||||
@@ -37,14 +37,55 @@ test('verification flow extends 2925 polling window', () => {
|
||||
const step4Payload = helpers.getVerificationPollPayload(4, { email: 'user@example.com', mailProvider: '2925' });
|
||||
const step8Payload = helpers.getVerificationPollPayload(8, { email: 'user@example.com', mailProvider: '2925' });
|
||||
|
||||
assert.equal(step4Payload.filterAfterTimestamp, 0);
|
||||
assert.equal(step4Payload.maxAttempts, 15);
|
||||
assert.equal(step4Payload.intervalMs, 15000);
|
||||
assert.equal(step8Payload.filterAfterTimestamp, 0);
|
||||
assert.equal(step8Payload.maxAttempts, 15);
|
||||
assert.equal(step8Payload.intervalMs, 15000);
|
||||
});
|
||||
|
||||
test('verification flow only enables 2925 target email matching in receive mode', () => {
|
||||
const helpers = api.createVerificationFlowHelpers({
|
||||
addLog: async () => {},
|
||||
chrome: { tabs: { update: async () => {} } },
|
||||
CLOUDFLARE_TEMP_EMAIL_PROVIDER: 'cloudflare-temp-email',
|
||||
completeStepFromBackground: async () => {},
|
||||
confirmCustomVerificationStepBypassRequest: async () => ({ confirmed: true }),
|
||||
getHotmailVerificationPollConfig: () => ({}),
|
||||
getHotmailVerificationRequestTimestamp: () => 0,
|
||||
getState: async () => ({}),
|
||||
getTabId: async () => 1,
|
||||
HOTMAIL_PROVIDER: 'hotmail-api',
|
||||
isStopError: () => false,
|
||||
LUCKMAIL_PROVIDER: 'luckmail-api',
|
||||
MAIL_2925_VERIFICATION_INTERVAL_MS: 15000,
|
||||
MAIL_2925_VERIFICATION_MAX_ATTEMPTS: 15,
|
||||
pollCloudflareTempEmailVerificationCode: async () => ({}),
|
||||
pollHotmailVerificationCode: async () => ({}),
|
||||
pollLuckmailVerificationCode: async () => ({}),
|
||||
sendToContentScript: async () => ({}),
|
||||
sendToMailContentScriptResilient: async () => ({}),
|
||||
setState: async () => {},
|
||||
setStepStatus: async () => {},
|
||||
sleepWithStop: async () => {},
|
||||
throwIfStopped: () => {},
|
||||
VERIFICATION_POLL_MAX_ROUNDS: 5,
|
||||
});
|
||||
|
||||
const providePayload = helpers.getVerificationPollPayload(4, {
|
||||
email: 'user@example.com',
|
||||
mailProvider: '2925',
|
||||
mail2925Mode: 'provide',
|
||||
});
|
||||
const receivePayload = helpers.getVerificationPollPayload(4, {
|
||||
email: 'user@example.com',
|
||||
mailProvider: '2925',
|
||||
mail2925Mode: 'receive',
|
||||
});
|
||||
|
||||
assert.equal(providePayload.mail2925MatchTargetEmail, false);
|
||||
assert.equal(receivePayload.mail2925MatchTargetEmail, true);
|
||||
});
|
||||
|
||||
test('verification flow runs beforeSubmit hook before filling the code', async () => {
|
||||
const events = [];
|
||||
|
||||
@@ -111,7 +152,7 @@ test('verification flow runs beforeSubmit hook before filling the code', async (
|
||||
]);
|
||||
});
|
||||
|
||||
test('verification flow triggers 2925 mailbox cleanup only after code submission succeeds', async () => {
|
||||
test('verification flow skips 2925 mailbox preclear when using a fixed login mail window and still clears after success', async () => {
|
||||
const mailMessages = [];
|
||||
|
||||
const helpers = api.createVerificationFlowHelpers({
|
||||
@@ -164,7 +205,74 @@ test('verification flow triggers 2925 mailbox cleanup only after code submission
|
||||
lastLoginCode: null,
|
||||
},
|
||||
{ provider: '2925', label: '2925 邮箱' },
|
||||
{}
|
||||
{ filterAfterTimestamp: 123456 }
|
||||
);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
assert.deepStrictEqual(mailMessages, ['POLL_EMAIL', 'DELETE_ALL_EMAILS']);
|
||||
});
|
||||
|
||||
test('verification flow skips 2925 mailbox preclear when using a fixed signup mail window and still clears after success', async () => {
|
||||
const mailMessages = [];
|
||||
|
||||
const helpers = api.createVerificationFlowHelpers({
|
||||
addLog: async () => {},
|
||||
chrome: {
|
||||
tabs: {
|
||||
update: async () => {},
|
||||
},
|
||||
},
|
||||
CLOUDFLARE_TEMP_EMAIL_PROVIDER: 'cloudflare-temp-email',
|
||||
completeStepFromBackground: async () => {},
|
||||
confirmCustomVerificationStepBypassRequest: async () => ({ confirmed: true }),
|
||||
getHotmailVerificationPollConfig: () => ({}),
|
||||
getHotmailVerificationRequestTimestamp: () => 0,
|
||||
getState: async () => ({}),
|
||||
getTabId: async () => 1,
|
||||
HOTMAIL_PROVIDER: 'hotmail-api',
|
||||
isStopError: () => false,
|
||||
LUCKMAIL_PROVIDER: 'luckmail-api',
|
||||
MAIL_2925_VERIFICATION_INTERVAL_MS: 15000,
|
||||
MAIL_2925_VERIFICATION_MAX_ATTEMPTS: 15,
|
||||
pollCloudflareTempEmailVerificationCode: async () => ({}),
|
||||
pollHotmailVerificationCode: async () => ({}),
|
||||
pollLuckmailVerificationCode: async () => ({}),
|
||||
sendToContentScript: async (_source, message) => {
|
||||
if (message.type === 'FILL_CODE') {
|
||||
return {};
|
||||
}
|
||||
if (message.type === 'RESEND_VERIFICATION_CODE') {
|
||||
return {};
|
||||
}
|
||||
return {};
|
||||
},
|
||||
sendToMailContentScriptResilient: async (_mail, message) => {
|
||||
mailMessages.push(message.type);
|
||||
if (message.type === 'POLL_EMAIL') {
|
||||
return { code: '654321', emailTimestamp: 123 };
|
||||
}
|
||||
return { ok: true, deleted: true };
|
||||
},
|
||||
setState: async () => {},
|
||||
setStepStatus: async () => {},
|
||||
sleepWithStop: async () => {},
|
||||
throwIfStopped: () => {},
|
||||
VERIFICATION_POLL_MAX_ROUNDS: 5,
|
||||
});
|
||||
|
||||
await helpers.resolveVerificationStep(
|
||||
4,
|
||||
{
|
||||
email: 'user@example.com',
|
||||
mailProvider: '2925',
|
||||
lastSignupCode: null,
|
||||
},
|
||||
{ provider: '2925', label: '2925 邮箱' },
|
||||
{
|
||||
filterAfterTimestamp: 123456,
|
||||
requestFreshCodeFirst: false,
|
||||
}
|
||||
);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
@@ -301,6 +409,73 @@ test('verification flow caps mail polling timeout to the remaining oauth budget'
|
||||
assert.equal(mailPollCalls[0].payload.maxAttempts, 2);
|
||||
});
|
||||
|
||||
test('verification flow keeps 2925 mailbox polling at 15 refresh attempts even when oauth budget is smaller', async () => {
|
||||
const mailPollCalls = [];
|
||||
|
||||
const helpers = api.createVerificationFlowHelpers({
|
||||
addLog: async () => {},
|
||||
chrome: {
|
||||
tabs: {
|
||||
update: async () => {},
|
||||
},
|
||||
},
|
||||
CLOUDFLARE_TEMP_EMAIL_PROVIDER: 'cloudflare-temp-email',
|
||||
completeStepFromBackground: async () => {},
|
||||
confirmCustomVerificationStepBypassRequest: async () => ({ confirmed: true }),
|
||||
getHotmailVerificationPollConfig: () => ({}),
|
||||
getHotmailVerificationRequestTimestamp: () => 0,
|
||||
getState: async () => ({}),
|
||||
getTabId: async () => 1,
|
||||
HOTMAIL_PROVIDER: 'hotmail-api',
|
||||
isStopError: () => false,
|
||||
LUCKMAIL_PROVIDER: 'luckmail-api',
|
||||
MAIL_2925_VERIFICATION_INTERVAL_MS: 15000,
|
||||
MAIL_2925_VERIFICATION_MAX_ATTEMPTS: 15,
|
||||
pollCloudflareTempEmailVerificationCode: async () => ({}),
|
||||
pollHotmailVerificationCode: async () => ({}),
|
||||
pollLuckmailVerificationCode: async () => ({}),
|
||||
sendToContentScript: async (_source, message) => {
|
||||
if (message.type === 'FILL_CODE') {
|
||||
return {};
|
||||
}
|
||||
return {};
|
||||
},
|
||||
sendToMailContentScriptResilient: async (_mail, message, options) => {
|
||||
mailPollCalls.push({
|
||||
type: message.type,
|
||||
payload: message.payload,
|
||||
options,
|
||||
});
|
||||
return { code: '654321', emailTimestamp: 123 };
|
||||
},
|
||||
setState: async () => {},
|
||||
setStepStatus: async () => {},
|
||||
sleepWithStop: async () => {},
|
||||
throwIfStopped: () => {},
|
||||
VERIFICATION_POLL_MAX_ROUNDS: 5,
|
||||
});
|
||||
|
||||
await helpers.resolveVerificationStep(
|
||||
8,
|
||||
{
|
||||
email: 'user@example.com',
|
||||
mailProvider: '2925',
|
||||
lastLoginCode: null,
|
||||
},
|
||||
{ provider: '2925', label: '2925 邮箱' },
|
||||
{
|
||||
getRemainingTimeMs: async () => 5000,
|
||||
resendIntervalMs: 0,
|
||||
disableTimeBudgetCap: true,
|
||||
}
|
||||
);
|
||||
|
||||
const pollCall = mailPollCalls.find((entry) => entry.type === 'POLL_EMAIL');
|
||||
assert.ok(pollCall);
|
||||
assert.equal(pollCall.payload.maxAttempts, 15);
|
||||
assert.ok(pollCall.options.timeoutMs >= 250000);
|
||||
});
|
||||
|
||||
test('verification flow keeps Hotmail request timestamp filtering on the first poll', async () => {
|
||||
const pollPayloads = [];
|
||||
|
||||
|
||||
Reference in New Issue
Block a user