Pārlūkot izejas kodu

Add A4Sky mail provider and phplife code polling

chendeben 4 mēneši atpakaļ
vecāks
revīzija
91b0399fc2

+ 14 - 0
background.js

@@ -126,6 +126,7 @@ const ICLOUD_LOGIN_URLS = [
 ];
 const ICLOUD_PROVIDER = 'icloud';
 const GMAIL_PROVIDER = 'gmail';
+const A4SKY_PROVIDER = 'a4sky';
 const HOTMAIL_PROVIDER = 'hotmail-api';
 const LUCKMAIL_PROVIDER = 'luckmail-api';
 const CLOUDFLARE_TEMP_EMAIL_PROVIDER = 'cloudflare-temp-email';
@@ -621,6 +622,7 @@ function normalizeMailProvider(value = '') {
     case 'custom':
     case ICLOUD_PROVIDER:
     case GMAIL_PROVIDER:
+    case A4SKY_PROVIDER:
     case HOTMAIL_PROVIDER:
     case LUCKMAIL_PROVIDER:
     case CLOUDFLARE_TEMP_EMAIL_PROVIDER:
@@ -5704,6 +5706,7 @@ const signupFlowHelpers = self.MultiPageSignupFlowHelpers?.createSignupFlowHelpe
   waitForTabUrlMatch,
 });
 const verificationFlowHelpers = self.MultiPageBackgroundVerificationFlow?.createVerificationFlowHelpers({
+  A4SKY_PROVIDER,
   addLog,
   chrome,
   CLOUDFLARE_TEMP_EMAIL_PROVIDER,
@@ -6048,6 +6051,17 @@ function getMailConfig(state) {
       injectSource: 'gmail-mail',
     };
   }
+  if (provider === A4SKY_PROVIDER) {
+    return {
+      provider: A4SKY_PROVIDER,
+      source: 'mail-phplife',
+      url: 'https://mail.phplife.net/?_task=mail&_mbox=INBOX',
+      label: 'A4Sky 邮箱(mail.phplife.net)',
+      navigateOnReuse: true,
+      inject: ['content/activation-utils.js', 'content/utils.js', 'content/phplife-mail.js'],
+      injectSource: 'mail-phplife',
+    };
+  }
   if (provider === LUCKMAIL_PROVIDER) {
     return { provider: LUCKMAIL_PROVIDER, label: 'LuckMail(API 购邮)' };
   }

+ 30 - 0
background/generated-email-helpers.js

@@ -1,6 +1,8 @@
 (function attachGeneratedEmailHelpers(root, factory) {
   root.MultiPageGeneratedEmailHelpers = factory();
 })(typeof self !== 'undefined' ? self : globalThis, function createGeneratedEmailHelpersModule() {
+  const A4SKY_PROVIDER = 'a4sky';
+
   function createGeneratedEmailHelpers(deps = {}) {
     const {
       addLog,
@@ -24,6 +26,29 @@
       throwIfStopped,
     } = deps;
 
+    function padNumber(value) {
+      return String(value).padStart(2, '0');
+    }
+
+    function buildA4skyTimestamp(date = new Date()) {
+      return [
+        date.getFullYear(),
+        padNumber(date.getMonth() + 1),
+        padNumber(date.getDate()),
+        padNumber(date.getHours()),
+        padNumber(date.getMinutes()),
+        padNumber(date.getSeconds()),
+      ].join('');
+    }
+
+    async function fetchA4skyEmail() {
+      throwIfStopped();
+      const email = `n${buildA4skyTimestamp()}@a4sky.com`;
+      await setEmailState(email);
+      await addLog(`A4Sky 邮箱:已生成 ${email}`, 'ok');
+      return email;
+    }
+
     function generateCloudflareAliasLocalPart() {
       const letters = 'abcdefghijklmnopqrstuvwxyz';
       const digits = '0123456789';
@@ -210,6 +235,9 @@
     async function fetchGeneratedEmail(state, options = {}) {
       const currentState = state || await getState();
       const provider = String(options.mailProvider || currentState.mailProvider || '').trim().toLowerCase();
+      if (provider === A4SKY_PROVIDER) {
+        return fetchA4skyEmail();
+      }
       if (isGeneratedAliasProvider?.(provider)) {
         return fetchManagedAliasEmail(currentState, options);
       }
@@ -231,10 +259,12 @@
 
     return {
       ensureCloudflareTempEmailConfig,
+      fetchA4skyEmail,
       fetchCloudflareEmail,
       fetchCloudflareTempEmailAddress,
       fetchDuckEmail,
       fetchGeneratedEmail,
+      buildA4skyTimestamp,
       generateCloudflareAliasLocalPart,
       requestCloudflareTempEmailJson,
     };

+ 23 - 4
background/verification-flow.js

@@ -3,6 +3,7 @@
 })(typeof self !== 'undefined' ? self : globalThis, function createBackgroundVerificationFlowModule() {
   function createVerificationFlowHelpers(deps = {}) {
     const {
+      A4SKY_PROVIDER,
       addLog,
       chrome,
       CLOUDFLARE_TEMP_EMAIL_PROVIDER,
@@ -28,6 +29,8 @@
       VERIFICATION_POLL_MAX_ROUNDS,
     } = deps;
 
+    const A4SKY_MANUAL_LOGIN_RESPONSE_TIMEOUT_MS = 20 * 60 * 1000;
+
     function getVerificationCodeStateKey(step) {
       return step === 4 ? 'lastSignupCode' : 'lastLoginCode';
     }
@@ -185,6 +188,24 @@
       };
     }
 
+    function getMailContentScriptTimeoutOptions(mail, timedPoll = {}) {
+      if (mail?.provider === A4SKY_PROVIDER) {
+        const extendedTimeoutMs = Math.max(
+          Number(timedPoll.responseTimeoutMs) || 0,
+          A4SKY_MANUAL_LOGIN_RESPONSE_TIMEOUT_MS
+        );
+        return {
+          timeoutMs: extendedTimeoutMs,
+          responseTimeoutMs: extendedTimeoutMs,
+        };
+      }
+
+      return {
+        timeoutMs: timedPoll.timeoutMs,
+        responseTimeoutMs: timedPoll.responseTimeoutMs,
+      };
+    }
+
     async function requestVerificationCodeResend(step, options = {}) {
       throwIfStopped();
       const signupTabId = await getTabId('signup-page');
@@ -310,9 +331,8 @@
                 payload: timedPoll.payload,
               },
               {
-                timeoutMs: timedPoll.timeoutMs,
+                ...getMailContentScriptTimeoutOptions(mail, timedPoll),
                 maxRecoveryAttempts: 2,
-                responseTimeoutMs: timedPoll.responseTimeoutMs,
               }
             );
 
@@ -448,9 +468,8 @@
               payload: timedPoll.payload,
             },
             {
-              timeoutMs: timedPoll.timeoutMs,
+              ...getMailContentScriptTimeoutOptions(mail, timedPoll),
               maxRecoveryAttempts: 2,
-              responseTimeoutMs: timedPoll.responseTimeoutMs,
             }
           );
 

+ 545 - 0
content/phplife-mail.js

@@ -0,0 +1,545 @@
+// content/phplife-mail.js — Content script for A4Sky mailbox on mail.phplife.net
+// Injected dynamically on: mail.phplife.net
+
+const PHPLIFE_MAIL_PREFIX = '[MultiPage:mail-phplife]';
+const isTopFrame = window === window.top;
+
+console.log(PHPLIFE_MAIL_PREFIX, 'Content script loaded on', location.href, 'frame:', isTopFrame ? 'top' : 'child');
+
+if (!isTopFrame) {
+  console.log(PHPLIFE_MAIL_PREFIX, 'Skipping child frame');
+} else {
+
+let seenCodes = new Set();
+let waitingLoginLogged = false;
+
+async function loadSeenCodes() {
+  try {
+    const data = await chrome.storage.session.get('seenPhplifeCodes');
+    if (Array.isArray(data.seenPhplifeCodes)) {
+      seenCodes = new Set(data.seenPhplifeCodes.filter(Boolean));
+    }
+  } catch (err) {
+    console.warn(PHPLIFE_MAIL_PREFIX, 'Could not load seen codes:', err?.message || err);
+  }
+}
+
+loadSeenCodes();
+
+async function persistSeenCodes() {
+  try {
+    await chrome.storage.session.set({ seenPhplifeCodes: [...seenCodes] });
+  } catch (err) {
+    console.warn(PHPLIFE_MAIL_PREFIX, 'Could not persist seen codes:', err?.message || err);
+  }
+}
+
+chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
+  if (message.type === 'POLL_EMAIL') {
+    resetStopState();
+    handlePollEmail(message.step, message.payload).then((result) => {
+      sendResponse(result);
+    }).catch((err) => {
+      if (isStopError(err)) {
+        log(`步骤 ${message.step}:已被用户停止。`, 'warn');
+        sendResponse({ stopped: true, error: err.message });
+        return;
+      }
+      log(`步骤 ${message.step}:A4Sky 邮箱轮询失败:${err.message}`, 'warn');
+      sendResponse({ error: err.message });
+    });
+    return true;
+  }
+});
+
+function normalizeText(value) {
+  return String(value || '').replace(/\s+/g, ' ').trim();
+}
+
+function sleep(ms) {
+  return new Promise((resolve, reject) => {
+    if (flowStopped) {
+      reject(new Error(STOP_ERROR_MESSAGE));
+      return;
+    }
+    setTimeout(() => {
+      if (flowStopped) {
+        reject(new Error(STOP_ERROR_MESSAGE));
+        return;
+      }
+      resolve();
+    }, ms);
+  });
+}
+
+function isVisibleElement(element) {
+  if (!element) return false;
+  const style = window.getComputedStyle(element);
+  if (style.display === 'none' || style.visibility === 'hidden') return false;
+  const rect = element.getBoundingClientRect();
+  return rect.width > 0 && rect.height > 0;
+}
+
+function getRcmailEnv() {
+  try {
+    return window.rcmail?.env || null;
+  } catch {
+    return null;
+  }
+}
+
+function isLoginPageLikely() {
+  const url = location.href.toLowerCase();
+  if (/[_-]task=login|[?&]_action=login\b|\/login\b/.test(url)) {
+    return true;
+  }
+
+  const passwordInput = document.querySelector('input[type="password"]');
+  const loginForm = document.querySelector('form[action*="login"], form[name*="login"], #login-form, .login-form');
+  const loginButton = Array.from(document.querySelectorAll('button, input[type="submit"], a')).find((element) => {
+    const text = normalizeText(
+      element?.textContent
+      || element?.value
+      || element?.getAttribute?.('title')
+      || element?.getAttribute?.('aria-label')
+      || ''
+    );
+    return /登录|登入|sign in|log in/i.test(text);
+  });
+  const mailboxList = document.querySelector('#mailboxlist');
+  const messageList = document.querySelector('#messagelist');
+  const hasMailUi = mailboxList || messageList || getRcmailEnv()?.task === 'mail';
+
+  if ((passwordInput || loginForm || loginButton) && !hasMailUi) {
+    return true;
+  }
+
+  const pageText = normalizeText(document.body?.innerText || document.body?.textContent || '');
+  return /(企业邮箱登录|请输入密码|登录邮箱|sign in)/i.test(pageText) && !hasMailUi;
+}
+
+async function waitUntilLoggedIn(step) {
+  let loggedWaitMessage = false;
+  while (isLoginPageLikely()) {
+    throwIfStopped();
+    if (!loggedWaitMessage && !waitingLoginLogged) {
+      waitingLoginLogged = true;
+      loggedWaitMessage = true;
+      log(`步骤 ${step}:检测到 mail.phplife.net 未登录,正在等待你手动登录...`, 'warn');
+    }
+    await sleep(1000);
+  }
+
+  if (loggedWaitMessage || waitingLoginLogged) {
+    log(`步骤 ${step}:已检测到 mail.phplife.net 登录完成,继续读取验证码...`, 'ok');
+  }
+  waitingLoginLogged = false;
+}
+
+function normalizeMinuteTimestamp(timestamp) {
+  if (!Number.isFinite(timestamp) || timestamp <= 0) return 0;
+  const date = new Date(timestamp);
+  date.setSeconds(0, 0);
+  return date.getTime();
+}
+
+function parseRoundcubeTimestamp(rawText) {
+  const text = normalizeText(rawText);
+  if (!text) return null;
+
+  let match = text.match(/今天\s*(\d{1,2}):(\d{2})/);
+  if (match) {
+    const now = new Date();
+    return new Date(now.getFullYear(), now.getMonth(), now.getDate(), Number(match[1]), Number(match[2]), 0, 0).getTime();
+  }
+
+  match = text.match(/昨天\s*(\d{1,2}):(\d{2})/);
+  if (match) {
+    const now = new Date();
+    now.setDate(now.getDate() - 1);
+    return new Date(now.getFullYear(), now.getMonth(), now.getDate(), Number(match[1]), Number(match[2]), 0, 0).getTime();
+  }
+
+  match = text.match(/(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})日?\s*(\d{1,2}):(\d{2})/);
+  if (match) {
+    return new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]), Number(match[4]), Number(match[5]), 0, 0).getTime();
+  }
+
+  match = text.match(/(\d{1,2})[-/](\d{1,2})\s*(\d{1,2}):(\d{2})/);
+  if (match) {
+    const now = new Date();
+    return new Date(now.getFullYear(), Number(match[1]) - 1, Number(match[2]), Number(match[3]), Number(match[4]), 0, 0).getTime();
+  }
+
+  match = text.match(/^(\d{1,2}):(\d{2})$/);
+  if (match) {
+    const now = new Date();
+    return new Date(now.getFullYear(), now.getMonth(), now.getDate(), Number(match[1]), Number(match[2]), 0, 0).getTime();
+  }
+
+  const parsed = Date.parse(text);
+  return Number.isFinite(parsed) ? parsed : null;
+}
+
+function extractVerificationCodes(text) {
+  const source = String(text || '');
+  const codes = [];
+  const patterns = [
+    /(?:验证码|代码)[^0-9]{0,24}(\d{6})/ig,
+    /(?:chatgpt\s+log-?in\s+code|your\s+chatgpt\s+code\s+is|verification\s+code|temporary\s+verification\s+code|enter\s+this\s+code)[^0-9]{0,24}(\d{6})/ig,
+    /\b(\d{6})\b/g,
+  ];
+
+  for (const pattern of patterns) {
+    let match = null;
+    while ((match = pattern.exec(source))) {
+      if (match[1] && !codes.includes(match[1])) {
+        codes.push(match[1]);
+      }
+    }
+    if (codes.length) {
+      return codes;
+    }
+  }
+
+  return codes;
+}
+
+function extractEmails(text) {
+  const matches = String(text || '').match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/ig) || [];
+  return [...new Set(matches.map((item) => item.toLowerCase()))];
+}
+
+function getTargetEmailMatchState(text, targetEmail) {
+  const normalizedTarget = String(targetEmail || '').trim().toLowerCase();
+  if (!normalizedTarget) {
+    return { matches: true, hasExplicitEmail: false };
+  }
+
+  const normalizedText = String(text || '').toLowerCase();
+  if (normalizedText.includes(normalizedTarget)) {
+    return { matches: true, hasExplicitEmail: true };
+  }
+
+  const emails = extractEmails(text);
+  if (!emails.length) {
+    return { matches: false, hasExplicitEmail: false };
+  }
+
+  return {
+    matches: emails.includes(normalizedTarget),
+    hasExplicitEmail: true,
+  };
+}
+
+function matchesMailFilters(text, senderFilters = [], subjectFilters = []) {
+  const normalizedText = String(text || '').toLowerCase();
+  const senderMatched = senderFilters.some((filter) => normalizedText.includes(String(filter || '').toLowerCase()));
+  const subjectMatched = subjectFilters.some((filter) => normalizedText.includes(String(filter || '').toLowerCase()));
+  return senderMatched || subjectMatched;
+}
+
+function getPreviewDocument() {
+  const frame = document.getElementById('messagecontframe');
+  if (!frame) return null;
+  try {
+    return frame.contentDocument || frame.contentWindow?.document || null;
+  } catch {
+    return null;
+  }
+}
+
+function getMessageDocument() {
+  if (document.querySelector('#messagebody, #messageheader, .headers-table')) {
+    return document;
+  }
+
+  const previewDocument = getPreviewDocument();
+  if (previewDocument?.querySelector?.('#messagebody, #messageheader, .headers-table')) {
+    return previewDocument;
+  }
+
+  return null;
+}
+
+function getMessageDetailsFromDocument(doc = null) {
+  const sourceDocument = doc || getMessageDocument();
+  if (!sourceDocument) return null;
+
+  const subject = normalizeText(sourceDocument.querySelector('h2.subject')?.textContent || '');
+  const from = normalizeText(sourceDocument.querySelector('.headers-table .header.from')?.textContent || '');
+  const to = normalizeText(sourceDocument.querySelector('.headers-table .header.to')?.textContent || '');
+  const dateText = normalizeText(sourceDocument.querySelector('.headers-table .header.date')?.textContent || '');
+  const bodyText = normalizeText(
+    sourceDocument.querySelector('#messagebody')?.innerText
+    || sourceDocument.querySelector('#messagebody')?.textContent
+    || sourceDocument.body?.innerText
+    || sourceDocument.body?.textContent
+    || ''
+  );
+  const combinedText = normalizeText([subject, from, to, dateText, bodyText].join(' '));
+  const codes = extractVerificationCodes(combinedText);
+
+  return {
+    subject,
+    from,
+    to,
+    dateText,
+    emailTimestamp: parseRoundcubeTimestamp(dateText),
+    bodyText,
+    combinedText,
+    codes,
+  };
+}
+
+function getMessageListRows() {
+  return Array.from(document.querySelectorAll('#messagelist tbody tr')).filter(isVisibleElement);
+}
+
+function getRowText(row, selector) {
+  const node = row?.querySelector(selector);
+  return normalizeText(
+    node?.getAttribute?.('title')
+    || node?.getAttribute?.('aria-label')
+    || node?.textContent
+    || ''
+  );
+}
+
+function getRowDetails(row) {
+  const subject = getRowText(row, 'td.subject');
+  const from = getRowText(row, 'td.fromto');
+  const to = getRowText(row, 'td.to');
+  const dateText = getRowText(row, 'td.date');
+  const combinedText = normalizeText([subject, from, to, dateText, row?.textContent || ''].join(' '));
+  return {
+    row,
+    subject,
+    from,
+    to,
+    dateText,
+    emailTimestamp: parseRoundcubeTimestamp(dateText),
+    codes: extractVerificationCodes(combinedText),
+    combinedText,
+  };
+}
+
+function scoreRowCandidate(details, payload = {}) {
+  const { senderFilters = [], subjectFilters = [], targetEmail = '' } = payload;
+  let score = 0;
+  const combinedText = details?.combinedText || '';
+
+  if (matchesMailFilters(combinedText, senderFilters, subjectFilters)) score += 4;
+  if (/openai|chatgpt|verification|verify|验证码/i.test(combinedText)) score += 3;
+  const targetMatch = getTargetEmailMatchState(combinedText, targetEmail);
+  if (targetMatch.matches) score += targetMatch.hasExplicitEmail ? 4 : 1;
+  if (details?.emailTimestamp) score += 1;
+
+  return score;
+}
+
+function getCurrentMessageUid() {
+  const envUid = getRcmailEnv()?.uid;
+  if (envUid) return String(envUid);
+
+  const doc = getMessageDocument();
+  const permaLink = doc?.querySelector?.('a[href*="_uid="]')?.getAttribute?.('href') || location.href;
+  const match = String(permaLink || '').match(/[?&]_uid=(\d+)/);
+  return match ? match[1] : '';
+}
+
+async function waitForPreviewLoaded(previousUid = '', timeoutMs = 15000) {
+  const start = Date.now();
+  while (Date.now() - start < timeoutMs) {
+    throwIfStopped();
+    const doc = getMessageDocument();
+    const details = getMessageDetailsFromDocument(doc);
+    const currentUid = getCurrentMessageUid();
+    if (details?.combinedText && (!previousUid || !currentUid || currentUid !== previousUid)) {
+      return details;
+    }
+    await sleep(250);
+  }
+
+  return getMessageDetailsFromDocument();
+}
+
+function openMessageRow(row) {
+  if (!row) {
+    return;
+  }
+
+  if (typeof row.click === 'function') {
+    row.click();
+    return;
+  }
+
+  row.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
+}
+
+function findRefreshButton() {
+  const selectors = [
+    '#rcmbtn105',
+    'a.button.checkmail',
+    'a[title*="检查新邮件"]',
+    'a[title*="刷新"]',
+  ];
+
+  for (const selector of selectors) {
+    const node = document.querySelector(selector);
+    if (node) return node;
+  }
+
+  return Array.from(document.querySelectorAll('a, button')).find((element) => /刷新|检查新邮件|check mail/i.test(normalizeText(element.textContent || element.getAttribute('title') || ''))) || null;
+}
+
+function findInboxLink() {
+  return document.querySelector('#mailboxlist .mailbox.inbox a[rel="INBOX"], #mailboxlist a[rel="INBOX"]');
+}
+
+async function ensureInboxActive() {
+  const inboxLink = findInboxLink();
+  if (!inboxLink) return;
+  const inboxItem = inboxLink.closest('.mailbox');
+  if (inboxItem?.classList?.contains('selected')) {
+    return;
+  }
+  inboxLink.click();
+  await sleep(800);
+}
+
+async function refreshMessageList() {
+  const refreshButton = findRefreshButton();
+  if (!refreshButton) return false;
+  refreshButton.click();
+  await sleep(1200);
+  return true;
+}
+
+function selectCandidateCode(codes = [], excludedCodeSet = new Set()) {
+  for (const code of codes) {
+    if (!excludedCodeSet.has(code) && !seenCodes.has(code)) {
+      return code;
+    }
+  }
+  return null;
+}
+
+function matchesCurrentMessage(details, payload = {}, excludedCodeSet = new Set(), filterAfterMinute = 0) {
+  if (!details?.combinedText) {
+    return { matched: false };
+  }
+
+  const targetMatch = getTargetEmailMatchState(details.combinedText, payload.targetEmail);
+  if (targetMatch.hasExplicitEmail && !targetMatch.matches) {
+    return { matched: false };
+  }
+
+  if (!matchesMailFilters(details.combinedText, payload.senderFilters, payload.subjectFilters)) {
+    return { matched: false };
+  }
+
+  const normalizedTimestamp = normalizeMinuteTimestamp(details.emailTimestamp || 0);
+  if (filterAfterMinute && normalizedTimestamp && normalizedTimestamp < filterAfterMinute) {
+    return { matched: false };
+  }
+
+  const code = selectCandidateCode(details.codes, excludedCodeSet);
+  if (!code) {
+    return { matched: false };
+  }
+
+  return {
+    matched: true,
+    code,
+    emailTimestamp: details.emailTimestamp || Date.now(),
+  };
+}
+
+async function tryReadCurrentMessage(payload, excludedCodeSet, filterAfterMinute) {
+  const details = getMessageDetailsFromDocument();
+  const result = matchesCurrentMessage(details, payload, excludedCodeSet, filterAfterMinute);
+  return result.matched ? result : null;
+}
+
+async function tryOpenRowsAndRead(step, payload, excludedCodeSet, filterAfterMinute) {
+  const rows = getMessageListRows()
+    .map((row) => getRowDetails(row))
+    .map((details) => ({ ...details, score: scoreRowCandidate(details, payload) }))
+    .filter((details) => details.score > 0)
+    .sort((left, right) => right.score - left.score);
+
+  for (const details of rows.slice(0, 8)) {
+    throwIfStopped();
+
+    const rowMinuteTimestamp = normalizeMinuteTimestamp(details.emailTimestamp || 0);
+    if (filterAfterMinute && rowMinuteTimestamp && rowMinuteTimestamp < filterAfterMinute) {
+      continue;
+    }
+
+    const directResult = matchesCurrentMessage(details, payload, excludedCodeSet, filterAfterMinute);
+    if (directResult.matched) {
+      log(`步骤 ${step}:已直接从 mail.phplife.net 列表命中验证码邮件。`, 'ok');
+      return directResult;
+    }
+  }
+
+  return null;
+}
+
+async function handlePollEmail(step, payload) {
+  const {
+    maxAttempts = 5,
+    intervalMs = 3000,
+    excludeCodes = [],
+    filterAfterTimestamp = 0,
+  } = payload || {};
+  const excludedCodeSet = new Set((excludeCodes || []).filter(Boolean));
+  const filterAfterMinute = normalizeMinuteTimestamp(Number(filterAfterTimestamp) || 0);
+
+  await waitUntilLoggedIn(step);
+  await ensureInboxActive();
+
+  log(`步骤 ${step}:开始轮询 A4Sky 邮箱(最多 ${maxAttempts} 次)`);
+  if (filterAfterMinute) {
+    log(`步骤 ${step}:仅尝试 ${new Date(filterAfterMinute).toLocaleString('zh-CN', { hour12: false })} 及之后时间的邮件。`);
+  }
+
+  let lastError = null;
+  for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
+    throwIfStopped();
+    await waitUntilLoggedIn(step);
+    log(`步骤 ${step}:正在检查 mail.phplife.net 邮件(${attempt}/${maxAttempts})...`);
+
+    await refreshMessageList();
+
+    const currentMessageResult = await tryReadCurrentMessage(payload, excludedCodeSet, filterAfterMinute);
+    if (currentMessageResult?.matched) {
+      seenCodes.add(currentMessageResult.code);
+      await persistSeenCodes();
+      return {
+        code: currentMessageResult.code,
+        emailTimestamp: currentMessageResult.emailTimestamp,
+      };
+    }
+
+    const openedRowResult = await tryOpenRowsAndRead(step, payload, excludedCodeSet, filterAfterMinute);
+    if (openedRowResult?.matched) {
+      seenCodes.add(openedRowResult.code);
+      await persistSeenCodes();
+      return {
+        code: openedRowResult.code,
+        emailTimestamp: openedRowResult.emailTimestamp,
+      };
+    }
+
+    lastError = new Error(`步骤 ${step}:暂未在 A4Sky 邮箱中找到新的匹配验证码(${attempt}/${maxAttempts})。`);
+    if (attempt < maxAttempts) {
+      await sleep(intervalMs);
+    }
+  }
+
+  throw lastError || new Error(`步骤 ${step}:未在 A4Sky 邮箱中找到新的匹配验证码。`);
+}
+
+}

