feat:新增CloudflareTempEmail

This commit is contained in:
Twelveeee
2026-04-13 17:27:42 +08:00
parent a2ef57da7e
commit 0614917ad4
9 changed files with 1258 additions and 17 deletions
@@ -60,11 +60,19 @@ const bundle = [
extractFunction('hasSavedProgress'),
extractFunction('getRunningSteps'),
extractFunction('getAutoRunStatusPayload'),
extractFunction('createAutoRunRoundSummary'),
extractFunction('normalizeAutoRunRoundSummary'),
extractFunction('buildAutoRunRoundSummaries'),
extractFunction('serializeAutoRunRoundSummaries'),
extractFunction('getAutoRunRoundRetryCount'),
extractFunction('formatAutoRunFailureReasons'),
extractFunction('logAutoRunFinalSummary'),
extractFunction('autoRunLoop'),
].join('\n');
const api = new Function(`
const STOP_ERROR_MESSAGE = 'Flow stopped.';
const AUTO_RUN_MAX_RETRIES_PER_ROUND = 3;
const DEFAULT_STATE = {
stepStatuses: {
1: 'pending',
@@ -0,0 +1,160 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const source = fs.readFileSync('background.js', 'utf8');
function extractFunction(name) {
const markers = [`async function ${name}(`, `function ${name}(`];
const start = markers
.map((marker) => source.indexOf(marker))
.find((index) => index >= 0);
if (start < 0) {
throw new Error(`missing function ${name}`);
}
let parenDepth = 0;
let signatureEnded = false;
let braceStart = -1;
for (let i = start; i < source.length; i += 1) {
const ch = source[i];
if (ch === '(') {
parenDepth += 1;
} else if (ch === ')') {
parenDepth -= 1;
if (parenDepth === 0) {
signatureEnded = true;
}
} else if (ch === '{' && signatureEnded) {
braceStart = i;
break;
}
}
if (braceStart < 0) {
throw new Error(`missing body for function ${name}`);
}
let depth = 0;
let end = braceStart;
for (; end < source.length; end += 1) {
const ch = source[end];
if (ch === '{') depth += 1;
if (ch === '}') {
depth -= 1;
if (depth === 0) {
end += 1;
break;
}
}
}
return source.slice(start, end);
}
test('pollCloudflareTempEmailVerificationCode returns code even if delete fails', async () => {
const bundle = [
extractFunction('isStopError'),
extractFunction('throwIfStopped'),
extractFunction('summarizeCloudflareTempEmailMessagesForLog'),
extractFunction('pollCloudflareTempEmailVerificationCode'),
].join('\n');
const api = new Function(`
let stopRequested = false;
const STOP_ERROR_MESSAGE = '流程已被用户停止。';
const CLOUDFLARE_TEMP_EMAIL_DEFAULT_PAGE_SIZE = 20;
const logs = [];
function normalizeCloudflareTempEmailAddress(value) {
return String(value || '').trim().toLowerCase();
}
async function addLog(message, level) {
logs.push({ message, level });
}
async function sleepWithStop() {}
async function listCloudflareTempEmailMessages() {
return {
config: {},
messages: [{
id: 'mail-1',
address: 'user@example.com',
receivedDateTime: '2026-04-13T09:20:00.000Z',
subject: 'OpenAI verification code',
from: { emailAddress: { address: 'noreply@tm.openai.com' } },
bodyPreview: 'Your verification code is 123456.',
}],
};
}
function pickVerificationMessageWithTimeFallback(messages) {
return {
match: {
code: '123456',
receivedAt: Date.parse(messages[0].receivedDateTime),
message: messages[0],
},
usedRelaxedFilters: false,
usedTimeFallback: false,
};
}
async function deleteCloudflareTempEmailMail() {
throw new Error('delete failed');
}
${bundle}
return {
pollCloudflareTempEmailVerificationCode,
snapshot() {
return { logs };
},
};
`)();
const result = await api.pollCloudflareTempEmailVerificationCode(4, { email: 'user@example.com' }, {
targetEmail: 'user@example.com',
maxAttempts: 1,
intervalMs: 1,
});
assert.equal(result.code, '123456');
const state = api.snapshot();
assert.equal(state.logs.some((entry) => entry.message.includes('删除 Cloudflare Temp Email 邮件失败')), true);
});
test('pollCloudflareTempEmailVerificationCode requires target email', async () => {
const bundle = [
extractFunction('isStopError'),
extractFunction('throwIfStopped'),
extractFunction('pollCloudflareTempEmailVerificationCode'),
].join('\n');
const api = new Function(`
let stopRequested = false;
const STOP_ERROR_MESSAGE = '流程已被用户停止。';
const CLOUDFLARE_TEMP_EMAIL_DEFAULT_PAGE_SIZE = 20;
function normalizeCloudflareTempEmailAddress(value) {
return String(value || '').trim().toLowerCase();
}
async function addLog() {}
async function sleepWithStop() {}
async function listCloudflareTempEmailMessages() {
throw new Error('should not reach list');
}
function pickVerificationMessageWithTimeFallback() {
return { match: null, usedRelaxedFilters: false, usedTimeFallback: false };
}
async function deleteCloudflareTempEmailMail() {}
function summarizeCloudflareTempEmailMessagesForLog() {
return '';
}
${bundle}
return { pollCloudflareTempEmailVerificationCode };
`)();
await assert.rejects(
api.pollCloudflareTempEmailVerificationCode(4, {}, {}),
/缺少目标邮箱地址/
);
});
+107
View File
@@ -0,0 +1,107 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const {
buildCloudflareTempEmailHeaders,
getCloudflareTempEmailAddressFromResponse,
normalizeCloudflareTempEmailBaseUrl,
normalizeCloudflareTempEmailDomain,
normalizeCloudflareTempEmailDomains,
normalizeCloudflareTempEmailMailApiMessages,
} = require('../cloudflare-temp-email-utils.js');
test('normalizeCloudflareTempEmailBaseUrl normalizes host and preserves path', () => {
assert.equal(
normalizeCloudflareTempEmailBaseUrl('temp.example.com/api/'),
'https://temp.example.com/api'
);
assert.equal(
normalizeCloudflareTempEmailBaseUrl('http://127.0.0.1:8787'),
'http://127.0.0.1:8787'
);
assert.equal(normalizeCloudflareTempEmailBaseUrl('::::'), '');
});
test('normalizeCloudflareTempEmailDomain and domains de-duplicate valid entries', () => {
assert.equal(normalizeCloudflareTempEmailDomain('@Mail.Example.com'), 'mail.example.com');
assert.equal(normalizeCloudflareTempEmailDomain('not-a-domain'), '');
assert.deepEqual(
normalizeCloudflareTempEmailDomains(['mail.example.com', 'MAIL.EXAMPLE.COM', 'bad-value']),
['mail.example.com']
);
});
test('buildCloudflareTempEmailHeaders includes auth headers and content type when needed', () => {
assert.deepEqual(
buildCloudflareTempEmailHeaders(
{
adminAuth: 'admin-secret',
customAuth: 'site-secret',
},
{ json: true }
),
{
'x-admin-auth': 'admin-secret',
'x-custom-auth': 'site-secret',
'Content-Type': 'application/json',
Accept: 'application/json',
}
);
});
test('normalizeCloudflareTempEmailMailApiMessages extracts sender, subject, code, and address from raw mime', () => {
const messages = normalizeCloudflareTempEmailMailApiMessages({
data: [
{
id: 'mail-1',
address: 'user@example.com',
created_at: '2026-04-13T09:15:00.000Z',
raw: [
'From: OpenAI <noreply@tm.openai.com>',
'Subject: =?UTF-8?B?T3BlbkFJIHZlcmlmaWNhdGlvbiBjb2Rl?=',
'Content-Type: text/plain; charset=UTF-8',
'',
'Your verification code is 654321.',
].join('\r\n'),
},
],
});
assert.equal(messages.length, 1);
assert.equal(messages[0].id, 'mail-1');
assert.equal(messages[0].address, 'user@example.com');
assert.equal(messages[0].subject, 'OpenAI verification code');
assert.equal(messages[0].from.emailAddress.address, 'OpenAI <noreply@tm.openai.com>');
assert.match(messages[0].bodyPreview, /654321/);
});
test('normalizeCloudflareTempEmailMailApiMessages decodes multipart quoted printable html bodies', () => {
const messages = normalizeCloudflareTempEmailMailApiMessages([
{
id: 'mail-2',
address: 'user@example.com',
received_at: '2026-04-13T09:20:00.000Z',
source: [
'From: ChatGPT <noreply@tm.openai.com>',
'Subject: Login code',
'Content-Type: multipart/alternative; boundary="abc123"',
'',
'--abc123',
'Content-Type: text/html; charset=UTF-8',
'Content-Transfer-Encoding: quoted-printable',
'',
'<p>Your login code is <strong>112233</strong>.</p>',
'--abc123--',
].join('\r\n'),
},
]);
assert.equal(messages.length, 1);
assert.match(messages[0].bodyPreview, /112233/);
assert.equal(messages[0].subject, 'Login code');
});
test('getCloudflareTempEmailAddressFromResponse supports direct and nested response shapes', () => {
assert.equal(getCloudflareTempEmailAddressFromResponse({ address: 'one@example.com' }), 'one@example.com');
assert.equal(getCloudflareTempEmailAddressFromResponse({ data: { address: 'two@example.com' } }), 'two@example.com');
});
@@ -52,7 +52,11 @@ function extractFunction(name) {
const bundle = [
extractFunction('getTabRegistry'),
extractFunction('normalizeEmailGenerator'),
extractFunction('parseUrlSafely'),
extractFunction('isHotmailProvider'),
extractFunction('isGeneratedAliasProvider'),
extractFunction('shouldUseCustomRegistrationEmail'),
extractFunction('isLocalhostOAuthCallbackUrl'),
extractFunction('isLocalhostOAuthCallbackTabMatch'),
extractFunction('closeLocalhostCallbackTabs'),
@@ -62,6 +66,9 @@ const bundle = [
].join('\n');
const api = new Function(`
const HOTMAIL_PROVIDER = 'hotmail-api';
const CLOUDFLARE_TEMP_EMAIL_PROVIDER = 'cloudflare-temp-email';
const CLOUDFLARE_TEMP_EMAIL_GENERATOR = 'cloudflare-temp-email';
let currentState = {
tabRegistry: {
'signup-page': { tabId: 1, ready: true },
+4 -2
View File
@@ -57,10 +57,11 @@ async function testPollFreshVerificationCodeRethrowsStop() {
extractFunction('pollFreshVerificationCode'),
].join('\n');
const api = new Function(`
const api = new Function(`
let stopRequested = false;
const STOP_ERROR_MESSAGE = '流程已被用户停止。';
const HOTMAIL_PROVIDER = 'hotmail-api';
const CLOUDFLARE_TEMP_EMAIL_PROVIDER = 'cloudflare-temp-email';
const VERIFICATION_POLL_MAX_ROUNDS = 5;
const logs = [];
let resendCalls = 0;
@@ -119,9 +120,10 @@ async function testResolveVerificationStepRethrowsStopFromFreshRequest() {
extractFunction('resolveVerificationStep'),
].join('\n');
const api = new Function(`
const api = new Function(`
const STOP_ERROR_MESSAGE = '流程已被用户停止。';
const HOTMAIL_PROVIDER = 'hotmail-api';
const CLOUDFLARE_TEMP_EMAIL_PROVIDER = 'cloudflare-temp-email';
const logs = [];
let pollCalls = 0;