From 0614917ad4d723564ee97560eb7fc6e7e26465f3 Mon Sep 17 00:00:00 2001 From: Twelveeee Date: Mon, 13 Apr 2026 17:27:42 +0800 Subject: [PATCH 1/4] =?UTF-8?q?feat:=E6=96=B0=E5=A2=9ECloudflareTempEmail?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- background.js | 303 +++++++++++++- cloudflare-temp-email-utils.js | 400 +++++++++++++++++++ sidepanel/sidepanel.html | 23 ++ sidepanel/sidepanel.js | 261 +++++++++++- tests/auto-run-fresh-attempt-reset.test.js | 8 + tests/cloudflare-temp-email-provider.test.js | 160 ++++++++ tests/cloudflare-temp-email-utils.test.js | 107 +++++ tests/step9-localhost-cleanup-scope.test.js | 7 + tests/verification-stop-propagation.test.js | 6 +- 9 files changed, 1258 insertions(+), 17 deletions(-) create mode 100644 cloudflare-temp-email-utils.js create mode 100644 tests/cloudflare-temp-email-provider.test.js create mode 100644 tests/cloudflare-temp-email-utils.test.js diff --git a/background.js b/background.js index 11fd5ec..d28953a 100644 --- a/background.js +++ b/background.js @@ -1,6 +1,6 @@ // background.js — Service Worker: orchestration, state, tab management, message routing -importScripts('data/names.js', 'hotmail-utils.js', 'content/activation-utils.js'); +importScripts('data/names.js', 'hotmail-utils.js', 'cloudflare-temp-email-utils.js', 'content/activation-utils.js'); const { buildHotmailMailApiLatestUrl, @@ -17,6 +17,17 @@ const { pickVerificationMessageWithTimeFallback, shouldClearHotmailCurrentSelection, } = self.HotmailUtils; +const { + DEFAULT_MAIL_PAGE_SIZE: CLOUDFLARE_TEMP_EMAIL_DEFAULT_PAGE_SIZE, + buildCloudflareTempEmailHeaders, + getCloudflareTempEmailAddressFromResponse, + joinCloudflareTempEmailUrl, + normalizeCloudflareTempEmailAddress, + normalizeCloudflareTempEmailBaseUrl, + normalizeCloudflareTempEmailDomain, + normalizeCloudflareTempEmailDomains, + normalizeCloudflareTempEmailMailApiMessages, +} = self.CloudflareTempEmailUtils; const { isRecoverableStep9AuthFailure, } = self.MultiPageActivationUtils; @@ -24,6 +35,8 @@ const { const LOG_PREFIX = '[MultiPage:bg]'; const DUCK_AUTOFILL_URL = 'https://duckduckgo.com/email/settings/autofill'; const HOTMAIL_PROVIDER = 'hotmail-api'; +const CLOUDFLARE_TEMP_EMAIL_PROVIDER = 'cloudflare-temp-email'; +const CLOUDFLARE_TEMP_EMAIL_GENERATOR = 'cloudflare-temp-email'; const HOTMAIL_MAILBOXES = ['INBOX', 'Junk']; const STOP_ERROR_MESSAGE = '流程已被用户停止。'; const HUMAN_STEP_DELAY_MIN = 700; @@ -81,6 +94,11 @@ const PERSISTED_SETTING_DEFAULTS = { hotmailLocalBaseUrl: DEFAULT_HOTMAIL_LOCAL_BASE_URL, cloudflareDomain: '', cloudflareDomains: [], + cloudflareTempEmailBaseUrl: '', + cloudflareTempEmailAdminAuth: '', + cloudflareTempEmailCustomAuth: '', + cloudflareTempEmailDomain: '', + cloudflareTempEmailDomains: [], hotmailAccounts: [], }; @@ -218,9 +236,8 @@ function normalizeEmailGenerator(value = '') { if (normalized === 'custom' || normalized === 'manual') { return 'custom'; } - if (normalized === 'cloudflare') { - return 'cloudflare'; - } + if (normalized === 'cloudflare') return 'cloudflare'; + if (normalized === CLOUDFLARE_TEMP_EMAIL_GENERATOR) return CLOUDFLARE_TEMP_EMAIL_GENERATOR; return 'duck'; } @@ -233,6 +250,7 @@ function normalizeMailProvider(value = '') { switch (normalized) { case 'custom': case HOTMAIL_PROVIDER: + case CLOUDFLARE_TEMP_EMAIL_PROVIDER: case '163': case '163-vip': case 'qq': @@ -330,6 +348,16 @@ function getHotmailServiceSettings(state = {}) { }; } +function getCloudflareTempEmailConfig(state = {}) { + return { + baseUrl: normalizeCloudflareTempEmailBaseUrl(state.cloudflareTempEmailBaseUrl), + adminAuth: String(state.cloudflareTempEmailAdminAuth || ''), + customAuth: String(state.cloudflareTempEmailCustomAuth || ''), + domain: normalizeCloudflareTempEmailDomain(state.cloudflareTempEmailDomain), + domains: normalizeCloudflareTempEmailDomains(state.cloudflareTempEmailDomains), + }; +} + function normalizePersistentSettingValue(key, value) { switch (key) { case 'panelMode': @@ -379,6 +407,15 @@ function normalizePersistentSettingValue(key, value) { return normalizeCloudflareDomain(value); case 'cloudflareDomains': return normalizeCloudflareDomains(value); + case 'cloudflareTempEmailBaseUrl': + return normalizeCloudflareTempEmailBaseUrl(value); + case 'cloudflareTempEmailAdminAuth': + case 'cloudflareTempEmailCustomAuth': + return String(value || ''); + case 'cloudflareTempEmailDomain': + return normalizeCloudflareTempEmailDomain(value); + case 'cloudflareTempEmailDomains': + return normalizeCloudflareTempEmailDomains(value); case 'hotmailAccounts': return normalizeHotmailAccounts(value); default: @@ -422,6 +459,13 @@ function buildPersistentSettingsPayload(input = {}, options = {}) { } payload.cloudflareDomains = domains; } + if (payload.cloudflareTempEmailDomains) { + const domains = normalizeCloudflareTempEmailDomains(payload.cloudflareTempEmailDomains); + if (payload.cloudflareTempEmailDomain && !domains.includes(payload.cloudflareTempEmailDomain)) { + domains.unshift(payload.cloudflareTempEmailDomain); + } + payload.cloudflareTempEmailDomains = domains; + } return payload; } @@ -1302,6 +1346,120 @@ function buildGeneratedAliasEmail(state) { throw new Error(`未支持的别名邮箱类型:${provider}`); } +function summarizeCloudflareTempEmailMessagesForLog(messages) { + return (messages || []) + .slice() + .sort((left, right) => { + const leftTime = Date.parse(left.receivedDateTime || '') || 0; + const rightTime = Date.parse(right.receivedDateTime || '') || 0; + return rightTime - leftTime; + }) + .slice(0, 3) + .map((message) => { + const receivedAt = message?.receivedDateTime || '未知时间'; + const sender = message?.from?.emailAddress?.address || '未知发件人'; + const subject = message?.subject || '(无主题)'; + const preview = String(message?.bodyPreview || '').replace(/\s+/g, ' ').trim().slice(0, 80); + const address = message?.address || '未知地址'; + return `[${address}] ${receivedAt} | ${sender} | ${subject} | ${preview}`; + }) + .join(' || '); +} + +async function deleteCloudflareTempEmailMail(config, mailId) { + const normalizedMailId = String(mailId || '').trim(); + if (!normalizedMailId) return false; + + await requestCloudflareTempEmailJson(config, `/admin/mails/${encodeURIComponent(normalizedMailId)}`, { + method: 'DELETE', + }); + return true; +} + +async function listCloudflareTempEmailMessages(state, options = {}) { + const config = ensureCloudflareTempEmailConfig(state, { requireAdminAuth: true }); + const address = normalizeCloudflareTempEmailAddress(options.address); + const payload = await requestCloudflareTempEmailJson(config, '/admin/mails', { + method: 'GET', + searchParams: { + limit: Number(options.limit) || CLOUDFLARE_TEMP_EMAIL_DEFAULT_PAGE_SIZE, + offset: Number(options.offset) || 0, + address, + }, + }); + + const messages = normalizeCloudflareTempEmailMailApiMessages(payload).filter((message) => { + if (!address) return true; + return !message.address || normalizeCloudflareTempEmailAddress(message.address) === address; + }); + + return { config, messages }; +} + +async function pollCloudflareTempEmailVerificationCode(step, state, pollPayload = {}) { + const targetEmail = normalizeCloudflareTempEmailAddress(pollPayload.targetEmail || state.email); + if (!targetEmail) { + throw new Error('Cloudflare Temp Email 轮询前缺少目标邮箱地址。'); + } + + await addLog(`步骤 ${step}:正在轮询 Cloudflare Temp Email 邮件(${targetEmail})...`, 'info'); + const maxAttempts = Number(pollPayload.maxAttempts) || 5; + const intervalMs = Number(pollPayload.intervalMs) || 3000; + let lastError = null; + + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + throwIfStopped(); + try { + const { config, messages } = await listCloudflareTempEmailMessages(state, { + address: targetEmail, + limit: pollPayload.limit || CLOUDFLARE_TEMP_EMAIL_DEFAULT_PAGE_SIZE, + offset: pollPayload.offset || 0, + }); + const matchResult = pickVerificationMessageWithTimeFallback(messages, { + afterTimestamp: pollPayload.filterAfterTimestamp || 0, + senderFilters: pollPayload.senderFilters || [], + subjectFilters: pollPayload.subjectFilters || [], + excludeCodes: pollPayload.excludeCodes || [], + }); + const match = matchResult.match; + + if (match?.code) { + if (matchResult.usedRelaxedFilters) { + const fallbackLabel = matchResult.usedTimeFallback ? '宽松匹配 + 时间回退' : '宽松匹配'; + await addLog(`步骤 ${step}:严格规则未命中,已改用 ${fallbackLabel} 并命中 Cloudflare Temp Email 验证码。`, 'warn'); + } + try { + await deleteCloudflareTempEmailMail(config, match.message?.id); + } catch (err) { + await addLog(`步骤 ${step}:删除 Cloudflare Temp Email 邮件失败:${err.message}`, 'warn'); + } + return { + ok: true, + code: match.code, + emailTimestamp: match.receivedAt || Date.now(), + mailId: match.message?.id || '', + }; + } + + lastError = new Error(`步骤 ${step}:暂未在 Cloudflare Temp Email 中找到匹配验证码(${attempt}/${maxAttempts})。`); + await addLog(lastError.message, attempt === maxAttempts ? 'warn' : 'info'); + const sample = summarizeCloudflareTempEmailMessagesForLog(messages); + if (sample) { + await addLog(`步骤 ${step}:最近邮件样本:${sample}`, 'info'); + } + } catch (err) { + lastError = err; + await addLog(`步骤 ${step}:Cloudflare Temp Email 轮询失败:${err.message}`, 'warn'); + } + + if (attempt < maxAttempts) { + await sleepWithStop(intervalMs); + } + } + + throw lastError || new Error(`步骤 ${step}:未在 Cloudflare Temp Email 中找到新的匹配验证码。`); +} + // ============================================================ // Tab Registry // ============================================================ @@ -1532,11 +1690,14 @@ function buildLocalhostCleanupPrefix(rawUrl) { async function closeTabsByUrlPrefix(prefix, options = {}) { if (!prefix) return 0; - const { excludeTabIds = [] } = options; + const { excludeTabIds = [], excludeUrls = [], excludeLocalhostCallbacks = false } = options; const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id))); + const excludedUrls = new Set((Array.isArray(excludeUrls) ? excludeUrls : []).filter(Boolean)); const tabs = await chrome.tabs.query({}); const matchedIds = tabs .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id)) + .filter((tab) => typeof tab.url === 'string' && !excludedUrls.has(tab.url)) + .filter((tab) => !(excludeLocalhostCallbacks && isLocalhostOAuthCallbackUrl(tab.url))) .filter((tab) => typeof tab.url === 'string' && tab.url.startsWith(prefix)) .map((tab) => tab.id); @@ -2124,6 +2285,7 @@ function getSourceLabel(source) { 'inbucket-mail': 'Inbucket 邮箱', 'duck-mail': 'Duck 邮箱', 'hotmail-api': 'Hotmail(远程/本地)', + 'cloudflare-temp-email': 'Cloudflare Temp Email', }; return labels[source] || source || '未知来源'; } @@ -3141,7 +3303,10 @@ async function handleStepData(step, payload) { } const localhostPrefix = buildLocalhostCleanupPrefix(payload.localhostUrl); if (localhostPrefix) { - await closeTabsByUrlPrefix(localhostPrefix); + await closeTabsByUrlPrefix(localhostPrefix, { + excludeUrls: [payload.localhostUrl], + excludeLocalhostCallbacks: true, + }); } if (shouldUseCustomRegistrationEmail(latestState) && latestState.email) { await setEmailStateSilently(null); @@ -3434,7 +3599,9 @@ function getEmailGeneratorLabel(generator) { if (generator === 'custom') { return '自定义邮箱'; } - return generator === 'cloudflare' ? 'Cloudflare 邮箱' : 'Duck 邮箱'; + if (generator === 'cloudflare') return 'Cloudflare 邮箱'; + if (generator === CLOUDFLARE_TEMP_EMAIL_GENERATOR) return 'Cloudflare Temp Email'; + return 'Duck 邮箱'; } function generateCloudflareAliasLocalPart() { @@ -3474,6 +3641,107 @@ async function fetchCloudflareEmail(state, options = {}) { return aliasEmail; } +function ensureCloudflareTempEmailConfig(state, options = {}) { + const { + requireAdminAuth = false, + requireDomain = false, + } = options; + const config = getCloudflareTempEmailConfig(state); + if (!config.baseUrl) { + throw new Error('Cloudflare Temp Email 服务地址为空或格式无效。'); + } + if (requireAdminAuth && !config.adminAuth) { + throw new Error('Cloudflare Temp Email 缺少 Admin Auth。'); + } + if (requireDomain && !config.domain) { + throw new Error('Cloudflare Temp Email 域名为空或格式无效。'); + } + return config; +} + +async function requestCloudflareTempEmailJson(config, path, options = {}) { + const { + method = 'GET', + payload, + searchParams, + timeoutMs = 20000, + } = options; + + const url = new URL(joinCloudflareTempEmailUrl(config.baseUrl, path)); + if (searchParams && typeof searchParams === 'object') { + for (const [key, value] of Object.entries(searchParams)) { + if (value === undefined || value === null || value === '') continue; + url.searchParams.set(key, String(value)); + } + } + + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs); + + let response; + try { + response = await fetch(url.toString(), { + method, + headers: buildCloudflareTempEmailHeaders(config, { + json: payload !== undefined, + }), + body: payload !== undefined ? JSON.stringify(payload) : undefined, + signal: controller.signal, + }); + } catch (err) { + const errorMessage = err?.name === 'AbortError' + ? `Cloudflare Temp Email 请求超时(>${Math.round(timeoutMs / 1000)} 秒)` + : `Cloudflare Temp Email 请求失败:${err.message}`; + throw new Error(errorMessage); + } finally { + clearTimeout(timeoutId); + } + + const text = await response.text(); + let parsed; + try { + parsed = text ? JSON.parse(text) : {}; + } catch { + parsed = text; + } + + if (!response.ok) { + const payloadError = typeof parsed === 'object' && parsed + ? (parsed.message || parsed.error || parsed.msg) + : ''; + throw new Error(`Cloudflare Temp Email 请求失败:${payloadError || text || `HTTP ${response.status}`}`); + } + + return parsed; +} + +async function fetchCloudflareTempEmailAddress(state, options = {}) { + throwIfStopped(); + const latestState = state || await getState(); + const config = ensureCloudflareTempEmailConfig(latestState, { + requireAdminAuth: true, + requireDomain: true, + }); + const requestedName = String(options.localPart || options.name || '').trim().toLowerCase() || generateCloudflareAliasLocalPart(); + const payload = { + enablePrefix: true, + name: requestedName, + domain: config.domain, + }; + const result = await requestCloudflareTempEmailJson(config, '/admin/new_address', { + method: 'POST', + payload, + }); + const address = normalizeCloudflareTempEmailAddress(getCloudflareTempEmailAddressFromResponse(result)); + if (!address) { + throw new Error('Cloudflare Temp Email 未返回可用邮箱地址。'); + } + + await setEmailState(address); + await addLog(`Cloudflare Temp Email:已生成 ${address}`, 'ok'); + return address; +} + async function fetchDuckEmail(options = {}) { throwIfStopped(); const { generateNew = true } = options; @@ -3508,6 +3776,9 @@ async function fetchGeneratedEmail(state, options = {}) { if (generator === 'cloudflare') { return fetchCloudflareEmail(currentState, options); } + if (generator === CLOUDFLARE_TEMP_EMAIL_GENERATOR) { + return fetchCloudflareTempEmailAddress(currentState, options); + } return fetchDuckEmail(options); } @@ -3610,7 +3881,10 @@ async function ensureAutoEmailReady(targetRun, totalRuns, attemptRuns) { } catch (err) { lastError = err; await addLog(`${generatorLabel}自动获取失败(${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS}):${err.message}`, 'warn'); - if (generator === 'cloudflare' && /域名/.test(String(err.message || ''))) { + if ( + (generator === 'cloudflare' && /域名/.test(String(err.message || ''))) + || (generator === CLOUDFLARE_TEMP_EMAIL_GENERATOR && /(服务地址|Admin Auth|域名)/.test(String(err.message || ''))) + ) { break; } } @@ -4732,6 +5006,9 @@ function getMailConfig(state) { if (provider === HOTMAIL_PROVIDER) { return { provider: HOTMAIL_PROVIDER, label: 'Hotmail(远程/本地)' }; } + if (provider === CLOUDFLARE_TEMP_EMAIL_PROVIDER) { + return { provider: CLOUDFLARE_TEMP_EMAIL_PROVIDER, label: 'Cloudflare Temp Email' }; + } if (provider === '163') { return { source: 'mail-163', url: 'https://mail.163.com/js6/main.jsp?df=mail163_letter#module=mbox.ListModule%7C%7B%22fid%22%3A1%2C%22order%22%3A%22date%22%2C%22desc%22%3Atrue%7D', label: '163 邮箱' }; } @@ -4896,6 +5173,12 @@ async function pollFreshVerificationCode(step, state, mail, pollOverrides = {}) ...pollOverrides, }); } + if (mail.provider === CLOUDFLARE_TEMP_EMAIL_PROVIDER) { + return pollCloudflareTempEmailVerificationCode(step, state, { + ...getVerificationPollPayload(step, state), + ...pollOverrides, + }); + } const stateKey = getVerificationCodeStateKey(step); const rejectedCodes = new Set(); @@ -5111,7 +5394,7 @@ async function executeStep4(state) { } throwIfStopped(); - if (mail.provider === HOTMAIL_PROVIDER) { + if (mail.provider === HOTMAIL_PROVIDER || mail.provider === CLOUDFLARE_TEMP_EMAIL_PROVIDER) { await addLog(`步骤 4:正在通过 ${mail.label} 轮询验证码...`); } else { await addLog(`步骤 4:正在打开${mail.label}...`); @@ -5246,7 +5529,7 @@ async function runStep7Attempt(state) { } throwIfStopped(); - if (mail.provider === HOTMAIL_PROVIDER) { + if (mail.provider === HOTMAIL_PROVIDER || mail.provider === CLOUDFLARE_TEMP_EMAIL_PROVIDER) { await addLog(`步骤 7:正在通过 ${mail.label} 轮询验证码...`); } else { await addLog(`步骤 7:正在打开${mail.label}...`); diff --git a/cloudflare-temp-email-utils.js b/cloudflare-temp-email-utils.js new file mode 100644 index 0000000..e7a8992 --- /dev/null +++ b/cloudflare-temp-email-utils.js @@ -0,0 +1,400 @@ +(function cloudflareTempEmailUtilsModule(root, factory) { + if (typeof module !== 'undefined' && module.exports) { + module.exports = factory(); + return; + } + + root.CloudflareTempEmailUtils = factory(); +})(typeof self !== 'undefined' ? self : globalThis, function createCloudflareTempEmailUtils() { + const DEFAULT_MAIL_PAGE_SIZE = 20; + + function firstNonEmptyString(values) { + for (const value of values) { + if (value === undefined || value === null) continue; + const normalized = String(value).trim(); + if (normalized) return normalized; + } + return ''; + } + + function normalizeCloudflareTempEmailBaseUrl(rawValue = '') { + const value = String(rawValue || '').trim(); + if (!value) return ''; + + const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(value) ? value : `https://${value}`; + try { + const parsed = new URL(candidate); + parsed.hash = ''; + parsed.search = ''; + const pathname = parsed.pathname === '/' ? '' : parsed.pathname.replace(/\/+$/, ''); + return `${parsed.origin}${pathname}`; + } catch { + return ''; + } + } + + function normalizeCloudflareTempEmailDomain(rawValue = '') { + let value = String(rawValue || '').trim().toLowerCase(); + if (!value) return ''; + value = value.replace(/^@+/, ''); + value = value.replace(/^https?:\/\//, ''); + value = value.replace(/\/.*$/, ''); + if (!/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(value)) { + return ''; + } + return value; + } + + function normalizeCloudflareTempEmailDomains(values) { + const domains = []; + const seen = new Set(); + for (const value of Array.isArray(values) ? values : []) { + const normalized = normalizeCloudflareTempEmailDomain(value); + if (!normalized || seen.has(normalized)) continue; + seen.add(normalized); + domains.push(normalized); + } + return domains; + } + + function buildCloudflareTempEmailHeaders(config = {}, options = {}) { + const headers = {}; + const adminAuth = firstNonEmptyString([config.adminAuth, config.cloudflareTempEmailAdminAuth]); + const customAuth = firstNonEmptyString([config.customAuth, config.cloudflareTempEmailCustomAuth]); + if (adminAuth) { + headers['x-admin-auth'] = adminAuth; + } + if (customAuth) { + headers['x-custom-auth'] = customAuth; + } + if (options.json) { + headers['Content-Type'] = 'application/json'; + } + if (options.acceptJson !== false) { + headers.Accept = 'application/json'; + } + return headers; + } + + function joinCloudflareTempEmailUrl(baseUrl, path) { + const normalizedBase = normalizeCloudflareTempEmailBaseUrl(baseUrl); + const normalizedPath = String(path || '').trim(); + if (!normalizedBase || !normalizedPath) return normalizedBase || ''; + return `${normalizedBase}${normalizedPath.startsWith('/') ? '' : '/'}${normalizedPath}`; + } + + function getCloudflareTempEmailMailRows(payload) { + if (Array.isArray(payload)) return payload; + if (!payload || typeof payload !== 'object') return []; + + const candidates = [ + payload.data, + payload.items, + payload.messages, + payload.mails, + payload.results, + payload.rows, + ]; + + for (const candidate of candidates) { + if (Array.isArray(candidate)) { + return candidate; + } + } + + return []; + } + + function normalizeCloudflareTempEmailAddress(value) { + return String(value || '').trim().toLowerCase(); + } + + function splitRawMessage(raw = '') { + const source = String(raw || ''); + if (!source) { + return { headerText: '', bodyText: '' }; + } + + const normalized = source.replace(/\r\n/g, '\n'); + const separatorIndex = normalized.indexOf('\n\n'); + if (separatorIndex === -1) { + return { headerText: normalized, bodyText: '' }; + } + + return { + headerText: normalized.slice(0, separatorIndex), + bodyText: normalized.slice(separatorIndex + 2), + }; + } + + function parseRawHeaders(headerText = '') { + const headers = {}; + const lines = String(headerText || '').split('\n'); + let currentName = ''; + + for (const line of lines) { + if (!line) continue; + if ((line.startsWith(' ') || line.startsWith('\t')) && currentName) { + headers[currentName] += ` ${line.trim()}`; + continue; + } + + const separatorIndex = line.indexOf(':'); + if (separatorIndex <= 0) continue; + currentName = line.slice(0, separatorIndex).trim().toLowerCase(); + headers[currentName] = line.slice(separatorIndex + 1).trim(); + } + + return headers; + } + + function decodeMimeEncodedWords(value = '') { + const source = String(value || ''); + return source.replace(/=\?([^?]+)\?([bBqQ])\?([^?]+)\?=/g, (_match, charset, encoding, encodedText) => { + try { + if (String(encoding).toUpperCase() === 'B') { + return decodeBytesToString(base64ToBytes(encodedText), charset); + } + return decodeBytesToString( + quotedPrintableToBytes(String(encodedText).replace(/_/g, ' '), { headerMode: true }), + charset + ); + } catch { + return encodedText; + } + }); + } + + function base64ToBytes(value = '') { + const normalized = String(value || '').replace(/\s+/g, ''); + if (!normalized) return new Uint8Array(); + + if (typeof atob === 'function') { + const decoded = atob(normalized); + const bytes = new Uint8Array(decoded.length); + for (let i = 0; i < decoded.length; i += 1) { + bytes[i] = decoded.charCodeAt(i); + } + return bytes; + } + + if (typeof Buffer !== 'undefined') { + return Uint8Array.from(Buffer.from(normalized, 'base64')); + } + + throw new Error('No base64 decoder available'); + } + + function quotedPrintableToBytes(value = '', options = {}) { + const { headerMode = false } = options; + const source = String(value || '') + .replace(/=\r?\n/g, '') + .replace(headerMode ? /_/g : /$^/, ' '); + + const bytes = []; + for (let index = 0; index < source.length; index += 1) { + const char = source[index]; + if (char === '=' && /^[0-9A-Fa-f]{2}$/.test(source.slice(index + 1, index + 3))) { + bytes.push(parseInt(source.slice(index + 1, index + 3), 16)); + index += 2; + continue; + } + bytes.push(char.charCodeAt(0)); + } + return Uint8Array.from(bytes); + } + + function decodeBytesToString(bytes, charset = 'utf-8') { + const normalizedCharset = String(charset || 'utf-8').trim().toLowerCase(); + const candidates = [normalizedCharset]; + if (normalizedCharset === 'utf8') { + candidates.unshift('utf-8'); + } + if (normalizedCharset === 'gb2312' || normalizedCharset === 'gbk') { + candidates.unshift('gb18030'); + } + + for (const candidate of candidates) { + try { + if (typeof TextDecoder !== 'undefined') { + return new TextDecoder(candidate, { fatal: false }).decode(bytes); + } + } catch { + // ignore and try fallback + } + } + + if (typeof Buffer !== 'undefined') { + return Buffer.from(bytes).toString('utf8'); + } + + let result = ''; + for (const byte of bytes) { + result += String.fromCharCode(byte); + } + return result; + } + + function getCharsetFromContentType(contentType = '') { + const match = String(contentType || '').match(/charset="?([^";]+)"?/i); + return match ? match[1].trim() : 'utf-8'; + } + + function getBoundaryFromContentType(contentType = '') { + const match = String(contentType || '').match(/boundary="?([^";]+)"?/i); + return match ? match[1] : ''; + } + + function stripHtmlTags(value = '') { + return String(value || '') + .replace(//gi, ' ') + .replace(//gi, ' ') + .replace(/<[^>]+>/g, ' ') + .replace(/ /gi, ' ') + .replace(/&/gi, '&') + .replace(/</gi, '<') + .replace(/>/gi, '>') + .replace(/\s+/g, ' ') + .trim(); + } + + function decodeMimeBody(bodyText = '', headers = {}) { + const contentType = String(headers['content-type'] || ''); + const transferEncoding = String(headers['content-transfer-encoding'] || '').trim().toLowerCase(); + const charset = getCharsetFromContentType(contentType); + let decoded = String(bodyText || ''); + + if (transferEncoding === 'base64') { + decoded = decodeBytesToString(base64ToBytes(decoded), charset); + } else if (transferEncoding === 'quoted-printable') { + decoded = decodeBytesToString(quotedPrintableToBytes(decoded), charset); + } + + if (/text\/html/i.test(contentType)) { + return stripHtmlTags(decoded); + } + return decoded.replace(/\s+/g, ' ').trim(); + } + + function extractTextFromMime(rawMessage = '', depth = 0) { + const { headerText, bodyText } = splitRawMessage(rawMessage); + const headers = parseRawHeaders(headerText); + const contentType = String(headers['content-type'] || ''); + const boundary = getBoundaryFromContentType(contentType); + + if (/multipart\//i.test(contentType) && boundary && depth < 6) { + const marker = `--${boundary}`; + const sections = String(bodyText || '') + .split(marker) + .map((part) => part.trim()) + .filter((part) => part && part !== '--'); + + const extractedParts = sections + .map((part) => part.replace(/--\s*$/, '').trim()) + .map((part) => extractTextFromMime(part, depth + 1)?.text || '') + .filter(Boolean); + + const plainText = extractedParts.join(' ').replace(/\s+/g, ' ').trim(); + return { + headers, + text: plainText, + }; + } + + return { + headers, + text: decodeMimeBody(bodyText, headers), + }; + } + + function normalizeReceivedDateTime(value) { + if (!value && value !== 0) return ''; + if (typeof value === 'number' && Number.isFinite(value)) { + return new Date(value).toISOString(); + } + const source = String(value || '').trim(); + if (!source) return ''; + const parsed = Date.parse(source); + return Number.isFinite(parsed) ? new Date(parsed).toISOString() : source; + } + + function normalizeCloudflareTempEmailMessage(row = {}) { + if (!row || typeof row !== 'object') return null; + + const address = normalizeCloudflareTempEmailAddress(firstNonEmptyString([ + row.address, + row.mail_address, + row.email, + row.recipient, + ])); + const raw = firstNonEmptyString([row.raw, row.source, row.mime, row.message]); + const parsedMime = raw ? extractTextFromMime(raw) : { headers: {}, text: '' }; + const subject = decodeMimeEncodedWords(firstNonEmptyString([ + row.subject, + parsedMime.headers.subject, + ])); + const fromAddress = decodeMimeEncodedWords(firstNonEmptyString([ + row.from, + row.sender, + row.mail_from, + parsedMime.headers.from, + ])); + const bodyPreview = firstNonEmptyString([ + row.text, + row.preview, + row.body, + parsedMime.text, + raw, + ]).replace(/\s+/g, ' ').trim(); + + return { + id: firstNonEmptyString([row.id, row.mail_id]), + address, + addressId: firstNonEmptyString([row.address_id, row.addressId]), + subject, + from: { + emailAddress: { + address: fromAddress, + }, + }, + bodyPreview, + raw, + receivedDateTime: normalizeReceivedDateTime(firstNonEmptyString([ + row.receivedDateTime, + row.received_at, + row.created_at, + row.createdAt, + row.updated_at, + row.date, + ])), + }; + } + + function normalizeCloudflareTempEmailMailApiMessages(payload) { + return getCloudflareTempEmailMailRows(payload) + .map((row) => normalizeCloudflareTempEmailMessage(row)) + .filter(Boolean); + } + + function getCloudflareTempEmailAddressFromResponse(payload = {}) { + return firstNonEmptyString([ + payload.address, + payload.email, + payload?.data?.address, + payload?.data?.email, + ]); + } + + return { + DEFAULT_MAIL_PAGE_SIZE, + buildCloudflareTempEmailHeaders, + getCloudflareTempEmailAddressFromResponse, + joinCloudflareTempEmailUrl, + normalizeCloudflareTempEmailAddress, + normalizeCloudflareTempEmailBaseUrl, + normalizeCloudflareTempEmailDomain, + normalizeCloudflareTempEmailDomains, + normalizeCloudflareTempEmailMailApiMessages, + normalizeCloudflareTempEmailMessage, + }; +}); diff --git a/sidepanel/sidepanel.html b/sidepanel/sidepanel.html index 944b7e7..45ba375 100644 --- a/sidepanel/sidepanel.html +++ b/sidepanel/sidepanel.html @@ -159,6 +159,7 @@ + @@ -168,8 +169,30 @@ + + + + +
就绪 diff --git a/sidepanel/sidepanel.js b/sidepanel/sidepanel.js index e9d0405..2b6773f 100644 --- a/sidepanel/sidepanel.js +++ b/sidepanel/sidepanel.js @@ -79,6 +79,26 @@ const selectTempEmailDomain = document.getElementById('select-temp-email-domain' const inputTempEmailDomain = document.getElementById('input-temp-email-domain'); const btnTempEmailDomainMode = document.getElementById('btn-temp-email-domain-mode'); const hotmailSection = document.getElementById('hotmail-section'); +const icloudSection = document.getElementById('icloud-section'); +const icloudSummary = document.getElementById('icloud-summary'); +const icloudList = document.getElementById('icloud-list'); +const icloudLoginHelp = document.getElementById('icloud-login-help'); +const icloudLoginHelpTitle = document.getElementById('icloud-login-help-title'); +const icloudLoginHelpText = document.getElementById('icloud-login-help-text'); +const btnIcloudLoginDone = document.getElementById('btn-icloud-login-done'); +const btnIcloudRefresh = document.getElementById('btn-icloud-refresh'); +const btnIcloudDeleteUsed = document.getElementById('btn-icloud-delete-used'); +const selectIcloudHostPreference = document.getElementById('select-icloud-host-preference'); +const checkboxAutoDeleteIcloud = document.getElementById('checkbox-auto-delete-icloud'); +const inputIcloudSearch = document.getElementById('input-icloud-search'); +const selectIcloudFilter = document.getElementById('select-icloud-filter'); +const checkboxIcloudSelectAll = document.getElementById('checkbox-icloud-select-all'); +const icloudSelectionSummary = document.getElementById('icloud-selection-summary'); +const btnIcloudBulkUsed = document.getElementById('btn-icloud-bulk-used'); +const btnIcloudBulkUnused = document.getElementById('btn-icloud-bulk-unused'); +const btnIcloudBulkPreserve = document.getElementById('btn-icloud-bulk-preserve'); +const btnIcloudBulkUnpreserve = document.getElementById('btn-icloud-bulk-unpreserve'); +const btnIcloudBulkDelete = document.getElementById('btn-icloud-bulk-delete'); const rowHotmailServiceMode = document.getElementById('row-hotmail-service-mode'); const hotmailServiceModeButtons = Array.from(document.querySelectorAll('[data-hotmail-service-mode]')); const rowHotmailRemoteBaseUrl = document.getElementById('row-hotmail-remote-base-url'); @@ -174,6 +194,11 @@ let settingsSaveInFlight = false; let settingsAutoSaveTimer = null; let cloudflareDomainEditMode = false; let cloudflareTempEmailDomainEditMode = false; +let icloudRefreshQueued = false; +let lastRenderedIcloudAliases = []; +let icloudSelectedEmails = new Set(); +let icloudSearchTerm = ''; +let icloudFilterMode = 'all'; let modalChoiceResolver = null; let currentModalActions = []; let modalResultBuilder = null; @@ -1032,6 +1057,8 @@ function collectSettingsPayload() { customPassword: inputPassword.value, mailProvider: selectMailProvider.value, emailGenerator: selectEmailGenerator.value, + autoDeleteUsedIcloudAlias: checkboxAutoDeleteIcloud?.checked, + icloudHostPreference: selectIcloudHostPreference?.value || 'auto', emailPrefix: inputEmailPrefix.value.trim(), inbucketHost: inputInbucketHost.value.trim(), inbucketMailbox: inputInbucketMailbox.value.trim(), @@ -1323,10 +1350,26 @@ function applySettingsState(state) { ? 'custom' : '163'); selectMailProvider.value = restoredMailProvider; - const restoredEmailGenerator = String(state?.emailGenerator || '').trim().toLowerCase(); - selectEmailGenerator.value = ['cloudflare', 'cloudflare-temp-email'].includes(restoredEmailGenerator) - ? restoredEmailGenerator - : 'duck'; + { + const restoredGenerator = String(state?.emailGenerator || '').trim().toLowerCase(); + if (restoredGenerator === 'icloud') { + selectEmailGenerator.value = 'icloud'; + } else if (restoredGenerator === 'cloudflare') { + selectEmailGenerator.value = 'cloudflare'; + } else if (restoredGenerator === 'cloudflare-temp-email') { + selectEmailGenerator.value = 'cloudflare-temp-email'; + } else { + selectEmailGenerator.value = 'duck'; + } + } + if (selectIcloudHostPreference) { + selectIcloudHostPreference.value = String(state?.icloudHostPreference || '').trim().toLowerCase() === 'icloud.com' + ? 'icloud.com' + : (String(state?.icloudHostPreference || '').trim().toLowerCase() === 'icloud.com.cn' ? 'icloud.com.cn' : 'auto'); + } + if (checkboxAutoDeleteIcloud) { + checkboxAutoDeleteIcloud.checked = Boolean(state?.autoDeleteUsedIcloudAlias); + } inputEmailPrefix.value = state?.emailPrefix || ''; inputInbucketHost.value = state?.inbucketHost || ''; inputInbucketMailbox.value = state?.inbucketMailbox || ''; @@ -1362,6 +1405,9 @@ async function restoreState() { try { const state = await chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }); applySettingsState(state); + if (getSelectedEmailGenerator() === 'icloud' && icloudSection?.style.display !== 'none') { + refreshIcloudAliases({ silent: true }).catch(() => { }); + } if (state.oauthUrl) { displayOauthUrl.textContent = state.oauthUrl; @@ -1609,6 +1655,9 @@ function getSelectedEmailGenerator() { if (generator === 'custom' || generator === 'manual') { return 'custom'; } + if (generator === 'icloud') { + return 'icloud'; + } if (generator === 'cloudflare') return 'cloudflare'; if (generator === 'cloudflare-temp-email') return 'cloudflare-temp-email'; return 'duck'; @@ -1618,6 +1667,14 @@ function getEmailGeneratorUiCopy() { if (getSelectedEmailGenerator() === 'custom') { return getCustomMailProviderUiCopy(); } + if (getSelectedEmailGenerator() === 'icloud') { + return { + buttonLabel: '获取', + placeholder: '点击获取 iCloud 隐私邮箱,或手动粘贴邮箱', + successVerb: '获取', + label: 'iCloud 隐私邮箱', + }; + } if (getSelectedEmailGenerator() === 'cloudflare') { return { buttonLabel: '生成', @@ -1946,14 +2003,26 @@ function updateMailProviderUI() { const hotmailServiceMode = getSelectedHotmailServiceMode(); rowInbucketHost.style.display = useInbucket ? '' : 'none'; rowInbucketMailbox.style.display = useInbucket ? '' : 'none'; - const useCloudflare = selectEmailGenerator.value === 'cloudflare'; - const useCloudflareTempEmailGenerator = selectEmailGenerator.value === 'cloudflare-temp-email'; + const selectedGenerator = getSelectedEmailGenerator(); + const useCloudflare = selectedGenerator === 'cloudflare'; + const useIcloud = selectedGenerator === 'icloud'; + const useCloudflareTempEmailGenerator = selectedGenerator === 'cloudflare-temp-email'; const showCloudflareDomain = useEmailGenerator && useCloudflare; const showCloudflareTempEmailSettings = useCloudflareTempEmailProvider || (useEmailGenerator && useCloudflareTempEmailGenerator); const showCloudflareTempEmailDomain = useEmailGenerator && useCloudflareTempEmailGenerator; if (rowEmailGenerator) { rowEmailGenerator.style.display = useEmailGenerator ? '' : 'none'; } + if (icloudSection) { + const showIcloudSection = useEmailGenerator && useIcloud; + icloudSection.style.display = showIcloudSection ? '' : 'none'; + if (showIcloudSection && !lastRenderedIcloudAliases.length) { + queueIcloudAliasRefresh(); + } + if (!showIcloudSection) { + hideIcloudLoginHelp(); + } + } rowCfDomain.style.display = showCloudflareDomain ? '' : 'none'; const { domains } = getCloudflareDomainsFromState(); if (showCloudflareDomain) { @@ -2002,7 +2071,7 @@ function updateMailProviderUI() { ? '请先校验并选择一个 Hotmail 账号' : (useGeneratedAlias ? '步骤 3 会自动生成邮箱,无需手动获取' - : (useCustomEmail ? '请先填写自定义注册邮箱,成功一轮后会自动清空' : '先自动获取邮箱,或手动粘贴邮箱后再继续')); + : (useCustomEmail ? '请先填写自定义注册邮箱,成功一轮后会自动清空' : `先自动获取${uiCopy.label},或手动粘贴邮箱后再继续`)); } if (useHotmail) { inputEmail.value = getCurrentHotmailEmail(); @@ -2166,6 +2235,11 @@ function updateButtonStates() { }); btnReset.disabled = anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked; + const disableIcloudControls = anyRunning || autoScheduled || autoLocked; + if (btnIcloudRefresh) btnIcloudRefresh.disabled = disableIcloudControls; + if (btnIcloudDeleteUsed) btnIcloudDeleteUsed.disabled = disableIcloudControls || !(lastRenderedIcloudAliases.some((alias) => alias.used && !alias.preserved)); + if (selectIcloudHostPreference) selectIcloudHostPreference.disabled = disableIcloudControls; + if (checkboxAutoDeleteIcloud) checkboxAutoDeleteIcloud.disabled = disableIcloudControls; updateStopButtonState(anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked); } @@ -2288,6 +2362,375 @@ function escapeHtml(text) { return div.innerHTML; } +function normalizeIcloudSearchText(value) { + return String(value || '').trim().toLowerCase(); +} + +function getFilteredIcloudAliases(aliases = lastRenderedIcloudAliases) { + const searchTerm = normalizeIcloudSearchText(icloudSearchTerm); + return (Array.isArray(aliases) ? aliases : []).filter((alias) => { + const matchesFilter = (() => { + switch (icloudFilterMode) { + case 'active': return Boolean(alias.active); + case 'used': return Boolean(alias.used); + case 'unused': return !alias.used; + case 'preserved': return Boolean(alias.preserved); + default: return true; + } + })(); + + if (!matchesFilter) return false; + if (!searchTerm) return true; + + const haystack = [ + alias.email, + alias.label, + alias.note, + alias.used ? '已用 used' : '未用 unused', + alias.active ? '可用 active' : '不可用 inactive', + alias.preserved ? '保留 preserved' : '', + ].join(' ').toLowerCase(); + + return haystack.includes(searchTerm); + }); +} + +function pruneIcloudSelection(aliases = lastRenderedIcloudAliases) { + const existing = new Set((Array.isArray(aliases) ? aliases : []).map((alias) => alias.email)); + icloudSelectedEmails = new Set([...icloudSelectedEmails].filter((email) => existing.has(email))); +} + +function updateIcloudBulkUI(visibleAliases = getFilteredIcloudAliases()) { + if (!checkboxIcloudSelectAll || !icloudSelectionSummary) { + return; + } + + const visibleEmails = visibleAliases.map((alias) => alias.email); + const selectedVisibleCount = visibleEmails.filter((email) => icloudSelectedEmails.has(email)).length; + const hasVisible = visibleEmails.length > 0; + + checkboxIcloudSelectAll.checked = hasVisible && selectedVisibleCount === visibleEmails.length; + checkboxIcloudSelectAll.indeterminate = selectedVisibleCount > 0 && selectedVisibleCount < visibleEmails.length; + checkboxIcloudSelectAll.disabled = !hasVisible; + icloudSelectionSummary.textContent = `已选 ${icloudSelectedEmails.size} 个(当前显示 ${visibleEmails.length} 个)`; + + const hasSelection = icloudSelectedEmails.size > 0; + if (btnIcloudBulkUsed) btnIcloudBulkUsed.disabled = !hasSelection; + if (btnIcloudBulkUnused) btnIcloudBulkUnused.disabled = !hasSelection; + if (btnIcloudBulkPreserve) btnIcloudBulkPreserve.disabled = !hasSelection; + if (btnIcloudBulkUnpreserve) btnIcloudBulkUnpreserve.disabled = !hasSelection; + if (btnIcloudBulkDelete) btnIcloudBulkDelete.disabled = !hasSelection; +} + +function setIcloudLoadingState(loading, summary = '') { + if (btnIcloudRefresh) btnIcloudRefresh.disabled = loading; + if (btnIcloudDeleteUsed) btnIcloudDeleteUsed.disabled = loading; + if (btnIcloudLoginDone) btnIcloudLoginDone.disabled = loading; + if (inputIcloudSearch) inputIcloudSearch.disabled = loading; + if (selectIcloudFilter) selectIcloudFilter.disabled = loading; + if (checkboxIcloudSelectAll) checkboxIcloudSelectAll.disabled = loading || getFilteredIcloudAliases().length === 0; + if (btnIcloudBulkUsed) btnIcloudBulkUsed.disabled = loading || icloudSelectedEmails.size === 0; + if (btnIcloudBulkUnused) btnIcloudBulkUnused.disabled = loading || icloudSelectedEmails.size === 0; + if (btnIcloudBulkPreserve) btnIcloudBulkPreserve.disabled = loading || icloudSelectedEmails.size === 0; + if (btnIcloudBulkUnpreserve) btnIcloudBulkUnpreserve.disabled = loading || icloudSelectedEmails.size === 0; + if (btnIcloudBulkDelete) btnIcloudBulkDelete.disabled = loading || icloudSelectedEmails.size === 0; + if (summary && icloudSummary) icloudSummary.textContent = summary; +} + +function showIcloudLoginHelp(payload = {}) { + if (!icloudLoginHelp) return; + const loginUrl = String(payload.loginUrl || '').trim(); + const host = loginUrl ? new URL(loginUrl).host : 'icloud.com.cn / icloud.com'; + if (icloudLoginHelpTitle) icloudLoginHelpTitle.textContent = '需要登录 iCloud'; + if (icloudLoginHelpText) icloudLoginHelpText.textContent = `我已经为你打开 ${host}。请在那个页面完成登录,然后回到这里点击“我已登录”。`; + icloudLoginHelp.style.display = 'flex'; +} + +function hideIcloudLoginHelp() { + if (icloudLoginHelp) { + icloudLoginHelp.style.display = 'none'; + } +} + +function renderIcloudAliases(aliases = []) { + if (!icloudList || !icloudSummary) return; + + lastRenderedIcloudAliases = Array.isArray(aliases) ? aliases : []; + pruneIcloudSelection(lastRenderedIcloudAliases); + icloudList.innerHTML = ''; + + if (!aliases.length) { + icloudSelectedEmails.clear(); + icloudList.innerHTML = '
未找到 iCloud Hide My Email 别名。
'; + icloudSummary.textContent = '加载你的 iCloud Hide My Email 别名以便在这里管理。'; + if (btnIcloudDeleteUsed) btnIcloudDeleteUsed.disabled = true; + updateIcloudBulkUI([]); + return; + } + + const usedCount = aliases.filter((alias) => alias.used).length; + const deletableUsedCount = aliases.filter((alias) => alias.used && !alias.preserved).length; + icloudSummary.textContent = `已加载 ${aliases.length} 个别名,其中 ${usedCount} 个已标记为已用。`; + if (btnIcloudDeleteUsed) btnIcloudDeleteUsed.disabled = deletableUsedCount === 0; + + const visibleAliases = getFilteredIcloudAliases(aliases); + if (!visibleAliases.length) { + icloudList.innerHTML = '
没有匹配当前筛选条件的别名。
'; + updateIcloudBulkUI([]); + return; + } + + for (const alias of visibleAliases) { + const item = document.createElement('div'); + item.className = 'icloud-item'; + item.innerHTML = ` + +
+ +
+ ${alias.used ? '已用' : ''} + ${!alias.used && alias.active ? '可用' : ''} + ${alias.preserved ? '保留' : ''} + ${alias.label ? `${escapeHtml(alias.label)}` : ''} + ${alias.note ? `${escapeHtml(alias.note)}` : ''} +
+
+
+ + + +
+ `; + + item.querySelector('[data-action="select"]').addEventListener('change', (event) => { + if (event.target.checked) { + icloudSelectedEmails.add(alias.email); + } else { + icloudSelectedEmails.delete(alias.email); + } + updateIcloudBulkUI(visibleAliases); + }); + item.querySelector('[data-action="toggle-used"]').addEventListener('click', async () => { + await setSingleIcloudAliasUsedState(alias, !alias.used); + }); + item.querySelector('[data-action="toggle-preserved"]').addEventListener('click', async () => { + await setSingleIcloudAliasPreservedState(alias, !alias.preserved); + }); + item.querySelector('[data-action="delete"]').addEventListener('click', async () => { + await deleteSingleIcloudAlias(alias); + }); + icloudList.appendChild(item); + } + + updateIcloudBulkUI(visibleAliases); +} + +async function refreshIcloudAliases(options = {}) { + const { silent = false } = options; + if (!icloudSection || icloudSection.style.display === 'none') { + return; + } + + if (!silent) setIcloudLoadingState(true, '正在加载 iCloud 别名...'); + try { + const response = await chrome.runtime.sendMessage({ + type: 'LIST_ICLOUD_ALIASES', + source: 'sidepanel', + payload: {}, + }); + if (response?.error) throw new Error(response.error); + hideIcloudLoginHelp(); + renderIcloudAliases(response?.aliases || []); + } catch (err) { + icloudSelectedEmails.clear(); + if (icloudList) { + icloudList.innerHTML = '
无法加载 iCloud 别名。
'; + } + if (icloudSummary) { + icloudSummary.textContent = err.message; + } + updateIcloudBulkUI([]); + if (!silent) showToast(`iCloud 别名加载失败:${err.message}`, 'error'); + } finally { + setIcloudLoadingState(false); + } +} + +function queueIcloudAliasRefresh() { + if (icloudRefreshQueued) return; + icloudRefreshQueued = true; + setTimeout(async () => { + icloudRefreshQueued = false; + await refreshIcloudAliases({ silent: true }); + }, 150); +} + +async function deleteSingleIcloudAlias(alias) { + const confirmed = await openConfirmModal({ + title: '删除 iCloud 别名', + message: `确认删除 ${alias.email} 吗?此操作不可撤销。`, + confirmLabel: '确认删除', + confirmVariant: 'btn-danger', + }); + if (!confirmed) { + return; + } + + setIcloudLoadingState(true, `正在删除 ${alias.email} ...`); + try { + const response = await chrome.runtime.sendMessage({ + type: 'DELETE_ICLOUD_ALIAS', + source: 'sidepanel', + payload: { email: alias.email, anonymousId: alias.anonymousId }, + }); + if (response?.error) throw new Error(response.error); + showToast(`已删除 ${alias.email}`, 'success', 2200); + await refreshIcloudAliases({ silent: true }); + } catch (err) { + if (icloudSummary) icloudSummary.textContent = err.message; + showToast(`删除 iCloud 别名失败:${err.message}`, 'error'); + } finally { + setIcloudLoadingState(false); + } +} + +async function setSingleIcloudAliasUsedState(alias, used) { + setIcloudLoadingState(true, `正在更新 ${alias.email} 的使用状态...`); + try { + const response = await chrome.runtime.sendMessage({ + type: 'SET_ICLOUD_ALIAS_USED_STATE', + source: 'sidepanel', + payload: { email: alias.email, used }, + }); + if (response?.error) throw new Error(response.error); + showToast(`${alias.email} 已${used ? '标记为已用' : '恢复为未用'}`, 'success', 2200); + await refreshIcloudAliases({ silent: true }); + } catch (err) { + if (icloudSummary) icloudSummary.textContent = err.message; + showToast(`更新 iCloud 使用状态失败:${err.message}`, 'error'); + } finally { + setIcloudLoadingState(false); + } +} + +async function setSingleIcloudAliasPreservedState(alias, preserved) { + setIcloudLoadingState(true, `正在更新 ${alias.email} 的保留状态...`); + try { + const response = await chrome.runtime.sendMessage({ + type: 'SET_ICLOUD_ALIAS_PRESERVED_STATE', + source: 'sidepanel', + payload: { email: alias.email, preserved }, + }); + if (response?.error) throw new Error(response.error); + showToast(`${alias.email} 已${preserved ? '设为保留' : '取消保留'}`, 'success', 2200); + await refreshIcloudAliases({ silent: true }); + } catch (err) { + if (icloudSummary) icloudSummary.textContent = err.message; + showToast(`更新 iCloud 保留状态失败:${err.message}`, 'error'); + } finally { + setIcloudLoadingState(false); + } +} + +async function runBulkIcloudAction(action) { + const selectedAliases = lastRenderedIcloudAliases.filter((alias) => icloudSelectedEmails.has(alias.email)); + if (!selectedAliases.length) { + updateIcloudBulkUI(); + return; + } + + if (action === 'delete') { + const confirmed = await openConfirmModal({ + title: '批量删除 iCloud 别名', + message: `确认删除选中的 ${selectedAliases.length} 个 iCloud 别名吗?此操作不可撤销。`, + confirmLabel: '确认删除', + confirmVariant: 'btn-danger', + }); + if (!confirmed) { + return; + } + } + + const actionLabelMap = { + used: '标记已用', + unused: '标记未用', + preserve: '保留', + unpreserve: '取消保留', + delete: '删除', + }; + setIcloudLoadingState(true, `正在批量${actionLabelMap[action] || '处理'} iCloud 别名...`); + + try { + for (const alias of selectedAliases) { + let response = null; + if (action === 'used' || action === 'unused') { + response = await chrome.runtime.sendMessage({ + type: 'SET_ICLOUD_ALIAS_USED_STATE', + source: 'sidepanel', + payload: { email: alias.email, used: action === 'used' }, + }); + } else if (action === 'preserve' || action === 'unpreserve') { + response = await chrome.runtime.sendMessage({ + type: 'SET_ICLOUD_ALIAS_PRESERVED_STATE', + source: 'sidepanel', + payload: { email: alias.email, preserved: action === 'preserve' }, + }); + } else if (action === 'delete') { + response = await chrome.runtime.sendMessage({ + type: 'DELETE_ICLOUD_ALIAS', + source: 'sidepanel', + payload: { email: alias.email, anonymousId: alias.anonymousId }, + }); + icloudSelectedEmails.delete(alias.email); + } + + if (response?.error) { + throw new Error(response.error); + } + } + + showToast(`已批量${actionLabelMap[action] || '处理'} ${selectedAliases.length} 个 iCloud 别名`, 'success', 2400); + await refreshIcloudAliases({ silent: true }); + } catch (err) { + if (icloudSummary) icloudSummary.textContent = err.message; + showToast(`批量处理 iCloud 别名失败:${err.message}`, 'error'); + } finally { + setIcloudLoadingState(false); + updateIcloudBulkUI(); + } +} + +async function deleteUsedIcloudAliases() { + const confirmed = await openConfirmModal({ + title: '删除已用 iCloud 别名', + message: '确认删除所有未保留的已用 iCloud 别名吗?此操作不可撤销。', + confirmLabel: '确认删除', + confirmVariant: 'btn-danger', + }); + if (!confirmed) { + return; + } + + setIcloudLoadingState(true, '正在删除已用 iCloud 别名...'); + try { + const response = await chrome.runtime.sendMessage({ + type: 'DELETE_USED_ICLOUD_ALIASES', + source: 'sidepanel', + payload: {}, + }); + if (response?.error) throw new Error(response.error); + const deleted = response?.deleted || []; + const skipped = response?.skipped || []; + showToast(`已删除 ${deleted.length} 个已用别名,跳过 ${skipped.length} 个`, skipped.length ? 'warn' : 'success', 2800); + await refreshIcloudAliases({ silent: true }); + } catch (err) { + if (icloudSummary) icloudSummary.textContent = err.message; + showToast(`删除已用 iCloud 别名失败:${err.message}`, 'error'); + } finally { + setIcloudLoadingState(false); + } +} + async function fetchGeneratedEmail(options = {}) { const { showFailureToast = true } = options; const uiCopy = getEmailGeneratorUiCopy(); @@ -2316,6 +2759,9 @@ async function fetchGeneratedEmail(options = {}) { } inputEmail.value = response.email; + if (getSelectedEmailGenerator() === 'icloud') { + queueIcloudAliasRefresh(); + } showToast(`已${uiCopy.successVerb} ${uiCopy.label}:${response.email}`, 'success', 2500); return response.email; } catch (err) { @@ -2628,6 +3074,75 @@ btnFetchEmail.addEventListener('click', async () => { await fetchGeneratedEmail().catch(() => { }); }); +btnIcloudRefresh?.addEventListener('click', async () => { + await refreshIcloudAliases(); +}); + +btnIcloudDeleteUsed?.addEventListener('click', async () => { + await deleteUsedIcloudAliases(); +}); + +inputIcloudSearch?.addEventListener('input', () => { + icloudSearchTerm = inputIcloudSearch.value || ''; + renderIcloudAliases(lastRenderedIcloudAliases); +}); + +selectIcloudFilter?.addEventListener('change', () => { + icloudFilterMode = selectIcloudFilter.value || 'all'; + renderIcloudAliases(lastRenderedIcloudAliases); +}); + +checkboxIcloudSelectAll?.addEventListener('change', () => { + const visibleAliases = getFilteredIcloudAliases(); + if (checkboxIcloudSelectAll.checked) { + visibleAliases.forEach((alias) => icloudSelectedEmails.add(alias.email)); + } else { + visibleAliases.forEach((alias) => icloudSelectedEmails.delete(alias.email)); + } + renderIcloudAliases(lastRenderedIcloudAliases); +}); + +btnIcloudBulkUsed?.addEventListener('click', async () => { + await runBulkIcloudAction('used'); +}); + +btnIcloudBulkUnused?.addEventListener('click', async () => { + await runBulkIcloudAction('unused'); +}); + +btnIcloudBulkPreserve?.addEventListener('click', async () => { + await runBulkIcloudAction('preserve'); +}); + +btnIcloudBulkUnpreserve?.addEventListener('click', async () => { + await runBulkIcloudAction('unpreserve'); +}); + +btnIcloudBulkDelete?.addEventListener('click', async () => { + await runBulkIcloudAction('delete'); +}); + +btnIcloudLoginDone?.addEventListener('click', async () => { + btnIcloudLoginDone.disabled = true; + try { + const response = await chrome.runtime.sendMessage({ + type: 'CHECK_ICLOUD_SESSION', + source: 'sidepanel', + payload: {}, + }); + if (response?.error) { + throw new Error(response.error); + } + hideIcloudLoginHelp(); + showToast('iCloud 会话已恢复,别名列表已刷新。', 'success', 2600); + await refreshIcloudAliases({ silent: true }); + } catch (err) { + showToast(`看起来还没有登录完成:${err.message}`, 'warn', 4200); + } finally { + btnIcloudLoginDone.disabled = false; + } +}); + btnToggleHotmailList?.addEventListener('click', () => { setHotmailListExpanded(!hotmailListExpanded); }); @@ -3106,6 +3621,15 @@ btnReset.addEventListener('click', async () => { displayStatus.textContent = '就绪'; statusBar.className = 'status-bar'; logArea.innerHTML = ''; + icloudSelectedEmails.clear(); + lastRenderedIcloudAliases = []; + if (icloudList) { + icloudList.innerHTML = ''; + } + if (icloudSummary) { + icloudSummary.textContent = '加载你的 iCloud Hide My Email 别名以便在这里管理。'; + } + updateIcloudBulkUI([]); document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row'); document.querySelectorAll('.step-status').forEach(el => el.textContent = ''); setDefaultAutoRunButton(); @@ -3202,6 +3726,19 @@ selectEmailGenerator.addEventListener('change', () => { saveSettings({ silent: true }).catch(() => { }); }); +selectIcloudHostPreference?.addEventListener('change', () => { + markSettingsDirty(true); + saveSettings({ silent: true }).catch(() => { }); + if (getSelectedEmailGenerator() === 'icloud') { + queueIcloudAliasRefresh(); + } +}); + +checkboxAutoDeleteIcloud?.addEventListener('change', () => { + markSettingsDirty(true); + saveSettings({ silent: true }).catch(() => { }); +}); + selectPanelMode.addEventListener('change', () => { updatePanelModeUI(); markSettingsDirty(true); @@ -3502,6 +4039,11 @@ chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => { displayStatus.textContent = '就绪'; statusBar.className = 'status-bar'; logArea.innerHTML = ''; + icloudSelectedEmails.clear(); + lastRenderedIcloudAliases = []; + if (icloudList) icloudList.innerHTML = ''; + if (icloudSummary) icloudSummary.textContent = '加载你的 iCloud Hide My Email 别名以便在这里管理。'; + updateIcloudBulkUI([]); document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row'); document.querySelectorAll('.step-status').forEach(el => el.textContent = ''); syncAutoRunState({ @@ -3559,6 +4101,15 @@ chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => { inputEmail.value = getCurrentHotmailEmail(); } } + if (message.payload.autoDeleteUsedIcloudAlias !== undefined && checkboxAutoDeleteIcloud) { + checkboxAutoDeleteIcloud.checked = Boolean(message.payload.autoDeleteUsedIcloudAlias); + } + if (message.payload.icloudHostPreference !== undefined && selectIcloudHostPreference) { + const hostPreference = String(message.payload.icloudHostPreference || '').trim().toLowerCase(); + selectIcloudHostPreference.value = hostPreference === 'icloud.com' + ? 'icloud.com' + : (hostPreference === 'icloud.com.cn' ? 'icloud.com.cn' : 'auto'); + } if (message.payload.autoRunSkipFailures !== undefined) { inputAutoSkipFailures.checked = Boolean(message.payload.autoRunSkipFailures); updateFallbackThreadIntervalInputState(); @@ -3582,6 +4133,21 @@ chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => { break; } + case 'ICLOUD_LOGIN_REQUIRED': { + const loginMessage = '需要登录 iCloud,我已经为你打开登录页。'; + showToast(loginMessage, 'warn', 5000); + if (icloudSummary) { + icloudSummary.textContent = loginMessage; + } + showIcloudLoginHelp(message.payload || {}); + break; + } + + case 'ICLOUD_ALIASES_CHANGED': { + queueIcloudAliasRefresh(); + break; + } + case 'AUTO_RUN_STATUS': { syncLatestState({ autoRunning: ['scheduled', 'running', 'waiting_step', 'waiting_email', 'retrying', 'waiting_interval'].includes(message.payload.phase), diff --git a/tests/auto-run-fresh-attempt-reset.test.js b/tests/auto-run-fresh-attempt-reset.test.js index 3c8622a..91533ea 100644 --- a/tests/auto-run-fresh-attempt-reset.test.js +++ b/tests/auto-run-fresh-attempt-reset.test.js @@ -189,6 +189,20 @@ function cancelPendingCommands() {} function normalizeAutoRunFallbackThreadIntervalMinutes(value) { return Math.max(0, Math.floor(Number(value) || 0)); } +function buildAutoRunRoundSummaries(totalRuns, rawSummaries = []) { + return Array.from({ length: totalRuns }, (_, index) => ({ + round: index + 1, + status: rawSummaries[index]?.status || 'pending', + attempts: rawSummaries[index]?.attempts || 0, + failureReasons: [...(rawSummaries[index]?.failureReasons || [])], + finalFailureReason: rawSummaries[index]?.finalFailureReason || '', + })); +} +function serializeAutoRunRoundSummaries(totalRuns, roundSummaries = []) { + return buildAutoRunRoundSummaries(totalRuns, roundSummaries); +} +async function logAutoRunFinalSummary() {} +async function waitBetweenAutoRunRounds() {} const chrome = { runtime: { diff --git a/tests/background-icloud.test.js b/tests/background-icloud.test.js new file mode 100644 index 0000000..c7f26db --- /dev/null +++ b/tests/background-icloud.test.js @@ -0,0 +1,265 @@ +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); +} + +const bundle = [ + extractFunction('normalizeEmailGenerator'), + extractFunction('getEmailGeneratorLabel'), + extractFunction('normalizePersistentSettingValue'), + extractFunction('finalizeIcloudAliasAfterSuccessfulFlow'), +].join('\n'); + +function createApi(overrides = {}) { + return new Function('overrides', ` +const HOTMAIL_PROVIDER = 'hotmail-api'; +const HOTMAIL_SERVICE_MODE_LOCAL = 'local'; +const CLOUDFLARE_TEMP_EMAIL_GENERATOR = 'cloudflare-temp-email'; +const DEFAULT_LOCAL_CPA_STEP9_MODE = 'submit'; +const DEFAULT_HOTMAIL_REMOTE_BASE_URL = ''; +const DEFAULT_HOTMAIL_LOCAL_BASE_URL = 'http://127.0.0.1:17373'; +const PERSISTED_SETTING_DEFAULTS = { + mailProvider: '163', + autoStepDelaySeconds: null, +}; + +const calls = { + setUsed: [], + logs: [], + deletes: [], + listCalls: 0, +}; + +function normalizeIcloudHost(value) { + const normalized = String(value || '').trim().toLowerCase(); + return ['icloud.com', 'icloud.com.cn'].includes(normalized) ? normalized : ''; +} +function normalizePanelMode(value = '') { + return String(value || '').trim().toLowerCase() === 'sub2api' ? 'sub2api' : 'cpa'; +} +function normalizeMailProvider(value = '') { + return String(value || '').trim().toLowerCase() || '163'; +} +function normalizeAutoRunFallbackThreadIntervalMinutes(value) { + return Math.max(0, Math.floor(Number(value) || 0)); +} +function normalizeAutoRunDelayMinutes(value) { + return Math.max(1, Math.floor(Number(value) || 30)); +} +function normalizeAutoStepDelaySeconds(value, fallback = null) { + const numeric = Number(value); + return Number.isFinite(numeric) ? Math.max(0, Math.floor(numeric)) : fallback; +} +function normalizeHotmailServiceMode() { + return HOTMAIL_SERVICE_MODE_LOCAL; +} +function normalizeHotmailRemoteBaseUrl(value = '') { + return String(value || '').trim() || DEFAULT_HOTMAIL_REMOTE_BASE_URL; +} +function normalizeHotmailLocalBaseUrl(value = '') { + return String(value || '').trim() || DEFAULT_HOTMAIL_LOCAL_BASE_URL; +} +function normalizeCloudflareDomain(value = '') { + return String(value || '').trim().toLowerCase(); +} +function normalizeCloudflareDomains(values = []) { + return Array.isArray(values) ? values : []; +} +function normalizeHotmailAccounts(values = []) { + return Array.isArray(values) ? values : []; +} +function getManualAliasUsageMap(state) { + return { ...(state?.manualAliasUsage || {}) }; +} +function getPreservedAliasMap(state) { + return { ...(state?.preservedAliases || {}) }; +} +function isAliasPreserved(state, email) { + return Boolean(getPreservedAliasMap(state)[String(email || '').trim().toLowerCase()]); +} +async function setIcloudAliasUsedState(payload, options = {}) { + calls.setUsed.push({ payload, options }); +} +async function addLog(message, level = 'info') { + calls.logs.push({ message, level }); +} +async function deleteIcloudAlias(alias) { + calls.deletes.push(alias); +} +async function listIcloudAliases() { + calls.listCalls += 1; + return overrides.listIcloudAliases ? overrides.listIcloudAliases() : []; +} +function findIcloudAliasByEmail(aliases, email) { + return (aliases || []).find((alias) => String(alias.email || '').toLowerCase() === String(email || '').toLowerCase()) || null; +} +function getErrorMessage(error) { + return String(typeof error === 'string' ? error : error?.message || ''); +} + +${bundle} + +return { + calls, + normalizeEmailGenerator, + getEmailGeneratorLabel, + normalizePersistentSettingValue, + finalizeIcloudAliasAfterSuccessfulFlow, +}; +`)(overrides); +} + +test('normalizeEmailGenerator and label support icloud', () => { + const api = createApi(); + assert.equal(api.normalizeEmailGenerator('icloud'), 'icloud'); + assert.equal(api.getEmailGeneratorLabel('icloud'), 'iCloud 隐私邮箱'); +}); + +test('normalizePersistentSettingValue handles icloud settings', () => { + const api = createApi(); + assert.equal(api.normalizePersistentSettingValue('icloudHostPreference', 'icloud.com'), 'icloud.com'); + assert.equal(api.normalizePersistentSettingValue('icloudHostPreference', 'bad-host'), 'auto'); + assert.equal(api.normalizePersistentSettingValue('autoDeleteUsedIcloudAlias', 1), true); +}); + +test('finalizeIcloudAliasAfterSuccessfulFlow marks icloud aliases as used without deleting when auto-delete is off', async () => { + const api = createApi(); + const result = await api.finalizeIcloudAliasAfterSuccessfulFlow({ + email: 'alias@icloud.com', + emailGenerator: 'icloud', + autoDeleteUsedIcloudAlias: false, + manualAliasUsage: {}, + preservedAliases: {}, + }); + + assert.deepEqual(result, { handled: true, deleted: false }); + assert.equal(api.calls.setUsed.length, 1); + assert.equal(api.calls.listCalls, 0); + assert.equal(api.calls.deletes.length, 0); +}); + +test('finalizeIcloudAliasAfterSuccessfulFlow skips deleting preserved aliases', async () => { + const api = createApi(); + const result = await api.finalizeIcloudAliasAfterSuccessfulFlow({ + email: 'alias@icloud.com', + emailGenerator: 'icloud', + autoDeleteUsedIcloudAlias: true, + manualAliasUsage: {}, + preservedAliases: { 'alias@icloud.com': true }, + }); + + assert.deepEqual(result, { handled: true, deleted: false }); + assert.equal(api.calls.setUsed.length, 1); + assert.equal(api.calls.listCalls, 0); + assert.equal(api.calls.deletes.length, 0); +}); + +test('finalizeIcloudAliasAfterSuccessfulFlow skips deleting aliases that are preserved in the latest alias list', async () => { + const api = createApi({ + listIcloudAliases() { + return [ + { email: 'alias@icloud.com', anonymousId: 'anon-1', preserved: true }, + ]; + }, + }); + + const result = await api.finalizeIcloudAliasAfterSuccessfulFlow({ + email: 'alias@icloud.com', + emailGenerator: 'icloud', + autoDeleteUsedIcloudAlias: true, + manualAliasUsage: {}, + preservedAliases: {}, + }); + + assert.deepEqual(result, { handled: true, deleted: false }); + assert.equal(api.calls.setUsed.length, 1); + assert.equal(api.calls.listCalls, 1); + assert.equal(api.calls.deletes.length, 0); +}); + +test('finalizeIcloudAliasAfterSuccessfulFlow deletes alias when auto-delete is enabled and alias exists', async () => { + const api = createApi({ + listIcloudAliases() { + return [ + { email: 'alias@icloud.com', anonymousId: 'anon-1', preserved: false }, + ]; + }, + }); + + const result = await api.finalizeIcloudAliasAfterSuccessfulFlow({ + email: 'alias@icloud.com', + emailGenerator: 'icloud', + autoDeleteUsedIcloudAlias: true, + manualAliasUsage: {}, + preservedAliases: {}, + }); + + assert.deepEqual(result, { handled: true, deleted: true }); + assert.equal(api.calls.setUsed.length, 1); + assert.equal(api.calls.listCalls, 1); + assert.deepEqual(api.calls.deletes, [ + { email: 'alias@icloud.com', anonymousId: 'anon-1', preserved: false }, + ]); +}); + +test('finalizeIcloudAliasAfterSuccessfulFlow ignores non-icloud flows', async () => { + const api = createApi(); + const result = await api.finalizeIcloudAliasAfterSuccessfulFlow({ + email: 'plain@example.com', + emailGenerator: 'duck', + autoDeleteUsedIcloudAlias: true, + manualAliasUsage: {}, + preservedAliases: {}, + }); + + assert.deepEqual(result, { handled: false, deleted: false }); + assert.equal(api.calls.setUsed.length, 0); +}); diff --git a/tests/icloud-utils.test.js b/tests/icloud-utils.test.js new file mode 100644 index 0000000..5d8fa68 --- /dev/null +++ b/tests/icloud-utils.test.js @@ -0,0 +1,121 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const { + findIcloudAliasArray, + findIcloudAliasByEmail, + getConfiguredIcloudHostPreference, + getIcloudHostHintFromMessage, + getIcloudLoginUrlForHost, + getIcloudSetupUrlForHost, + normalizeBooleanMap, + normalizeIcloudAliasList, + normalizeIcloudAliasRecord, + normalizeIcloudHost, + pickReusableIcloudAlias, + toNormalizedEmailSet, +} = require('../icloud-utils.js'); + +test('normalizeIcloudHost and host preference helpers resolve supported hosts', () => { + assert.equal(normalizeIcloudHost('www.icloud.com'), 'icloud.com'); + assert.equal(normalizeIcloudHost('setup.icloud.com.cn'), 'icloud.com.cn'); + assert.equal(normalizeIcloudHost('example.com'), ''); + + assert.equal(getConfiguredIcloudHostPreference({ icloudHostPreference: 'icloud.com' }), 'icloud.com'); + assert.equal(getConfiguredIcloudHostPreference({ icloudHostPreference: 'auto' }), ''); + assert.equal(getIcloudLoginUrlForHost('icloud.com.cn'), 'https://www.icloud.com.cn/'); + assert.equal(getIcloudSetupUrlForHost('icloud.com'), 'https://setup.icloud.com/setup/ws/1'); +}); + +test('getIcloudHostHintFromMessage can infer host from error text', () => { + assert.equal(getIcloudHostHintFromMessage('status 401 from setup.icloud.com.cn/setup/ws/1'), 'icloud.com.cn'); + assert.equal(getIcloudHostHintFromMessage('request failed at https://www.icloud.com/'), 'icloud.com'); + assert.equal(getIcloudHostHintFromMessage('unknown host'), ''); +}); + +test('findIcloudAliasArray finds nested alias collections', () => { + const payload = { + result: { + data: { + items: [ + { hme: 'first@icloud.com', anonymousId: 'a1' }, + { hme: 'second@icloud.com', anonymousId: 'a2' }, + ], + }, + }, + }; + + assert.deepEqual(findIcloudAliasArray(payload), payload.result.data.items); +}); + +test('normalizeIcloudAliasRecord merges used and preserved state', () => { + const alias = normalizeIcloudAliasRecord({ + anonymousId: 'alias-1', + hme: 'Demo@iCloud.com', + label: 'Test', + note: 'Created by test', + state: 'active', + }, { + usedEmails: ['demo@icloud.com'], + preservedEmails: ['demo@icloud.com'], + }); + + assert.deepEqual(alias, { + anonymousId: 'alias-1', + email: 'demo@icloud.com', + label: 'Test', + note: 'Created by test', + state: 'active', + active: true, + used: true, + preserved: true, + createdAt: null, + }); +}); + +test('normalizeIcloudAliasList orders active unused aliases before used aliases', () => { + const aliases = normalizeIcloudAliasList({ + hmeEmails: [ + { hme: 'used@icloud.com', anonymousId: 'u1', active: true }, + { hme: 'fresh@icloud.com', anonymousId: 'f1', active: true }, + { hme: 'inactive@icloud.com', anonymousId: 'i1', active: false }, + ], + }, { + usedEmails: ['used@icloud.com'], + preservedEmails: ['inactive@icloud.com'], + }); + + assert.deepEqual(aliases.map((alias) => alias.email), [ + 'fresh@icloud.com', + 'used@icloud.com', + 'inactive@icloud.com', + ]); + assert.equal(aliases[2].preserved, true); +}); + +test('pickReusableIcloudAlias and findIcloudAliasByEmail select expected aliases', () => { + const aliases = normalizeIcloudAliasList({ + hmeEmails: [ + { hme: 'used@icloud.com', anonymousId: 'u1', active: true }, + { hme: 'fresh@icloud.com', anonymousId: 'f1', active: true }, + ], + }, { + usedEmails: ['used@icloud.com'], + }); + + assert.equal(pickReusableIcloudAlias(aliases)?.email, 'fresh@icloud.com'); + assert.equal(findIcloudAliasByEmail(aliases, 'FRESH@ICLOUD.COM')?.anonymousId, 'f1'); +}); + +test('normalizeBooleanMap and toNormalizedEmailSet normalize keys and truthy entries', () => { + const normalized = normalizeBooleanMap({ + ' Demo@icloud.com ': 1, + 'skip@icloud.com': 0, + }); + + assert.deepEqual(normalized, { + 'demo@icloud.com': true, + 'skip@icloud.com': false, + }); + assert.deepEqual([...toNormalizedEmailSet(normalized)], ['demo@icloud.com']); +}); diff --git a/tests/step9-localhost-cleanup-scope.test.js b/tests/step9-localhost-cleanup-scope.test.js index ffb9670..5779339 100644 --- a/tests/step9-localhost-cleanup-scope.test.js +++ b/tests/step9-localhost-cleanup-scope.test.js @@ -110,6 +110,11 @@ async function addLog(message) { logMessages.push(message); } +async function finalizeIcloudAliasAfterSuccessfulFlow() {} +function shouldUseCustomRegistrationEmail() { + return false; +} + ${bundle} return {