+ 1 - 0
sidepanel/sidepanel.html

@@ -160,6 +160,7 @@
             <option value="custom">自定义邮箱</option>
             <option value="hotmail-api">Hotmail(账号池)</option>
             <option value="luckmail-api">LuckMail(API 购邮)</option>
+            <option value="a4sky">A4Sky 邮箱 (mail.phplife.net)</option>
             <option value="icloud">iCloud 邮箱</option>
             <option value="163">163 邮箱 (mail.163.com)</option>
             <option value="163-vip">163 VIP 邮箱 (vip.163.com)</option>

+ 29 - 5
sidepanel/sidepanel.js

@@ -217,6 +217,7 @@ const HOTMAIL_SERVICE_MODE_REMOTE = 'remote';
 const HOTMAIL_SERVICE_MODE_LOCAL = 'local';
 const ICLOUD_PROVIDER = 'icloud';
 const GMAIL_PROVIDER = 'gmail';
+const A4SKY_PROVIDER = 'a4sky';
 const LUCKMAIL_PROVIDER = 'luckmail-api';
 const DEFAULT_LUCKMAIL_BASE_URL = 'https://mails.luckyous.com';
 const DEFAULT_LUCKMAIL_EMAIL_TYPE = 'ms_graph';
@@ -333,6 +334,14 @@ function setManagedAliasBaseEmailInputForProvider(provider = selectMailProvider.
 }
 
 function getCurrentRegistrationEmailUiCopy() {
+  if (isA4skyProvider()) {
+    return {
+      buttonLabel: '生成',
+      placeholder: '点击生成 A4Sky 邮箱,或手动粘贴邮箱',
+      successVerb: '生成',
+      label: 'A4Sky 邮箱',
+    };
+  }
   if (isCustomMailProvider()) {
     return getCustomMailProviderUiCopy();
   }
@@ -430,6 +439,11 @@ const MAIL_PROVIDER_LOGIN_CONFIGS = {
     url: 'https://mail.google.com/mail/u/0/#inbox',
     buttonLabel: '登录',
   },
+  [A4SKY_PROVIDER]: {
+    label: 'A4Sky 邮箱',
+    url: 'https://mail.phplife.net/?_task=mail&_mbox=INBOX',
+    buttonLabel: '登录',
+  },
   '163': {
     label: '163 邮箱',
     url: 'https://mail.163.com/',
@@ -1683,7 +1697,7 @@ function applySettingsState(state) {
   inputSub2ApiGroup.value = state?.sub2apiGroupName || '';
   inputSub2ApiDefaultProxy.value = state?.sub2apiDefaultProxyName || DEFAULT_SUB2API_PROXY_NAME;
   const restoredMailProvider = isCustomMailProvider(state?.mailProvider)
-    || [ICLOUD_PROVIDER, 'hotmail-api', GMAIL_PROVIDER, 'luckmail-api', '163', '163-vip', 'qq', 'inbucket', '2925', 'cloudflare-temp-email'].includes(String(state?.mailProvider || '').trim())
+    || [ICLOUD_PROVIDER, 'hotmail-api', GMAIL_PROVIDER, A4SKY_PROVIDER, 'luckmail-api', '163', '163-vip', 'qq', 'inbucket', '2925', 'cloudflare-temp-email'].includes(String(state?.mailProvider || '').trim())
     ? String(state?.mailProvider || '163').trim()
     : (String(state?.emailGenerator || '').trim().toLowerCase() === 'custom'
       || String(state?.emailGenerator || '').trim().toLowerCase() === 'manual'
@@ -2020,6 +2034,10 @@ function isLuckmailProvider(provider = selectMailProvider.value) {
   return String(provider || '').trim().toLowerCase() === LUCKMAIL_PROVIDER;
 }
 
+function isA4skyProvider(provider = selectMailProvider.value) {
+  return String(provider || '').trim().toLowerCase() === A4SKY_PROVIDER;
+}
+
 function isIcloudMailProvider(provider = selectMailProvider.value) {
   return String(provider || '').trim().toLowerCase() === ICLOUD_PROVIDER;
 }
@@ -2274,6 +2292,7 @@ function updateMailLoginButtonState() {
 function updateMailProviderUI() {
   const use2925 = selectMailProvider.value === '2925';
   const useGmail = selectMailProvider.value === GMAIL_PROVIDER;
+  const useA4sky = isA4skyProvider();
   const mail2925Mode = getSelectedMail2925Mode();
   const useGeneratedAlias = usesGeneratedAliasMailProvider(selectMailProvider.value, mail2925Mode);
   const useInbucket = selectMailProvider.value === 'inbucket';
@@ -2281,7 +2300,7 @@ function updateMailProviderUI() {
   const useLuckmail = isLuckmailProvider();
   const useCustomEmail = isCustomMailProvider();
   const useIcloudProvider = isIcloudMailProvider();
-  const useEmailGenerator = !useHotmail && !useLuckmail && !useGeneratedAlias && !useCustomEmail;
+  const useEmailGenerator = !useHotmail && !useLuckmail && !useGeneratedAlias && !useCustomEmail && !useA4sky;
   const useCloudflareTempEmailProvider = selectMailProvider.value === 'cloudflare-temp-email';
   const aliasUiCopy = useGeneratedAlias ? getManagedAliasProviderUiCopy(selectMailProvider.value) : null;
   const uiCopy = getCurrentRegistrationEmailUiCopy();
@@ -2341,7 +2360,7 @@ function updateMailProviderUI() {
   }
   labelEmailPrefix.textContent = '邮箱前缀';
   inputEmailPrefix.placeholder = '例如 abc';
-  selectEmailGenerator.disabled = useHotmail || useLuckmail || useGeneratedAlias || useCustomEmail;
+  selectEmailGenerator.disabled = useHotmail || useLuckmail || useGeneratedAlias || useCustomEmail || useA4sky;
   if (useGmail) {
     labelEmailPrefix.textContent = 'Gmail 原邮箱';
     inputEmailPrefix.placeholder = '例如 yourname@gmail.com';
@@ -2379,9 +2398,11 @@ function updateMailProviderUI() {
       ? '请先校验并选择一个 Hotmail 账号'
       : (useLuckmail
         ? '步骤 3 会自动购买 LuckMail 邮箱并用于收码'
+        : (useA4sky
+          ? '点击“生成”得到 n{Ymdhis}@a4sky.com;步骤 4/8 会打开 mail.phplife.net,若未登录则等待你登录后自动取码'
       : (useGeneratedAlias
         ? '步骤 3 会自动生成邮箱,无需手动获取'
-        : (useCustomEmail ? '请先填写自定义注册邮箱,成功一轮后会自动清空' : `先自动获取${uiCopy.label},或手动粘贴邮箱后再继续`)));
+        : (useCustomEmail ? '请先填写自定义注册邮箱,成功一轮后会自动清空' : `先自动获取${uiCopy.label},或手动粘贴邮箱后再继续`))));
   }
   if (autoHintText && useGmail && useGeneratedAlias) {
     autoHintText.textContent = '请先填写 Gmail 原邮箱,步骤 3 会自动生成 Gmail +tag 地址';
@@ -3539,12 +3560,15 @@ selectMailProvider.addEventListener('change', async () => {
   const leavingLuckmail = previousProvider === LUCKMAIL_PROVIDER
     && nextProvider !== LUCKMAIL_PROVIDER
     && isCurrentEmailManagedByLuckmail();
+  const leavingA4sky = previousProvider === A4SKY_PROVIDER
+    && nextProvider !== A4SKY_PROVIDER
+    && /^n\d{14}@a4sky\.com$/i.test(String(inputEmail.value || latestState?.email || '').trim());
   const leavingGeneratedAlias = (
     previousProvider !== nextProvider
     || (previousProvider === '2925' && normalizeMail2925Mode(previousMail2925Mode) !== getSelectedMail2925Mode())
   ) && usesGeneratedAliasMailProvider(previousProvider, previousMail2925Mode)
     && isCurrentEmailManagedByGeneratedAlias(previousProvider, latestState, previousMail2925Mode);
-  if (leavingHotmail || leavingLuckmail || leavingGeneratedAlias) {
+  if (leavingHotmail || leavingLuckmail || leavingA4sky || leavingGeneratedAlias) {
     await clearRegistrationEmail({ silent: true }).catch(() => { });
   }
   if (nextProvider === LUCKMAIL_PROVIDER) {

+ 22 - 0
tests/background-generated-email-module.test.js

@@ -15,3 +15,25 @@ test('generated email helper module exposes a factory', () => {
 
   assert.equal(typeof api?.createGeneratedEmailHelpers, 'function');
 });
+
+test('generated email helper supports a4sky mailbox format', async () => {
+  const source = fs.readFileSync('background/generated-email-helpers.js', 'utf8');
+  const globalScope = {};
+  const api = new Function('self', `${source}; return self.MultiPageGeneratedEmailHelpers;`)(globalScope);
+
+  let savedEmail = null;
+  const helpers = api.createGeneratedEmailHelpers({
+    addLog: async () => {},
+    getState: async () => ({ mailProvider: 'a4sky' }),
+    normalizeEmailGenerator: () => 'duck',
+    setEmailState: async (email) => {
+      savedEmail = email;
+    },
+    throwIfStopped: () => {},
+  });
+
+  const email = await helpers.fetchGeneratedEmail({ mailProvider: 'a4sky' });
+
+  assert.match(email, /^n\d{14}@a4sky\.com$/i);
+  assert.equal(savedEmail, email);
+});

+ 134 - 0
tests/phplife-mail-content.test.js

@@ -0,0 +1,134 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+
+const source = fs.readFileSync('content/phplife-mail.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('phplife mail parser extracts code and recipient from roundcube message view', () => {
+  const bundle = [
+    extractFunction('normalizeText'),
+    extractFunction('parseRoundcubeTimestamp'),
+    extractFunction('extractVerificationCodes'),
+    extractFunction('getMessageDetailsFromDocument'),
+  ].join('\n');
+
+  const api = new Function(`${bundle}
+return { getMessageDetailsFromDocument, parseRoundcubeTimestamp, extractVerificationCodes };
+`)();
+
+  const selectors = {
+    'h2.subject': { textContent: 'Your ChatGPT code is 866785' },
+    '.headers-table .header.from': { textContent: 'noreply@tm.openai.com' },
+    '.headers-table .header.to': { textContent: 'n2026041807@a4sky.com' },
+    '.headers-table .header.date': { textContent: '今天 12:30' },
+    '#messagebody': {
+      innerText: 'Enter this temporary verification code to continue: 866785. ChatGPT Log-in Code 866785',
+      textContent: 'Enter this temporary verification code to continue: 866785. ChatGPT Log-in Code 866785',
+    },
+  };
+
+  const fakeDocument = {
+    querySelector(selector) {
+      return selectors[selector] || null;
+    },
+    body: {
+      innerText: '',
+      textContent: '',
+    },
+  };
+
+  const details = api.getMessageDetailsFromDocument(fakeDocument);
+
+  assert.equal(details.subject, 'Your ChatGPT code is 866785');
+  assert.equal(details.from, 'noreply@tm.openai.com');
+  assert.equal(details.to, 'n2026041807@a4sky.com');
+  assert.equal(details.codes[0], '866785');
+  assert.equal(Number.isFinite(details.emailTimestamp), true);
+});
+
+test('phplife mail parser can read verification code directly from list row title', () => {
+  const bundle = [
+    extractFunction('normalizeText'),
+    extractFunction('parseRoundcubeTimestamp'),
+    extractFunction('extractVerificationCodes'),
+    extractFunction('getRowText'),
+    extractFunction('getRowDetails'),
+  ].join('\n');
+
+  const api = new Function(`${bundle}
+return { getRowDetails };
+`)();
+
+  const subjectNode = {
+    getAttribute(name) {
+      return name === 'title' ? 'Your ChatGPT code is 866785' : '';
+    },
+    textContent: 'fallback subject',
+  };
+  const fromNode = { getAttribute() { return ''; }, textContent: 'noreply@tm.openai.com' };
+  const toNode = { getAttribute() { return ''; }, textContent: 'n2026041807@a4sky.com' };
+  const dateNode = { getAttribute() { return ''; }, textContent: '今天 12:30' };
+
+  const fakeRow = {
+    querySelector(selector) {
+      if (selector === 'td.subject') return subjectNode;
+      if (selector === 'td.fromto') return fromNode;
+      if (selector === 'td.to') return toNode;
+      if (selector === 'td.date') return dateNode;
+      return null;
+    },
+    textContent: 'Your ChatGPT code is 866785 noreply@tm.openai.com n2026041807@a4sky.com 今天 12:30',
+  };
+
+  const details = api.getRowDetails(fakeRow);
+
+  assert.equal(details.subject, 'Your ChatGPT code is 866785');
+  assert.equal(details.codes[0], '866785');
+});

+ 12 - 0
tests/sidepanel-mail-provider-restore.test.js

@@ -0,0 +1,12 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+
+const source = fs.readFileSync('sidepanel/sidepanel.js', 'utf8');
+
+test('applySettingsState restore whitelist includes a4sky provider', () => {
+  assert.match(
+    source,
+    /\[ICLOUD_PROVIDER, 'hotmail-api', GMAIL_PROVIDER, A4SKY_PROVIDER, 'luckmail-api', '163', '163-vip', 'qq', 'inbucket', '2925', 'cloudflare-temp-email'\]/
+  );
+});