Просмотр исходного кода

Merge remote-tracking branch 'origin/dev'

QLHazyCoder 4 месяцев назад
Родитель
Сommit
71ee5dc03e
7 измененных файлов с 1272 добавлено и 15 удалено
  1. 60 3
      background.js
  2. 437 0
      content/mail-2925.js
  3. 2 1
      content/utils.js
  4. 170 2
      sidepanel/sidepanel.css
  5. 27 1
      sidepanel/sidepanel.html
  6. 288 8
      sidepanel/sidepanel.js
  7. 288 0
      sidepanel/update-service.js

+ 60 - 3
background.js

@@ -83,6 +83,7 @@ const LEGACY_PERSISTED_SETTING_DEFAULTS = {
   cloudflareDomain: '', // 仅当 emailGenerator=cloudflare 时填写自定义域名。
   cloudflareDomains: [], // Cloudflare 可选域名列表。
   hotmailAccounts: [],
+  emailPrefix: '',
 };
 
 const PERSISTED_SETTING_DEFAULTS = {
@@ -250,6 +251,7 @@ function normalizeMailProvider(value = '') {
     case '163-vip':
     case 'qq':
     case 'inbucket':
+    case '2925':
       return normalized;
     default:
       return PERSISTED_SETTING_DEFAULTS.mailProvider;
@@ -319,6 +321,8 @@ function normalizePersistentSettingValue(key, value) {
       return normalizeMailProvider(value);
     case 'emailGenerator':
       return normalizeEmailGenerator(value);
+    case 'emailPrefix':
+      return String(value || '').trim();
     case 'inbucketHost':
       return String(value || '').trim();
     case 'inbucketMailbox':
@@ -462,10 +466,8 @@ async function importSettingsBundle(configBundle) {
   const sessionUpdates = {
     ...importedSettings,
     currentHotmailAccountId: null,
+    email: null,
   };
-  if (importedSettings.mailProvider === HOTMAIL_PROVIDER) {
-    sessionUpdates.email = null;
-  }
 
   await setState(sessionUpdates);
   broadcastDataUpdate({
@@ -1163,6 +1165,34 @@ async function pollHotmailVerificationCode(step, state, pollPayload = {}) {
   throw lastError || new Error(`步骤 ${step}:未在 Hotmail 收件箱中找到新的匹配验证码。`);
 }
 
+function generateRandomSuffix(length = 6) {
+  const chars = 'abcdefghjkmnpqrstuvwxyz23456789';
+  let suffix = '';
+  for (let i = 0; i < length; i++) {
+    suffix += chars[Math.floor(Math.random() * chars.length)];
+  }
+  return suffix;
+}
+
+function isGeneratedAliasProvider(provider) {
+  return provider === '2925';
+}
+
+function buildGeneratedAliasEmail(state) {
+  const provider = state.mailProvider || '163';
+  const emailPrefix = (state.emailPrefix || '').trim();
+
+  if (!emailPrefix) {
+    throw new Error('2925 邮箱前缀未设置,请先在侧边栏填写。');
+  }
+
+  if (provider === '2925') {
+    return `${emailPrefix}${generateRandomSuffix(6)}@2925.com`;
+  }
+
+  throw new Error(`未支持的别名邮箱类型:${provider}`);
+}
+
 // ============================================================
 // Tab Registry
 // ============================================================
@@ -1282,6 +1312,8 @@ function matchesSourceUrlFamily(source, candidateUrl, referenceUrl) {
       return Boolean(reference)
         && candidate.origin === reference.origin
         && candidate.pathname.startsWith('/m/');
+    case 'mail-2925':
+      return candidate.hostname === '2925.com' || candidate.hostname === 'www.2925.com';
     case 'vps-panel':
       return Boolean(reference)
         && candidate.origin === reference.origin
@@ -1979,6 +2011,7 @@ function getSourceLabel(source) {
     'sub2api-panel': 'SUB2API 后台',
     'qq-mail': 'QQ 邮箱',
     'mail-163': '163 邮箱',
+    'mail-2925': '2925 邮箱',
     'inbucket-mail': 'Inbucket 邮箱',
     'duck-mail': 'Duck 邮箱',
     'hotmail-api': 'Hotmail(微软 Graph)',
@@ -2688,6 +2721,10 @@ async function handleMessage(message, sender) {
       if (message.payload.email) {
         await setEmailState(message.payload.email);
       }
+      if (message.payload.emailPrefix !== undefined) {
+        await setPersistentSettings({ emailPrefix: message.payload.emailPrefix });
+        await setState({ emailPrefix: message.payload.emailPrefix });
+      }
       await executeStep(step);
       return { ok: true };
     }
@@ -3306,6 +3343,14 @@ async function ensureAutoEmailReady(targetRun, totalRuns, attemptRuns) {
     return account.email;
   }
 
+  if (isGeneratedAliasProvider(currentState.mailProvider)) {
+    if (!currentState.emailPrefix) {
+      throw new Error('2925 邮箱前缀未设置,请先在侧边栏填写。');
+    }
+    await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:2925 模式已启用,将在步骤 3 自动生成邮箱(第 ${attemptRuns} 次尝试)===`, 'info');
+    return null;
+  }
+
   if (currentState.email) {
     return currentState.email;
   }
@@ -3496,6 +3541,7 @@ async function autoRunLoop(totalRuns, options = {}) {
         autoStepDelaySeconds: prevState.autoStepDelaySeconds,
         mailProvider: prevState.mailProvider,
         emailGenerator: prevState.emailGenerator,
+        emailPrefix: prevState.emailPrefix,
         inbucketHost: prevState.inbucketHost,
         inbucketMailbox: prevState.inbucketMailbox,
         cloudflareDomain: prevState.cloudflareDomain,
@@ -3831,6 +3877,8 @@ async function executeStep3(state) {
       preferredAccountId: state.currentHotmailAccountId || null,
     });
     resolvedEmail = account.email;
+  } else if (isGeneratedAliasProvider(state.mailProvider)) {
+    resolvedEmail = buildGeneratedAliasEmail(state);
   }
 
   if (!resolvedEmail) {
@@ -3892,6 +3940,15 @@ function getMailConfig(state) {
       injectSource: 'inbucket-mail',
     };
   }
+  if (provider === '2925') {
+    return {
+      source: 'mail-2925',
+      url: 'https://2925.com/#/mailList',
+      label: '2925 邮箱',
+      inject: ['content/utils.js', 'content/mail-2925.js'],
+      injectSource: 'mail-2925',
+    };
+  }
   return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ 邮箱' };
 }
 

+ 437 - 0
content/mail-2925.js

@@ -0,0 +1,437 @@
+// content/mail-2925.js — Content script for 2925 Mail (steps 4, 7)
+// Injected dynamically on: 2925.com
+
+const MAIL2925_PREFIX = '[MultiPage:mail-2925]';
+const isTopFrame = window === window.top;
+
+console.log(MAIL2925_PREFIX, 'Content script loaded on', location.href, 'frame:', isTopFrame ? 'top' : 'child');
+
+if (!isTopFrame) {
+  console.log(MAIL2925_PREFIX, 'Skipping child frame');
+} else {
+
+let seenCodes = new Set();
+
+async function loadSeenCodes() {
+  try {
+    const data = await chrome.storage.session.get('seen2925Codes');
+    if (data.seen2925Codes && Array.isArray(data.seen2925Codes)) {
+      seenCodes = new Set(data.seen2925Codes);
+      console.log(MAIL2925_PREFIX, `Loaded ${seenCodes.size} previously seen codes`);
+    }
+  } catch (err) {
+    console.warn(MAIL2925_PREFIX, 'Session storage unavailable, using in-memory seen codes:', err?.message || err);
+  }
+}
+
+loadSeenCodes();
+
+async function persistSeenCodes() {
+  try {
+    await chrome.storage.session.set({ seen2925Codes: [...seenCodes] });
+  } catch (err) {
+    console.warn(MAIL2925_PREFIX, 'Could not persist seen codes, continuing in-memory only:', 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}:邮箱轮询失败:${err.message}`, 'warn');
+      sendResponse({ error: err.message });
+    });
+    return true;
+  }
+});
+
+const MAIL_ITEM_SELECTORS = [
+  '.mail-item',
+  '.letter-item',
+  '[class*="mailItem"]',
+  '[class*="mail-item"]',
+  '[class*="MailItem"]',
+  '.el-table__row',
+  'tr[class*="mail"]',
+  '[class*="listItem"]',
+  '[class*="list-item"]',
+  'li[class*="mail"]',
+];
+
+function findMailItems() {
+  for (const selector of MAIL_ITEM_SELECTORS) {
+    const items = document.querySelectorAll(selector);
+    if (items.length > 0) {
+      return Array.from(items);
+    }
+  }
+  return [];
+}
+
+function getMailItemText(item) {
+  if (!item) return '';
+  const contentCell = item.querySelector('td.content, .content, .mail-content');
+  const titleEl = item.querySelector('.mail-content-title');
+  const textEl = item.querySelector('.mail-content-text');
+  return [
+    titleEl?.getAttribute('title') || '',
+    titleEl?.textContent || '',
+    textEl?.textContent || '',
+    contentCell?.textContent || '',
+    item.textContent || '',
+  ].join(' ');
+}
+
+function getMailItemTimeText(item) {
+  const timeEl = item?.querySelector('.date-time-text, [class*="date-time"], [class*="time"], td.time');
+  return (timeEl?.textContent || '').replace(/\s+/g, ' ').trim();
+}
+
+function normalizeMailIdentityPart(value) {
+  return (value || '').replace(/\s+/g, ' ').trim().toLowerCase();
+}
+
+function getMailItemId(item, index = 0) {
+  const candidates = [
+    item?.getAttribute?.('data-id'),
+    item?.dataset?.id,
+    item?.getAttribute?.('data-mail-id'),
+    item?.dataset?.mailId,
+    item?.getAttribute?.('data-key'),
+    item?.getAttribute?.('key'),
+  ].filter(Boolean);
+
+  if (candidates.length > 0) {
+    return String(candidates[0]);
+  }
+
+  return [
+    index,
+    normalizeMailIdentityPart(getMailItemTimeText(item)),
+    normalizeMailIdentityPart(getMailItemText(item)).slice(0, 240),
+  ].join('|');
+}
+
+function getCurrentMailIds(items = []) {
+  const ids = new Set();
+  items.forEach((item, index) => {
+    ids.add(getMailItemId(item, index));
+  });
+  return ids;
+}
+
+function normalizeMinuteTimestamp(timestamp) {
+  if (!Number.isFinite(timestamp) || timestamp <= 0) return 0;
+  const date = new Date(timestamp);
+  date.setSeconds(0, 0);
+  return date.getTime();
+}
+
+function matchesMailFilters(text, senderFilters, subjectFilters) {
+  const lower = (text || '').toLowerCase();
+  const senderMatch = senderFilters.some(filter => lower.includes(filter.toLowerCase()));
+  const subjectMatch = subjectFilters.some(filter => lower.includes(filter.toLowerCase()));
+  return senderMatch || subjectMatch;
+}
+
+function extractVerificationCode(text, strictChatGPTCodeOnly = false) {
+  if (strictChatGPTCodeOnly) {
+    const strictMatch = text.match(/your\s+chatgpt\s+code\s+is\s+(\d{6})/i);
+    return strictMatch ? strictMatch[1] : null;
+  }
+
+  const matchCn = text.match(/(?:代码为|验证码[^0-9]*?)[\s::]*(\d{6})/);
+  if (matchCn) return matchCn[1];
+
+  const matchChatGPT = text.match(/your\s+chatgpt\s+code\s+is\s+(\d{6})/i);
+  if (matchChatGPT) return matchChatGPT[1];
+
+  const matchEn = text.match(/code[:\s]+is[:\s]+(\d{6})|code[:\s]+(\d{6})/i);
+  if (matchEn) return matchEn[1] || matchEn[2];
+
+  const match6 = text.match(/\b(\d{6})\b/);
+  if (match6) return match6[1];
+
+  return null;
+}
+
+function extractEmails(text) {
+  const matches = text.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/ig) || [];
+  return [...new Set(matches.map(item => item.toLowerCase()))];
+}
+
+function emailMatchesTarget(candidate, targetEmail) {
+  const normalizedCandidate = String(candidate || '').trim().toLowerCase();
+  const normalizedTarget = String(targetEmail || '').trim().toLowerCase();
+  return Boolean(normalizedCandidate && normalizedTarget && normalizedCandidate === normalizedTarget);
+}
+
+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 atIndex = normalizedTarget.indexOf('@');
+  if (atIndex > 0) {
+    const encodedTarget = `${normalizedTarget.slice(0, atIndex)}=${normalizedTarget.slice(atIndex + 1)}`;
+    if (normalizedText.includes(encodedTarget)) {
+      return { matches: true, hasExplicitEmail: true };
+    }
+  }
+
+  const emails = extractEmails(text);
+  if (!emails.length) {
+    return { matches: false, hasExplicitEmail: false };
+  }
+
+  return {
+    matches: emails.some(email => emailMatchesTarget(email, normalizedTarget)),
+    hasExplicitEmail: true,
+  };
+}
+
+function parseMailItemTimestamp(item) {
+  const timeText = getMailItemTimeText(item);
+  if (!timeText) return null;
+
+  const now = new Date();
+  const date = new Date(now);
+  let match = null;
+
+  if (/刚刚/.test(timeText)) {
+    return now.getTime();
+  }
+
+  match = timeText.match(/(\d+)\s*分(?:钟)?前/);
+  if (match) {
+    return now.getTime() - Number(match[1]) * 60 * 1000;
+  }
+
+  match = timeText.match(/(\d+)\s*秒前/);
+  if (match) {
+    return now.getTime() - Number(match[1]) * 1000;
+  }
+
+  match = timeText.match(/^(\d{1,2}):(\d{2})$/);
+  if (match) {
+    date.setHours(Number(match[1]), Number(match[2]), 0, 0);
+    return date.getTime();
+  }
+
+  match = timeText.match(/今天\s*(\d{1,2}):(\d{2})/);
+  if (match) {
+    date.setHours(Number(match[1]), Number(match[2]), 0, 0);
+    return date.getTime();
+  }
+
+  match = timeText.match(/昨天\s*(\d{1,2}):(\d{2})/);
+  if (match) {
+    date.setDate(date.getDate() - 1);
+    date.setHours(Number(match[1]), Number(match[2]), 0, 0);
+    return date.getTime();
+  }
+
+  match = timeText.match(/(\d{1,2})-(\d{1,2})\s*(\d{1,2}):(\d{2})/);
+  if (match) {
+    date.setMonth(Number(match[1]) - 1, Number(match[2]));
+    date.setHours(Number(match[3]), Number(match[4]), 0, 0);
+    return date.getTime();
+  }
+
+  match = timeText.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();
+  }
+
+  return null;
+}
+
+async function sleepRandom(minMs, maxMs = minMs) {
+  const duration = Math.floor(Math.random() * (maxMs - minMs + 1)) + minMs;
+  await sleep(duration);
+}
+
+async function refreshInbox() {
+  const refreshBtn = document.querySelector(
+    '[class*="refresh"], [title*="刷新"], [aria-label*="刷新"], [class*="Refresh"]'
+  );
+  if (refreshBtn) {
+    simulateClick(refreshBtn);
+    await sleepRandom(700, 1200);
+    return;
+  }
+
+  const inboxLink = document.querySelector(
+    'a[href*="mailList"], [class*="inbox"], [class*="Inbox"], [title*="收件箱"]'
+  );
+  if (inboxLink) {
+    simulateClick(inboxLink);
+    await sleepRandom(700, 1200);
+  }
+}
+
+async function handlePollEmail(step, payload) {
+  const {
+    senderFilters,
+    subjectFilters,
+    maxAttempts,
+    intervalMs,
+    filterAfterTimestamp = 0,
+    excludeCodes = [],
+    strictChatGPTCodeOnly = false,
+    targetEmail = '',
+  } = payload;
+  const excludedCodeSet = new Set(excludeCodes.filter(Boolean));
+  const filterAfterMinute = normalizeMinuteTimestamp(Number(filterAfterTimestamp) || 0);
+
+  log(`步骤 ${step}:开始轮询 2925 邮箱(最多 ${maxAttempts} 次)`);
+  if (filterAfterMinute) {
+    log(`步骤 ${step}:仅尝试 ${new Date(filterAfterMinute).toLocaleString('zh-CN', { hour12: false })} 及之后时间的邮件。`);
+  }
+
+  let initialItems = [];
+  for (let i = 0; i < 20; i++) {
+    initialItems = findMailItems();
+    if (initialItems.length > 0) break;
+    await sleep(500);
+  }
+
+  if (initialItems.length === 0) {
+    await refreshInbox();
+    await sleep(2000);
+    initialItems = findMailItems();
+  }
+
+  if (initialItems.length === 0) {
+    throw new Error('2925 邮箱列表未加载完成,请确认当前已打开收件箱。');
+  }
+
+  const existingMailIds = getCurrentMailIds(initialItems);
+  log(`步骤 ${step}:邮件列表已加载,共 ${initialItems.length} 封邮件`);
+  log(`步骤 ${step}:已记录当前 ${existingMailIds.size} 封旧邮件快照`);
+
+  const FALLBACK_AFTER = 3;
+
+  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+    log(`步骤 ${step}:正在轮询 2925 邮箱,第 ${attempt}/${maxAttempts} 次`);
+
+    if (attempt > 1) {
+      await refreshInbox();
+      await sleepRandom(900, 1500);
+    }
+
+    const items = findMailItems();
+    if (items.length > 0) {
+      const useFallback = attempt > FALLBACK_AFTER;
+
+      for (let index = 0; index < items.length; index++) {
+        const item = items[index];
+        const itemId = getMailItemId(item, index);
+        const itemTimestamp = parseMailItemTimestamp(item);
+        const itemMinute = normalizeMinuteTimestamp(itemTimestamp || 0);
+        const passesTimeFilter = !filterAfterMinute || (itemMinute && itemMinute >= filterAfterMinute);
+        const shouldBypassOldSnapshot = Boolean(filterAfterMinute && passesTimeFilter && itemMinute > 0);
+
+        if (!passesTimeFilter) {
+          continue;
+        }
+
+        if (!useFallback && !shouldBypassOldSnapshot && existingMailIds.has(itemId)) {
+          continue;
+        }
+
+        const text = getMailItemText(item);
+        if (!matchesMailFilters(text, senderFilters, subjectFilters)) {
+          continue;
+        }
+
+        const previewEmails = extractEmails(text);
+        const previewTargetState = getTargetEmailMatchState(text, targetEmail);
+        const previewMatchesTarget = previewTargetState.matches;
+        if (targetEmail && previewEmails.length > 0 && !previewMatchesTarget) {
+          continue;
+        }
+
+        const code = extractVerificationCode(text, strictChatGPTCodeOnly);
+        if (code && previewMatchesTarget) {
+          if (excludedCodeSet.has(code)) {
+            log(`步骤 ${step}:跳过排除的验证码:${code}`, 'info');
+            continue;
+          }
+          if (seenCodes.has(code)) {
+            log(`步骤 ${step}:跳过已处理过的验证码:${code}`, 'info');
+            continue;
+          }
+          seenCodes.add(code);
+          persistSeenCodes();
+          const source = useFallback && existingMailIds.has(itemId) ? '回退匹配邮件' : '新邮件';
+          const timeLabel = itemTimestamp ? `,时间:${new Date(itemTimestamp).toLocaleString('zh-CN', { hour12: false })}` : '';
+          log(`步骤 ${step}:已找到验证码:${code}(来源:${source}${timeLabel})`, 'ok');
+          await sleep(1000);
+          return { ok: true, code, emailTimestamp: Date.now() };
+        }
+
+        simulateClick(item);
+        await sleepRandom(1200, 2200);
+        const openedText = document.body?.textContent || '';
+        const bodyCode = extractVerificationCode(openedText, strictChatGPTCodeOnly);
+        const openedTargetState = getTargetEmailMatchState(openedText, targetEmail);
+        if (targetEmail && openedTargetState.hasExplicitEmail && !openedTargetState.matches) {
+          continue;
+        }
+        if (bodyCode) {
+          if (excludedCodeSet.has(bodyCode)) {
+            log(`步骤 ${step}:跳过排除的验证码:${bodyCode}`, 'info');
+            continue;
+          }
+          if (seenCodes.has(bodyCode)) {
+            log(`步骤 ${step}:跳过已处理过的验证码:${bodyCode}`, 'info');
+            continue;
+          }
+          seenCodes.add(bodyCode);
+          persistSeenCodes();
+          const source = useFallback && existingMailIds.has(itemId) ? '回退匹配邮件正文' : '新邮件正文';
+          const timeLabel = itemTimestamp ? `,时间:${new Date(itemTimestamp).toLocaleString('zh-CN', { hour12: false })}` : '';
+          log(`步骤 ${step}:已在邮件正文中找到验证码:${bodyCode}(来源:${source}${timeLabel})`, 'ok');
+          await sleep(1000);
+          return { ok: true, code: bodyCode, emailTimestamp: Date.now() };
+        }
+      }
+    }
+
+    if (attempt === FALLBACK_AFTER + 1) {
+      log(`步骤 ${step}:连续 ${FALLBACK_AFTER} 次未发现新邮件,开始回退到首封匹配邮件`, 'warn');
+    }
+
+    if (attempt < maxAttempts) {
+      await sleepRandom(intervalMs, intervalMs + 1200);
+    }
+  }
+
+  throw new Error(
+    `${(maxAttempts * intervalMs / 1000).toFixed(0)} 秒后仍未在 2925 邮箱中找到新的匹配邮件。请手动检查收件箱。`
+  );
+}
+
+}

+ 2 - 1
content/utils.js

@@ -11,6 +11,7 @@ const SCRIPT_SOURCE = (() => {
   if (hostname === 'mail.163.com' || hostname.endsWith('.mail.163.com') || hostname === 'webmail.vip.163.com') return 'mail-163';
   if (url.includes('duckduckgo.com/email/settings/autofill')) return 'duck-mail';
   if (url.includes('chatgpt.com')) return 'chatgpt';
+  if (url.includes("2925.com")) return "mail-2925";
   // VPS panel — detected dynamically since URL is configurable
   return 'vps-panel';
 })();
@@ -404,7 +405,7 @@ async function humanPause(min = 250, max = 850) {
 
 // Auto-report ready on load
 // Skip ready signal from child iframes of mail pages to avoid overwriting the top frame's registration
-const _isMailChildFrame = (SCRIPT_SOURCE === 'qq-mail' || SCRIPT_SOURCE === 'mail-163' || SCRIPT_SOURCE === 'inbucket-mail') && window !== window.top;
+const _isMailChildFrame = (SCRIPT_SOURCE === 'qq-mail' || SCRIPT_SOURCE === 'mail-163' || SCRIPT_SOURCE === 'mail-2925' || SCRIPT_SOURCE === 'inbucket-mail') && window !== window.top;
 if (!_isMailChildFrame) {
   reportReady();
 }

+ 170 - 2
sidepanel/sidepanel.css

@@ -102,21 +102,77 @@ header {
   display: flex;
   align-items: center;
   gap: 8px;
+  min-width: 0;
+  flex: 1;
 }
 
 .header-left svg { color: var(--blue); }
 
-.header-left h1 {
-  font-size: 16px;
+.header-version-block {
+  min-width: 0;
+  display: flex;
+  flex-direction: column;
+  gap: 2px;
+}
+
+.header-version-main {
+  min-width: 0;
+  display: flex;
+  align-items: baseline;
+  gap: 8px;
+}
+
+.header-version-title {
+  font-size: 15px;
   font-weight: 700;
   letter-spacing: -0.02em;
   color: var(--text-primary);
+  min-width: 0;
+  flex: 0 1 auto;
+  white-space: nowrap;
+  overflow: hidden;
+  text-overflow: ellipsis;
+}
+
+.header-version-title.is-version-label { color: var(--blue); }
+.header-version-title.is-update-available { color: var(--orange); }
+.header-version-title.is-check-failed { color: var(--text-primary); }
+
+.header-version-meta {
+  min-width: 0;
+  font-size: 12px;
+  color: var(--text-secondary);
+  white-space: nowrap;
+  overflow: hidden;
+  text-overflow: ellipsis;
+}
+
+.header-version-meta[hidden] {
+  display: none !important;
+}
+
+.header-link-btn {
+  padding: 0;
+  border: none;
+  background: transparent;
+  color: var(--blue);
+  font: inherit;
+  font-size: 12px;
+  font-weight: 600;
+  cursor: pointer;
+  flex-shrink: 0;
+}
+
+.header-link-btn:hover {
+  color: var(--text-primary);
+  text-decoration: underline;
 }
 
 .header-btns {
   display: flex;
   align-items: center;
   gap: 4px;
+  flex-shrink: 0;
 }
 
 /* ============================================================
@@ -282,6 +338,118 @@ header {
 .btn-sm { padding: 5px 12px; font-size: 12px; }
 .btn-xs { padding: 4px 10px; font-size: 11px; }
 
+/* ============================================================
+   Extension Updates
+   ============================================================ */
+
+#update-section { margin-bottom: 14px; }
+
+.update-card {
+  background: var(--bg-surface);
+  border: 1px solid var(--border);
+  border-radius: var(--radius-md);
+  padding: 12px 14px;
+  display: flex;
+  flex-direction: column;
+  gap: 12px;
+  box-shadow: var(--shadow-sm);
+}
+
+.update-card-header {
+  display: flex;
+  flex-wrap: wrap;
+  align-items: flex-start;
+  justify-content: space-between;
+  gap: 12px;
+}
+
+.update-card-copy {
+  min-width: 0;
+  display: flex;
+  flex-direction: column;
+  gap: 4px;
+}
+
+.update-card-version {
+  font-size: 14px;
+  font-weight: 700;
+  color: var(--orange);
+}
+
+.update-card-summary {
+  font-size: 12px;
+  color: var(--text-secondary);
+  line-height: 1.6;
+}
+
+.update-release-list {
+  display: flex;
+  flex-direction: column;
+  gap: 10px;
+}
+
+.update-release-item {
+  padding-top: 10px;
+  border-top: 1px solid var(--border-subtle);
+}
+
+.update-release-item:first-child {
+  padding-top: 0;
+  border-top: none;
+}
+
+.update-release-head {
+  display: flex;
+  justify-content: space-between;
+  align-items: baseline;
+  gap: 8px;
+  margin-bottom: 6px;
+}
+
+.update-release-title-row {
+  display: flex;
+  align-items: baseline;
+  gap: 8px;
+  min-width: 0;
+}
+
+.update-release-version {
+  font-size: 13px;
+  font-weight: 700;
+  color: var(--text-primary);
+}
+
+.update-release-name {
+  min-width: 0;
+  font-size: 12px;
+  color: var(--text-secondary);
+  white-space: nowrap;
+  overflow: hidden;
+  text-overflow: ellipsis;
+}
+
+.update-release-date {
+  flex-shrink: 0;
+  font-family: 'JetBrains Mono', 'Consolas', monospace;
+  font-size: 11px;
+  color: var(--text-muted);
+}
+
+.update-release-notes {
+  margin: 0;
+  padding-left: 18px;
+  color: var(--text-secondary);
+  font-size: 12px;
+  line-height: 1.55;
+}
+
+.update-release-notes li + li { margin-top: 4px; }
+
+.update-release-empty {
+  font-size: 12px;
+  color: var(--text-muted);
+}
+
 /* ============================================================
    Data Card
    ============================================================ */

+ 27 - 1
sidepanel/sidepanel.html

@@ -20,7 +20,13 @@
         stroke-linecap="round" stroke-linejoin="round">
         <path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" />
       </svg>
-      <h1>多页面</h1>
+      <div class="header-version-block">
+        <div class="header-version-main">
+          <div id="extension-update-status" class="header-version-title">v0.0.0</div>
+          <button id="btn-release-log" class="header-link-btn" type="button" hidden>更新日志</button>
+        </div>
+        <span id="extension-version-meta" class="header-version-meta" hidden></span>
+      </div>
     </div>
     <div class="header-btns">
       <div class="run-group">
@@ -69,6 +75,20 @@
     </div>
   </header>
 
+  <section id="update-section" hidden>
+    <div class="update-card">
+      <div class="update-card-header">
+        <div class="update-card-copy">
+          <span class="section-label">更新内容</span>
+          <div id="update-card-version" class="update-card-version"></div>
+          <p id="update-card-summary" class="update-card-summary"></p>
+        </div>
+        <button id="btn-open-release" class="btn btn-primary btn-sm" type="button">前往更新</button>
+      </div>
+      <div id="update-release-list" class="update-release-list"></div>
+    </div>
+  </section>
+
   <section id="data-section">
     <div id="settings-card" class="data-card">
       <div class="data-row">
@@ -137,6 +157,7 @@
             <option value="163-vip">163 VIP 邮箱 (vip.163.com)</option>
             <option value="qq">QQ 邮箱 (wx.mail.qq.com)</option>
             <option value="inbucket">Inbucket(自定义主机)</option>
+            <option value="2925">2925 邮箱 (2925.com)</option>
           </select>
           <button id="btn-mail-login" class="btn btn-outline btn-sm data-inline-btn" type="button" disabled>登录</button>
         </div>
@@ -157,6 +178,10 @@
           <button id="btn-cf-domain-mode" class="btn btn-outline btn-sm data-inline-btn" type="button">添加</button>
         </div>
       </div>
+      <div class="data-row" id="row-email-prefix" style="display:none;">
+        <span class="data-label" id="label-email-prefix">邮箱前缀</span>
+        <input type="text" id="input-email-prefix" class="data-input" placeholder="例如 abc" />
+      </div>
       <div class="data-row" id="row-inbucket-host" style="display:none;">
         <span class="data-label">Inbucket</span>
         <input type="text" id="input-inbucket-host" class="data-input" placeholder="填写主机或 https://主机地址" />
@@ -387,6 +412,7 @@
   <div id="toast-container"></div>
   <input id="input-import-settings-file" type="file" accept=".json,application/json" hidden />
   <script src="../hotmail-utils.js"></script>
+  <script src="update-service.js"></script>
   <script src="sidepanel.js"></script>
 </body>
 

+ 288 - 8
sidepanel/sidepanel.js

@@ -11,6 +11,14 @@ const STATUS_ICONS = {
 };
 
 const logArea = document.getElementById('log-area');
+const updateSection = document.getElementById('update-section');
+const extensionUpdateStatus = document.getElementById('extension-update-status');
+const extensionVersionMeta = document.getElementById('extension-version-meta');
+const btnReleaseLog = document.getElementById('btn-release-log');
+const updateCardVersion = document.getElementById('update-card-version');
+const updateCardSummary = document.getElementById('update-card-summary');
+const updateReleaseList = document.getElementById('update-release-list');
+const btnOpenRelease = document.getElementById('btn-open-release');
 const settingsCard = document.getElementById('settings-card');
 const displayOauthUrl = document.getElementById('display-oauth-url');
 const displayLocalhostUrl = document.getElementById('display-localhost-url');
@@ -73,6 +81,9 @@ const btnDeleteAllHotmailAccounts = document.getElementById('btn-delete-all-hotm
 const btnToggleHotmailList = document.getElementById('btn-toggle-hotmail-list');
 const hotmailListShell = document.getElementById('hotmail-list-shell');
 const hotmailAccountsList = document.getElementById('hotmail-accounts-list');
+const rowEmailPrefix = document.getElementById('row-email-prefix');
+const labelEmailPrefix = document.getElementById('label-email-prefix');
+const inputEmailPrefix = document.getElementById('input-email-prefix');
 const rowInbucketHost = document.getElementById('row-inbucket-host');
 const inputInbucketHost = document.getElementById('input-inbucket-host');
 const rowInbucketMailbox = document.getElementById('row-inbucket-mailbox');
@@ -142,6 +153,7 @@ let hotmailActionInFlight = false;
 let hotmailListExpanded = false;
 let configMenuOpen = false;
 let configActionInFlight = false;
+let currentReleaseSnapshot = null;
 
 const EYE_OPEN_ICON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z"/><circle cx="12" cy="12" r="3"/></svg>';
 const EYE_CLOSED_ICON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.94 17.94A10.94 10.94 0 0 1 12 19C5 19 1 12 1 12a21.77 21.77 0 0 1 5.06-6.94"/><path d="M9.9 4.24A10.94 10.94 0 0 1 12 5c7 0 11 7 11 7a21.86 21.86 0 0 1-2.16 3.19"/><path d="M1 1l22 22"/><path d="M14.12 14.12a3 3 0 1 1-4.24-4.24"/></svg>';
@@ -153,6 +165,7 @@ const filterHotmailAccountsByUsage = window.HotmailUtils?.filterHotmailAccountsB
 const getHotmailBulkActionLabel = window.HotmailUtils?.getHotmailBulkActionLabel;
 const getHotmailListToggleLabel = window.HotmailUtils?.getHotmailListToggleLabel;
 const HOTMAIL_LIST_EXPANDED_STORAGE_KEY = 'multipage-hotmail-list-expanded';
+const sidepanelUpdateService = window.SidepanelUpdateService;
 const MAIL_PROVIDER_LOGIN_CONFIGS = {
   '163': {
     label: '163 邮箱',
@@ -166,6 +179,10 @@ const MAIL_PROVIDER_LOGIN_CONFIGS = {
     label: 'QQ 邮箱',
     url: 'https://wx.mail.qq.com/',
   },
+  '2925': {
+    label: '2925 邮箱',
+    url: 'https://2925.com/#/mailList',
+  },
 };
 
 // ============================================================
@@ -188,6 +205,10 @@ const LOG_LEVEL_LABELS = {
   error: '错误',
 };
 
+function usesGeneratedAliasMailProvider(provider) {
+  return provider === '2925';
+}
+
 function showToast(message, type = 'error', duration = 4000) {
   const toast = document.createElement('div');
   toast.className = `toast toast-${type}`;
@@ -743,6 +764,7 @@ function collectSettingsPayload() {
     customPassword: inputPassword.value,
     mailProvider: selectMailProvider.value,
     emailGenerator: selectEmailGenerator.value,
+    emailPrefix: inputEmailPrefix.value.trim(),
     inbucketHost: inputInbucketHost.value.trim(),
     inbucketMailbox: inputInbucketMailbox.value.trim(),
     cloudflareDomain: selectedCloudflareDomain,
@@ -890,7 +912,7 @@ function applyAutoRunStatus(payload = currentAutoRun) {
 
   inputRunCount.disabled = currentAutoRun.autoRunning;
   btnAutoRun.disabled = currentAutoRun.autoRunning;
-  btnFetchEmail.disabled = locked;
+  btnFetchEmail.disabled = locked || usesGeneratedAliasMailProvider(selectMailProvider.value);
   inputEmail.disabled = locked;
   inputAutoSkipFailures.disabled = scheduled;
 
@@ -924,7 +946,7 @@ function applyAutoRunStatus(payload = currentAutoRun) {
       setDefaultAutoRunButton();
       inputEmail.disabled = false;
       if (!locked) {
-        btnFetchEmail.disabled = false;
+        btnFetchEmail.disabled = usesGeneratedAliasMailProvider(selectMailProvider.value);
       }
       break;
   }
@@ -987,6 +1009,7 @@ function applySettingsState(state) {
   inputSub2ApiGroup.value = state?.sub2apiGroupName || '';
   selectMailProvider.value = state?.mailProvider || '163';
   selectEmailGenerator.value = state?.emailGenerator || 'duck';
+  inputEmailPrefix.value = state?.emailPrefix || '';
   inputInbucketHost.value = state?.inbucketHost || '';
   inputInbucketMailbox.value = state?.inbucketMailbox || '';
   renderCloudflareDomainOptions(state?.cloudflareDomain || '');
@@ -1041,6 +1064,212 @@ async function restoreState() {
   }
 }
 
+function openExternalUrl(url) {
+  const targetUrl = String(url || '').trim();
+  if (!targetUrl) {
+    return;
+  }
+
+  if (chrome?.tabs?.create) {
+    chrome.tabs.create({ url: targetUrl, active: true }).catch(() => {
+      window.open(targetUrl, '_blank', 'noopener');
+    });
+    return;
+  }
+
+  window.open(targetUrl, '_blank', 'noopener');
+}
+
+function createUpdateNoteList(notes = []) {
+  if (!Array.isArray(notes) || notes.length === 0) {
+    const empty = document.createElement('p');
+    empty.className = 'update-release-empty';
+    empty.textContent = '该版本未提供可解析的更新说明,请查看完整更新日志。';
+    return empty;
+  }
+
+  const list = document.createElement('ul');
+  list.className = 'update-release-notes';
+
+  notes.forEach((note) => {
+    const item = document.createElement('li');
+    item.textContent = note;
+    list.appendChild(item);
+  });
+
+  return list;
+}
+
+function renderUpdateReleaseList(releases = []) {
+  if (!updateReleaseList) {
+    return;
+  }
+
+  updateReleaseList.innerHTML = '';
+
+  releases.forEach((release) => {
+    const item = document.createElement('article');
+    item.className = 'update-release-item';
+
+    const head = document.createElement('div');
+    head.className = 'update-release-head';
+
+    const titleRow = document.createElement('div');
+    titleRow.className = 'update-release-title-row';
+
+    const version = document.createElement('span');
+    version.className = 'update-release-version';
+    version.textContent = `v${release.version}`;
+    titleRow.appendChild(version);
+
+    if (release.title) {
+      const name = document.createElement('span');
+      name.className = 'update-release-name';
+      name.textContent = release.title;
+      titleRow.appendChild(name);
+    }
+
+    head.appendChild(titleRow);
+
+    const publishedAt = sidepanelUpdateService?.formatReleaseDate?.(release.publishedAt) || '';
+    if (publishedAt) {
+      const date = document.createElement('span');
+      date.className = 'update-release-date';
+      date.textContent = publishedAt;
+      head.appendChild(date);
+    }
+
+    item.appendChild(head);
+    item.appendChild(createUpdateNoteList(release.notes));
+    updateReleaseList.appendChild(item);
+  });
+}
+
+function resetUpdateCard() {
+  if (updateSection) {
+    updateSection.hidden = true;
+  }
+  if (updateCardVersion) {
+    updateCardVersion.textContent = '';
+  }
+  if (updateCardSummary) {
+    updateCardSummary.textContent = '';
+  }
+  if (updateReleaseList) {
+    updateReleaseList.innerHTML = '';
+  }
+  if (btnOpenRelease) {
+    btnOpenRelease.hidden = true;
+    btnOpenRelease.onclick = null;
+  }
+}
+
+function renderReleaseSnapshot(snapshot) {
+  currentReleaseSnapshot = snapshot;
+
+  if (!extensionUpdateStatus || !extensionVersionMeta) {
+    return;
+  }
+
+  extensionUpdateStatus.classList.remove('is-update-available', 'is-check-failed', 'is-version-label');
+
+  const localVersionText = snapshot?.localVersion ? `v${snapshot.localVersion}` : '';
+  const logUrl = snapshot?.logUrl || snapshot?.releasesPageUrl || sidepanelUpdateService?.releasesPageUrl || '';
+
+  if (btnReleaseLog) {
+    btnReleaseLog.onclick = () => openExternalUrl(logUrl);
+    btnReleaseLog.hidden = true;
+  }
+  extensionVersionMeta.hidden = true;
+  extensionVersionMeta.textContent = '';
+
+  switch (snapshot?.status) {
+    case 'update-available': {
+      extensionUpdateStatus.textContent = '有更新';
+      extensionUpdateStatus.classList.add('is-update-available');
+      if (btnReleaseLog) {
+        btnReleaseLog.hidden = false;
+      }
+
+      if (updateSection) {
+        updateSection.hidden = false;
+      }
+      if (updateCardVersion) {
+        updateCardVersion.textContent = `最新版本 v${snapshot.latestVersion}`;
+      }
+      if (updateCardSummary) {
+        const updateCount = Array.isArray(snapshot.newerReleases) ? snapshot.newerReleases.length : 0;
+        updateCardSummary.textContent = updateCount > 1
+          ? `当前 ${localVersionText},共有 ${updateCount} 个新版本可更新。`
+          : `当前 ${localVersionText},可更新到 v${snapshot.latestVersion}。`;
+      }
+      renderUpdateReleaseList(snapshot.newerReleases || []);
+      if (btnOpenRelease) {
+        btnOpenRelease.hidden = false;
+        btnOpenRelease.textContent = '前往更新';
+        btnOpenRelease.onclick = () => openExternalUrl(logUrl);
+      }
+      break;
+    }
+
+    case 'latest': {
+      extensionUpdateStatus.textContent = localVersionText || 'v0.0.0';
+      extensionUpdateStatus.classList.add('is-version-label');
+      resetUpdateCard();
+      break;
+    }
+
+    case 'empty': {
+      extensionUpdateStatus.textContent = localVersionText || 'v0.0.0';
+      extensionUpdateStatus.classList.add('is-version-label');
+      resetUpdateCard();
+      break;
+    }
+
+    case 'error':
+    default: {
+      extensionUpdateStatus.textContent = localVersionText || 'v0.0.0';
+      extensionUpdateStatus.classList.add('is-version-label', 'is-check-failed');
+      extensionVersionMeta.textContent = snapshot?.errorMessage || 'GitHub Releases 检查失败';
+      extensionVersionMeta.hidden = false;
+      resetUpdateCard();
+      break;
+    }
+  }
+}
+
+async function initializeReleaseInfo() {
+  const fallbackReleaseUrl = sidepanelUpdateService?.releasesPageUrl || 'https://github.com/QLHazyCoder/codex-oauth-automation-extension/releases';
+
+  if (btnReleaseLog) {
+    btnReleaseLog.onclick = () => openExternalUrl(currentReleaseSnapshot?.logUrl || fallbackReleaseUrl);
+  }
+
+  if (!extensionUpdateStatus || !extensionVersionMeta) {
+    return;
+  }
+
+  const localVersion = sidepanelUpdateService?.stripVersionPrefix?.(chrome.runtime.getManifest()?.version || '') || '';
+  extensionUpdateStatus.textContent = localVersion ? `v${localVersion}` : 'v0.0.0';
+  extensionUpdateStatus.classList.remove('is-update-available', 'is-check-failed');
+  extensionUpdateStatus.classList.add('is-version-label');
+  extensionVersionMeta.hidden = true;
+  extensionVersionMeta.textContent = '';
+  if (btnReleaseLog) {
+    btnReleaseLog.hidden = true;
+  }
+  resetUpdateCard();
+
+  if (!sidepanelUpdateService) {
+    extensionVersionMeta.textContent = '更新检查服务不可用';
+    extensionVersionMeta.hidden = false;
+    return;
+  }
+
+  const snapshot = await sidepanelUpdateService.getReleaseSnapshot();
+  renderReleaseSnapshot(snapshot);
+}
+
 function syncPasswordField(state) {
   inputPassword.value = state.customPassword || state.password || '';
 }
@@ -1095,6 +1324,22 @@ function isCurrentEmailManagedByHotmail(state = latestState) {
   return inputEmailValue === hotmailEmail || stateEmailValue === hotmailEmail;
 }
 
+function isCurrentEmailManagedByGeneratedAlias(provider = latestState?.mailProvider, state = latestState) {
+  const normalizedProvider = String(provider || '').trim();
+  if (!usesGeneratedAliasMailProvider(normalizedProvider)) {
+    return false;
+  }
+
+  const inputEmailValue = String(inputEmail.value || '').trim().toLowerCase();
+  const stateEmailValue = String(state?.email || '').trim().toLowerCase();
+
+  if (normalizedProvider === '2925') {
+    return inputEmailValue.endsWith('@2925.com') || stateEmailValue.endsWith('@2925.com');
+  }
+
+  return false;
+}
+
 function updateMailLoginButtonState() {
   if (!btnMailLogin) {
     return;
@@ -1310,10 +1555,13 @@ function renderHotmailAccounts() {
 }
 
 function updateMailProviderUI() {
+  const use2925 = selectMailProvider.value === '2925';
+  const useGeneratedAlias = usesGeneratedAliasMailProvider(selectMailProvider.value);
   const useInbucket = selectMailProvider.value === 'inbucket';
   const useHotmail = selectMailProvider.value === 'hotmail-api';
-  const useEmailGenerator = !useHotmail;
+  const useEmailGenerator = !useHotmail && !useGeneratedAlias;
   updateMailLoginButtonState();
+  rowEmailPrefix.style.display = useGeneratedAlias ? '' : 'none';
   rowInbucketHost.style.display = useInbucket ? '' : 'none';
   rowInbucketMailbox.style.display = useInbucket ? '' : 'none';
   const useCloudflare = selectEmailGenerator.value === 'cloudflare';
@@ -1332,18 +1580,23 @@ function updateMailProviderUI() {
   if (hotmailSection) {
     hotmailSection.style.display = useHotmail ? '' : 'none';
   }
-  selectEmailGenerator.disabled = useHotmail;
+  labelEmailPrefix.textContent = '邮箱前缀';
+  inputEmailPrefix.placeholder = '例如 abc';
+  selectEmailGenerator.disabled = useHotmail || useGeneratedAlias;
   btnFetchEmail.hidden = useHotmail;
-  inputEmail.readOnly = useHotmail;
+  inputEmail.readOnly = useHotmail || useGeneratedAlias;
   const uiCopy = getEmailGeneratorUiCopy();
-  inputEmail.placeholder = useHotmail ? '由 Hotmail 账号池自动分配' : uiCopy.placeholder;
+  inputEmail.placeholder = useHotmail
+    ? '由 Hotmail 账号池自动分配'
+    : (use2925 ? '步骤 3 自动生成 2925 邮箱并回填' : uiCopy.placeholder);
+  btnFetchEmail.disabled = useGeneratedAlias || isAutoRunLockedPhase();
   if (!btnFetchEmail.disabled) {
     btnFetchEmail.textContent = uiCopy.buttonLabel;
   }
   if (autoHintText) {
     autoHintText.textContent = useHotmail
       ? '请先校验并选择一个 Hotmail 账号'
-      : '先自动获取邮箱,或手动粘贴邮箱后再继续';
+      : (useGeneratedAlias ? '步骤 3 会自动生成邮箱,无需手动获取' : '先自动获取邮箱,或手动粘贴邮箱后再继续');
   }
   if (useHotmail) {
     inputEmail.value = getCurrentHotmailEmail();
@@ -1873,6 +2126,16 @@ document.querySelectorAll('.step-btn').forEach(btn => {
           if (response?.error) {
             throw new Error(response.error);
           }
+        } else if (usesGeneratedAliasMailProvider(selectMailProvider.value)) {
+          const emailPrefix = inputEmailPrefix.value.trim();
+          if (!emailPrefix) {
+            showToast('请先填写 2925 邮箱前缀。', 'warn');
+            return;
+          }
+          const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, emailPrefix } });
+          if (response?.error) {
+            throw new Error(response.error);
+          }
         } else {
           let email = inputEmail.value.trim();
           if (!email) {
@@ -2395,7 +2658,13 @@ selectMailProvider.addEventListener('change', async () => {
   const previousProvider = latestState?.mailProvider || '';
   const nextProvider = selectMailProvider.value;
   updateMailProviderUI();
-  if (previousProvider === 'hotmail-api' && nextProvider !== 'hotmail-api' && isCurrentEmailManagedByHotmail()) {
+  const leavingHotmail = previousProvider === 'hotmail-api'
+    && nextProvider !== 'hotmail-api'
+    && isCurrentEmailManagedByHotmail();
+  const leavingGeneratedAlias = previousProvider !== nextProvider
+    && usesGeneratedAliasMailProvider(previousProvider)
+    && isCurrentEmailManagedByGeneratedAlias(previousProvider);
+  if (leavingHotmail || leavingGeneratedAlias) {
     await clearRegistrationEmail({ silent: true }).catch(() => { });
   }
   markSettingsDirty(true);
@@ -2483,6 +2752,14 @@ inputSub2ApiGroup.addEventListener('blur', () => {
   saveSettings({ silent: true }).catch(() => { });
 });
 
+inputEmailPrefix.addEventListener('input', () => {
+  markSettingsDirty(true);
+  scheduleSettingsAutoSave();
+});
+inputEmailPrefix.addEventListener('blur', () => {
+  saveSettings({ silent: true }).catch(() => {});
+});
+
 inputInbucketMailbox.addEventListener('input', () => {
   markSettingsDirty(true);
   scheduleSettingsAutoSave();
@@ -2745,6 +3022,9 @@ initHotmailListExpandedState();
 updateSaveButtonState();
 updateConfigMenuControls();
 setLocalCpaStep9Mode(DEFAULT_LOCAL_CPA_STEP9_MODE);
+initializeReleaseInfo().catch((err) => {
+  console.error('Failed to initialize release info:', err);
+});
 restoreState().then(() => {
   syncPasswordToggleLabel();
   syncVpsUrlToggleLabel();

+ 288 - 0
sidepanel/update-service.js

@@ -0,0 +1,288 @@
+(() => {
+  const GITHUB_OWNER = 'QLHazyCoder';
+  const GITHUB_REPO = 'codex-oauth-automation-extension';
+  const RELEASES_PAGE_URL = `https://github.com/${GITHUB_OWNER}/${GITHUB_REPO}/releases`;
+  const RELEASES_API_URL = `https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}/releases?per_page=10`;
+  const CACHE_KEY = 'multipage-release-snapshot-v1';
+  const CACHE_TTL_MS = 60 * 60 * 1000;
+  const FETCH_TIMEOUT_MS = 8000;
+  const MAX_RELEASES = 10;
+  const MAX_NOTES_PER_RELEASE = 5;
+
+  function stripVersionPrefix(version) {
+    return String(version || '').trim().replace(/^v/i, '');
+  }
+
+  function parseVersionParts(version) {
+    const core = stripVersionPrefix(version).split('-')[0];
+    if (!core) {
+      return [0];
+    }
+
+    return core.split('.').map((part) => {
+      const numeric = Number.parseInt(part, 10);
+      return Number.isFinite(numeric) ? numeric : 0;
+    });
+  }
+
+  function compareVersions(left, right) {
+    const leftParts = parseVersionParts(left);
+    const rightParts = parseVersionParts(right);
+    const maxLength = Math.max(leftParts.length, rightParts.length, 3);
+
+    for (let index = 0; index < maxLength; index += 1) {
+      const leftPart = leftParts[index] || 0;
+      const rightPart = rightParts[index] || 0;
+      if (leftPart > rightPart) {
+        return 1;
+      }
+      if (leftPart < rightPart) {
+        return -1;
+      }
+    }
+
+    return 0;
+  }
+
+  function sanitizeInlineMarkdown(text) {
+    return String(text || '')
+      .replace(/!\[[^\]]*]\(([^)]+)\)/g, '')
+      .replace(/\[([^\]]+)]\(([^)]+)\)/g, '$1')
+      .replace(/`([^`]+)`/g, '$1')
+      .replace(/[*_~>#]/g, '')
+      .replace(/\s+/g, ' ')
+      .trim();
+  }
+
+  function parseReleaseNotes(body) {
+    const lines = String(body || '')
+      .replace(/\r\n/g, '\n')
+      .split('\n')
+      .map((line) => line.trim())
+      .filter(Boolean);
+
+    const bulletLines = [];
+    const plainLines = [];
+
+    for (const line of lines) {
+      if (/^#{1,6}\s*/.test(line)) {
+        continue;
+      }
+
+      if (/^```/.test(line) || /^---+$/.test(line)) {
+        continue;
+      }
+
+      if (/^[-*+]\s+/.test(line)) {
+        bulletLines.push(line.replace(/^[-*+]\s+/, ''));
+        continue;
+      }
+
+      if (/^\d+\.\s+/.test(line)) {
+        bulletLines.push(line.replace(/^\d+\.\s+/, ''));
+        continue;
+      }
+
+      plainLines.push(line);
+    }
+
+    const noteLines = bulletLines.length > 0 ? bulletLines : plainLines;
+    return noteLines
+      .map(sanitizeInlineMarkdown)
+      .filter(Boolean)
+      .slice(0, MAX_NOTES_PER_RELEASE);
+  }
+
+  function normalizeReleaseVersion(release) {
+    const candidates = [
+      release?.tag_name,
+      release?.name,
+    ];
+
+    for (const candidate of candidates) {
+      const normalized = stripVersionPrefix(candidate);
+      if (normalized) {
+        return normalized;
+      }
+    }
+
+    return '';
+  }
+
+  function sanitizeRelease(release) {
+    const version = normalizeReleaseVersion(release);
+    if (!version) {
+      return null;
+    }
+
+    const rawTitle = sanitizeInlineMarkdown(release?.name || '');
+    const normalizedTitle = stripVersionPrefix(rawTitle) === version ? '' : rawTitle;
+
+    return {
+      version,
+      title: normalizedTitle,
+      url: String(release?.html_url || RELEASES_PAGE_URL),
+      publishedAt: String(release?.published_at || release?.created_at || ''),
+      notes: parseReleaseNotes(release?.body || ''),
+    };
+  }
+
+  function readCache() {
+    try {
+      const raw = localStorage.getItem(CACHE_KEY);
+      if (!raw) {
+        return null;
+      }
+
+      const parsed = JSON.parse(raw);
+      if (!parsed || !Array.isArray(parsed.releases) || !Number.isFinite(parsed.fetchedAt)) {
+        return null;
+      }
+
+      if ((Date.now() - parsed.fetchedAt) > CACHE_TTL_MS) {
+        return null;
+      }
+
+      return parsed.releases;
+    } catch (error) {
+      return null;
+    }
+  }
+
+  function writeCache(releases) {
+    try {
+      localStorage.setItem(CACHE_KEY, JSON.stringify({
+        fetchedAt: Date.now(),
+        releases,
+      }));
+    } catch (error) {
+      // Ignore cache write failures.
+    }
+  }
+
+  async function fetchReleases() {
+    const controller = new AbortController();
+    const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
+
+    try {
+      const response = await fetch(RELEASES_API_URL, {
+        method: 'GET',
+        headers: {
+          Accept: 'application/vnd.github+json',
+        },
+        cache: 'no-store',
+        signal: controller.signal,
+      });
+
+      if (!response.ok) {
+        throw new Error(`GitHub Releases 请求失败(${response.status})`);
+      }
+
+      const payload = await response.json();
+      if (!Array.isArray(payload)) {
+        throw new Error('GitHub Releases 返回格式异常');
+      }
+
+      const releases = payload
+        .filter((release) => release && !release.draft && !release.prerelease)
+        .map(sanitizeRelease)
+        .filter(Boolean)
+        .sort((left, right) => compareVersions(right.version, left.version))
+        .slice(0, MAX_RELEASES);
+
+      writeCache(releases);
+      return releases;
+    } catch (error) {
+      if (error?.name === 'AbortError') {
+        throw new Error('GitHub Releases 请求超时');
+      }
+      throw error;
+    } finally {
+      clearTimeout(timeoutId);
+    }
+  }
+
+  async function loadReleases(options = {}) {
+    if (!options.force) {
+      const cached = readCache();
+      if (cached) {
+        return cached;
+      }
+    }
+
+    return fetchReleases();
+  }
+
+  function buildReleaseSnapshot(releases, localVersion) {
+    const latestRelease = releases[0] || null;
+    if (!latestRelease) {
+      return {
+        status: 'empty',
+        localVersion,
+        latestVersion: null,
+        latestRelease: null,
+        newerReleases: [],
+        logUrl: RELEASES_PAGE_URL,
+        releasesPageUrl: RELEASES_PAGE_URL,
+        checkedAt: Date.now(),
+      };
+    }
+
+    const newerReleases = releases.filter((release) => compareVersions(release.version, localVersion) > 0);
+    return {
+      status: newerReleases.length > 0 ? 'update-available' : 'latest',
+      localVersion,
+      latestVersion: latestRelease.version,
+      latestRelease,
+      newerReleases,
+      logUrl: latestRelease.url || RELEASES_PAGE_URL,
+      releasesPageUrl: RELEASES_PAGE_URL,
+      checkedAt: Date.now(),
+    };
+  }
+
+  async function getReleaseSnapshot(options = {}) {
+    const localVersion = stripVersionPrefix(chrome.runtime.getManifest()?.version || '0.0.0');
+
+    try {
+      const releases = await loadReleases(options);
+      return buildReleaseSnapshot(releases, localVersion);
+    } catch (error) {
+      return {
+        status: 'error',
+        localVersion,
+        latestVersion: null,
+        latestRelease: null,
+        newerReleases: [],
+        logUrl: RELEASES_PAGE_URL,
+        releasesPageUrl: RELEASES_PAGE_URL,
+        checkedAt: Date.now(),
+        errorMessage: error?.message || '更新检查失败',
+      };
+    }
+  }
+
+  function formatReleaseDate(value) {
+    if (!value) {
+      return '';
+    }
+
+    const date = new Date(value);
+    if (Number.isNaN(date.getTime())) {
+      return '';
+    }
+
+    const year = date.getFullYear();
+    const month = String(date.getMonth() + 1).padStart(2, '0');
+    const day = String(date.getDate()).padStart(2, '0');
+    return `${year}-${month}-${day}`;
+  }
+
+  window.SidepanelUpdateService = {
+    compareVersions,
+    formatReleaseDate,
+    getReleaseSnapshot,
+    releasesPageUrl: RELEASES_PAGE_URL,
+    stripVersionPrefix,
+  };
+})();