Merge pull request #206 from initiatione/codex/free-phone-reuse-upstream

增加 HeroSMS 免费手机号复用
This commit is contained in:
Q3CC
2026-05-06 19:39:05 +08:00
committed by GitHub
13 changed files with 2170 additions and 15 deletions
@@ -7,6 +7,27 @@ test('background imports message router module', () => {
assert.match(source, /background\/message-router\.js/);
});
test('background defaults enable free phone reuse switches', () => {
const source = fs.readFileSync('background.js', 'utf8');
const defaultsStart = source.indexOf('const PERSISTED_SETTING_DEFAULTS = {');
const defaultsEnd = source.indexOf('const PERSISTED_SETTING_KEYS = Object.keys(PERSISTED_SETTING_DEFAULTS);');
const defaultsBlock = source.slice(defaultsStart, defaultsEnd);
assert.match(defaultsBlock, /freePhoneReuseEnabled:\s*true/);
assert.match(defaultsBlock, /freePhoneReuseAutoEnabled:\s*true/);
});
test('background free reusable phone setter does not depend on module-scoped phone flow constants', () => {
const source = fs.readFileSync('background.js', 'utf8');
const setterStart = source.indexOf('async function setFreeReusablePhoneActivation');
const setterEnd = source.indexOf('// ============================================================\n// Tab Registry', setterStart);
const setterBlock = source.slice(setterStart, setterEnd);
assert.ok(setterStart >= 0, 'expected setFreeReusablePhoneActivation to exist');
assert.doesNotMatch(setterBlock, /DEFAULT_PHONE_NUMBER_MAX_USES/);
assert.match(setterBlock, /maxUses:\s*Math\.max\(1,\s*Math\.floor\(Number\(record\.maxUses\)\s*\|\|\s*3\)\)/);
});
test('message router module exposes a factory', () => {
const source = fs.readFileSync('background/message-router.js', 'utf8');
const globalScope = {};
@@ -15,3 +36,56 @@ test('message router module exposes a factory', () => {
assert.equal(typeof api?.createMessageRouter, 'function');
});
test('SAVE_SETTING broadcasts free phone reuse setting updates for realtime sidepanel sync', async () => {
const source = fs.readFileSync('background/message-router.js', 'utf8');
const globalScope = { console };
const api = new Function('self', `${source}; return self.MultiPageBackgroundMessageRouter;`)(globalScope);
const broadcasts = [];
let state = {
freePhoneReuseEnabled: false,
freePhoneReuseAutoEnabled: false,
plusModeEnabled: false,
plusPaymentMethod: 'paypal',
};
const router = api.createMessageRouter({
addLog: async () => {},
buildLuckmailSessionSettingsPayload: () => ({}),
buildPersistentSettingsPayload: (input = {}) => {
const updates = {};
if (Object.prototype.hasOwnProperty.call(input, 'freePhoneReuseEnabled')) {
updates.freePhoneReuseEnabled = Boolean(input.freePhoneReuseEnabled);
}
if (Object.prototype.hasOwnProperty.call(input, 'freePhoneReuseAutoEnabled')) {
updates.freePhoneReuseAutoEnabled = Boolean(input.freePhoneReuseAutoEnabled);
}
return updates;
},
broadcastDataUpdate: (payload) => broadcasts.push(payload),
getState: async () => ({ ...state }),
setPersistentSettings: async () => {},
setState: async (updates) => {
state = { ...state, ...updates };
},
});
const response = await router.handleMessage({
type: 'SAVE_SETTING',
payload: {
freePhoneReuseEnabled: true,
freePhoneReuseAutoEnabled: true,
},
});
assert.equal(response.ok, true);
assert.equal(state.freePhoneReuseEnabled, true);
assert.equal(state.freePhoneReuseAutoEnabled, true);
assert.ok(
broadcasts.some((payload) => (
payload.freePhoneReuseEnabled === true
&& payload.freePhoneReuseAutoEnabled === true
)),
'expected SAVE_SETTING to broadcast free reuse switch updates'
);
});
+49
View File
@@ -448,3 +448,52 @@ test('phone auth resend stops with PHONE_ROUTE_405_RECOVERY_FAILED instead of en
global.window = originalWindow;
}
});
test('phone auth exposes resend page error checks for banned numbers', () => {
const originalLocation = global.location;
const originalDocument = global.document;
try {
global.location = {
href: 'https://auth.openai.com/phone-verification',
pathname: '/phone-verification',
};
global.document = {
querySelector() {
return {
querySelector() {
return null;
},
querySelectorAll() {
return [];
},
};
},
};
const helpers = api.createPhoneAuthHelpers({
fillInput: () => {},
getActionText: () => '',
getPageTextSnapshot: () => 'We cannot send a text message to this phone number. Please try another.',
getVerificationErrorText: () => '',
humanPause: async () => {},
isActionEnabled: () => true,
isAddPhonePageReady: () => false,
isConsentReady: () => false,
isPhoneVerificationPageReady: () => true,
isVisibleElement: () => true,
simulateClick: () => {},
sleep: async () => {},
throwIfStopped: () => {},
waitForElement: async () => null,
});
const result = helpers.checkPhoneResendError();
assert.equal(result.hasError, true);
assert.equal(result.reason, 'resend_phone_banned');
assert.equal(result.prefix, 'PHONE_RESEND_BANNED_NUMBER::');
assert.match(result.message, /cannot send/i);
} finally {
global.location = originalLocation;
global.document = originalDocument;
}
});
+819
View File
@@ -2794,6 +2794,28 @@ test('phone verification helper immediately replaces number when page says the p
verificationResendCount: 1,
currentPhoneActivation: null,
reusablePhoneActivation: null,
phoneReusableActivationPool: [
{
activationId: 'pool-used-match',
phoneNumber: '+66 95 000 0011',
provider: 'hero-sms',
serviceCode: 'dr',
countryId: 52,
successfulUses: 1,
maxUses: 3,
},
],
freeReusablePhoneActivation: {
activationId: 'free-used-match',
phoneNumber: '+66 95 000 0011',
provider: 'hero-sms',
serviceCode: 'dr',
countryId: 52,
countryLabel: 'Thailand',
successfulUses: 0,
maxUses: 3,
source: 'free-manual-reuse',
},
};
const numbers = [
@@ -2903,6 +2925,11 @@ test('phone verification helper immediately replaces number when page says the p
'SUBMIT_PHONE_NUMBER',
'SUBMIT_PHONE_VERIFICATION_CODE',
]);
assert.equal(currentState.freeReusablePhoneActivation, null);
assert.deepStrictEqual(
currentState.phoneReusableActivationPool.filter((activation) => activation.phoneNumber === '+66 95 000 0011'),
[]
);
});
test('phone verification helper treats phone_max_usage_exceeded as used-number and rotates immediately', async () => {
@@ -2913,6 +2940,28 @@ test('phone verification helper treats phone_max_usage_exceeded as used-number a
verificationResendCount: 1,
currentPhoneActivation: null,
reusablePhoneActivation: null,
phoneReusableActivationPool: [
{
activationId: 'pool-max-match',
phoneNumber: '+66 95 000 1011',
provider: 'hero-sms',
serviceCode: 'dr',
countryId: 52,
successfulUses: 1,
maxUses: 3,
},
],
freeReusablePhoneActivation: {
activationId: 'free-max-match',
phoneNumber: '+66 95 000 1011',
provider: 'hero-sms',
serviceCode: 'dr',
countryId: 52,
countryLabel: 'Thailand',
successfulUses: 0,
maxUses: 3,
source: 'free-manual-reuse',
},
};
const numbers = [
@@ -3022,6 +3071,11 @@ test('phone verification helper treats phone_max_usage_exceeded as used-number a
'SUBMIT_PHONE_NUMBER',
'SUBMIT_PHONE_VERIFICATION_CODE',
]);
assert.equal(currentState.freeReusablePhoneActivation, null);
assert.deepStrictEqual(
currentState.phoneReusableActivationPool.filter((activation) => activation.phoneNumber === '+66 95 000 1011'),
[]
);
});
test('phone verification helper rotates number when submitPhoneVerificationCode throws phone_max_usage_exceeded', async () => {
@@ -3418,6 +3472,771 @@ test('phone verification helper keeps maxUses behavior for reused V2 activations
assert.deepStrictEqual(currentState.reusablePhoneActivation, null);
});
test('phone verification helper gives automatic free reuse priority over paid reuse and new acquisition', async () => {
const requests = [];
let statusPollCount = 0;
let currentState = {
heroSmsApiKey: 'demo-key',
heroSmsReuseEnabled: true,
freePhoneReuseEnabled: true,
freePhoneReuseAutoEnabled: true,
verificationResendCount: 0,
currentPhoneActivation: null,
reusablePhoneActivation: {
activationId: 'paid-reuse',
phoneNumber: '66950003333',
provider: 'hero-sms',
serviceCode: 'dr',
countryId: 52,
countryLabel: 'Thailand',
successfulUses: 0,
maxUses: 3,
},
freeReusablePhoneActivation: {
activationId: 'free-priority',
phoneNumber: '66950004444',
provider: 'hero-sms',
serviceCode: 'dr',
countryId: 52,
countryLabel: 'Thailand',
successfulUses: 0,
maxUses: 3,
source: 'free-manual-reuse',
},
};
const helpers = api.createPhoneVerificationHelpers({
addLog: async () => {},
ensureStep8SignupPageReady: async () => {},
fetchImpl: async (url) => {
const parsedUrl = new URL(url);
requests.push(parsedUrl);
const action = parsedUrl.searchParams.get('action');
const id = parsedUrl.searchParams.get('id');
if (action === 'reactivate' || action === 'getPrices' || action === 'getNumber' || action === 'getNumberV2') {
throw new Error(`${action} should not be called before automatic free reuse`);
}
if (action === 'setStatus' && id === 'free-priority') {
return { ok: true, text: async () => 'ACCESS_RETRY_GET' };
}
if (action === 'getStatus' && id === 'free-priority') {
statusPollCount += 1;
return { ok: true, text: async () => (statusPollCount === 1 ? 'STATUS_WAIT_CODE' : 'STATUS_OK:112233') };
}
throw new Error(`Unexpected HeroSMS action: ${action}:${id || ''}`);
},
getOAuthFlowStepTimeoutMs: async (defaultTimeoutMs) => defaultTimeoutMs,
getState: async () => ({ ...currentState }),
sendToContentScriptResilient: async (_source, message) => {
if (message.type === 'SUBMIT_PHONE_NUMBER') {
return { phoneVerificationPage: true, url: 'https://auth.openai.com/phone-verification' };
}
if (message.type === 'SUBMIT_PHONE_VERIFICATION_CODE') {
return { success: true, consentReady: true, url: 'https://auth.openai.com/authorize' };
}
throw new Error(`Unexpected content-script message: ${message.type}`);
},
setState: async (updates) => {
currentState = { ...currentState, ...updates };
},
sleepWithStop: async () => {},
throwIfStopped: () => {},
});
const result = await helpers.completePhoneVerificationFlow(1, {
addPhonePage: true,
phoneVerificationPage: false,
url: 'https://auth.openai.com/add-phone',
});
assert.deepStrictEqual(result, {
success: true,
consentReady: true,
url: 'https://auth.openai.com/authorize',
});
assert.deepStrictEqual(
requests.map((requestUrl) => requestUrl.searchParams.get('action')),
['setStatus', 'getStatus', 'getStatus']
);
assert.deepStrictEqual(
requests
.filter((requestUrl) => requestUrl.searchParams.get('action') === 'setStatus')
.map((requestUrl) => requestUrl.searchParams.get('status')),
['3']
);
assert.equal(currentState.freeReusablePhoneActivation.successfulUses, 1);
assert.equal(currentState.freeReusablePhoneActivation.activationId, 'free-priority');
assert.equal(currentState.reusablePhoneActivation.activationId, 'paid-reuse');
});
test('phone verification helper accepts HeroSMS WAIT_RETRY as free-reuse ready without using its suffix as code', async () => {
const requests = [];
const events = [];
const submittedCodes = [];
let statusPollCount = 0;
let currentState = {
heroSmsApiKey: 'demo-key',
freePhoneReuseEnabled: true,
freePhoneReuseAutoEnabled: true,
verificationResendCount: 0,
currentPhoneActivation: null,
freeReusablePhoneActivation: {
activationId: 'retry-ready-free',
phoneNumber: '6283184934060',
provider: 'hero-sms',
serviceCode: 'dr',
countryId: 6,
countryLabel: 'Indonesia',
successfulUses: 0,
maxUses: 3,
source: 'free-manual-reuse',
},
};
const helpers = api.createPhoneVerificationHelpers({
addLog: async () => {},
ensureStep8SignupPageReady: async () => {},
fetchImpl: async (url) => {
const parsedUrl = new URL(url);
requests.push(parsedUrl);
const action = parsedUrl.searchParams.get('action');
const id = parsedUrl.searchParams.get('id');
const status = parsedUrl.searchParams.get('status');
events.push(action === 'setStatus' ? `${action}:${status}` : action);
if (action === 'setStatus' && id === 'retry-ready-free' && status === '3') {
return { ok: true, text: async () => 'ACCESS_RETRY_GET' };
}
if (action === 'getStatus' && id === 'retry-ready-free') {
statusPollCount += 1;
return {
ok: true,
text: async () => (statusPollCount === 1 ? 'STATUS_WAIT_RETRY:100001' : 'STATUS_OK:654321'),
};
}
throw new Error(`Unexpected HeroSMS action: ${action}:${id || ''}:${status || ''}`);
},
getOAuthFlowStepTimeoutMs: async (defaultTimeoutMs) => defaultTimeoutMs,
getState: async () => ({ ...currentState }),
sendToContentScriptResilient: async (_source, message) => {
events.push(message.type);
if (message.type === 'SUBMIT_PHONE_NUMBER') {
assert.equal(message.payload.phoneNumber, '6283184934060');
return { phoneVerificationPage: true, url: 'https://auth.openai.com/phone-verification' };
}
if (message.type === 'SUBMIT_PHONE_VERIFICATION_CODE') {
submittedCodes.push(message.payload.code);
return { success: true, consentReady: true, url: 'https://auth.openai.com/authorize' };
}
throw new Error(`Unexpected content-script message: ${message.type}`);
},
setState: async (updates) => {
currentState = { ...currentState, ...updates };
},
sleepWithStop: async () => {
events.push('sleep');
},
throwIfStopped: () => {},
});
const result = await helpers.completePhoneVerificationFlow(1, {
addPhonePage: true,
phoneVerificationPage: false,
url: 'https://auth.openai.com/add-phone',
});
assert.deepStrictEqual(result, {
success: true,
consentReady: true,
url: 'https://auth.openai.com/authorize',
});
assert.deepStrictEqual(submittedCodes, ['654321']);
assert.equal(submittedCodes.includes('100001'), false);
assert.deepStrictEqual(
events.slice(0, 4),
['setStatus:3', 'sleep', 'getStatus', 'SUBMIT_PHONE_NUMBER']
);
assert.equal(currentState.freeReusablePhoneActivation.successfulUses, 1);
assert.equal(
requests.some((requestUrl) => ['reactivate', 'getPrices', 'getNumber', 'getNumberV2'].includes(requestUrl.searchParams.get('action'))),
false
);
});
test('phone verification helper stops failed automatic free reuse without buying a new number', async () => {
const requests = [];
const messages = [];
const stops = [];
let currentState = {
heroSmsApiKey: 'demo-key',
freePhoneReuseEnabled: true,
freePhoneReuseAutoEnabled: true,
verificationResendCount: 0,
currentPhoneActivation: null,
freeReusablePhoneActivation: {
activationId: 'cancelled-free',
phoneNumber: '66950007777',
provider: 'hero-sms',
serviceCode: 'dr',
countryId: 52,
countryLabel: 'Thailand',
successfulUses: 0,
maxUses: 3,
source: 'free-manual-reuse',
},
};
const helpers = api.createPhoneVerificationHelpers({
addLog: async () => {},
ensureStep8SignupPageReady: async () => {},
fetchImpl: async (url) => {
const parsedUrl = new URL(url);
requests.push(parsedUrl);
const action = parsedUrl.searchParams.get('action');
const id = parsedUrl.searchParams.get('id');
if (action === 'setStatus' && id === 'cancelled-free') {
return { ok: true, text: async () => 'ACCESS_RETRY_GET' };
}
if (action === 'getStatus' && id === 'cancelled-free') {
return { ok: true, text: async () => 'STATUS_CANCEL' };
}
if (action === 'reactivate' || action === 'getPrices' || action === 'getNumber' || action === 'getNumberV2') {
throw new Error(`${action} should not be called after automatic free reuse preparation fails`);
}
throw new Error(`Unexpected HeroSMS action: ${action}:${id || ''}`);
},
getOAuthFlowStepTimeoutMs: async (defaultTimeoutMs) => defaultTimeoutMs,
getState: async () => ({ ...currentState }),
requestStop: async (payload) => {
stops.push(payload);
},
sendToContentScriptResilient: async (_source, message) => {
messages.push(message);
throw new Error(`Auth page should not be touched after failed free reuse: ${message.type}`);
},
setState: async (updates) => {
currentState = { ...currentState, ...updates };
},
sleepWithStop: async () => {},
throwIfStopped: () => {},
});
await assert.rejects(
helpers.completePhoneVerificationFlow(1, {
addPhonePage: true,
phoneVerificationPage: false,
url: 'https://auth.openai.com/add-phone',
}),
/PHONE_AUTO_FREE_REUSE_PREPARE::/
);
assert.deepStrictEqual(messages, []);
assert.equal(stops.length, 1);
assert.match(stops[0].logMessage, /不购买新 HeroSMS 号码/);
assert.equal(currentState.freeReusablePhoneActivation, null);
assert.equal(
requests.some((requestUrl) => ['reactivate', 'getPrices', 'getNumber', 'getNumberV2'].includes(requestUrl.searchParams.get('action'))),
false
);
});
test('phone verification helper stops never-ready automatic free reuse without buying or reactivating', async () => {
const requests = [];
const messages = [];
const stops = [];
let currentState = {
heroSmsApiKey: 'demo-key',
heroSmsReuseEnabled: true,
freePhoneReuseEnabled: true,
freePhoneReuseAutoEnabled: true,
verificationResendCount: 0,
currentPhoneActivation: null,
freeReusablePhoneActivation: {
activationId: 'never-ready-free',
phoneNumber: '66950008888',
provider: 'hero-sms',
serviceCode: 'dr',
countryId: 52,
countryLabel: 'Thailand',
successfulUses: 0,
maxUses: 3,
source: 'free-manual-reuse',
},
};
const helpers = api.createPhoneVerificationHelpers({
addLog: async () => {},
ensureStep8SignupPageReady: async () => {},
fetchImpl: async (url) => {
const parsedUrl = new URL(url);
requests.push(parsedUrl);
const action = parsedUrl.searchParams.get('action');
const id = parsedUrl.searchParams.get('id');
if (action === 'setStatus' && id === 'never-ready-free') {
return { ok: true, text: async () => 'ACCESS_RETRY_GET' };
}
if (action === 'getStatus' && id === 'never-ready-free') {
return { ok: true, text: async () => 'STATUS_OK:445566' };
}
if (action === 'reactivate' || action === 'getPrices' || action === 'getNumber' || action === 'getNumberV2') {
throw new Error(`${action} should not be called after automatic free reuse never becomes ready`);
}
throw new Error(`Unexpected HeroSMS action: ${action}:${id || ''}`);
},
getOAuthFlowStepTimeoutMs: async (defaultTimeoutMs) => defaultTimeoutMs,
getState: async () => ({ ...currentState }),
requestStop: async (payload) => {
stops.push(payload);
},
sendToContentScriptResilient: async (_source, message) => {
messages.push(message);
throw new Error(`Auth page should not be touched when automatic free reuse is never ready: ${message.type}`);
},
setState: async (updates) => {
currentState = { ...currentState, ...updates };
},
sleepWithStop: async () => {},
throwIfStopped: () => {},
});
await assert.rejects(
helpers.completePhoneVerificationFlow(1, {
addPhonePage: true,
phoneVerificationPage: false,
url: 'https://auth.openai.com/add-phone',
}),
/PHONE_AUTO_FREE_REUSE_PREPARE::/
);
assert.deepStrictEqual(messages, []);
assert.equal(stops.length, 1);
assert.match(stops[0].logMessage, /不购买新 HeroSMS 号码/);
assert.equal(currentState.freeReusablePhoneActivation.activationId, 'never-ready-free');
assert.equal(
requests.some((requestUrl) => ['reactivate', 'getPrices', 'getNumber', 'getNumberV2'].includes(requestUrl.searchParams.get('action'))),
false
);
assert.equal(requests.every((requestUrl) => requestUrl.searchParams.get('id') === 'never-ready-free'), true);
});
test('phone verification helper accepts HeroSMS WAIT_RESEND as free-reuse ready before submit', async () => {
const requests = [];
const messages = [];
let statusPollCount = 0;
let currentState = {
heroSmsApiKey: 'demo-key',
freePhoneReuseEnabled: true,
freePhoneReuseAutoEnabled: true,
verificationResendCount: 0,
currentPhoneActivation: null,
freeReusablePhoneActivation: {
activationId: 'not-waiting-free',
phoneNumber: '66950005555',
provider: 'hero-sms',
serviceCode: 'dr',
countryId: 52,
countryLabel: 'Thailand',
successfulUses: 0,
maxUses: 3,
source: 'free-manual-reuse',
},
};
const helpers = api.createPhoneVerificationHelpers({
addLog: async () => {},
ensureStep8SignupPageReady: async () => {},
fetchImpl: async (url) => {
const parsedUrl = new URL(url);
requests.push(parsedUrl);
const action = parsedUrl.searchParams.get('action');
const id = parsedUrl.searchParams.get('id');
if (action === 'setStatus' && id === 'not-waiting-free') {
return { ok: true, text: async () => 'ACCESS_RETRY_GET' };
}
if (action === 'getStatus' && id === 'not-waiting-free') {
statusPollCount += 1;
return {
ok: true,
text: async () => (statusPollCount === 1 ? 'STATUS_WAIT_RESEND' : 'STATUS_OK:778899'),
};
}
if (action === 'reactivate' || action === 'getPrices' || action === 'getNumber' || action === 'getNumberV2') {
throw new Error(`${action} should not be called for accepted saved free reuse waiting state`);
}
throw new Error(`Unexpected HeroSMS action: ${action}:${id || ''}`);
},
getOAuthFlowStepTimeoutMs: async (defaultTimeoutMs) => defaultTimeoutMs,
getState: async () => ({ ...currentState }),
sendToContentScriptResilient: async (_source, message) => {
messages.push(message);
if (message.type === 'SUBMIT_PHONE_NUMBER') {
return { phoneVerificationPage: true, url: 'https://auth.openai.com/phone-verification' };
}
if (message.type === 'SUBMIT_PHONE_VERIFICATION_CODE') {
return { success: true, consentReady: true, url: 'https://auth.openai.com/authorize' };
}
throw new Error(`Unexpected content-script message: ${message.type}`);
},
setState: async (updates) => {
currentState = { ...currentState, ...updates };
},
sleepWithStop: async () => {},
throwIfStopped: () => {},
});
const result = await helpers.completePhoneVerificationFlow(1, {
addPhonePage: true,
phoneVerificationPage: false,
url: 'https://auth.openai.com/add-phone',
});
assert.deepStrictEqual(result, {
success: true,
consentReady: true,
url: 'https://auth.openai.com/authorize',
});
assert.deepStrictEqual(
messages.map((message) => message.type),
['SUBMIT_PHONE_NUMBER', 'SUBMIT_PHONE_VERIFICATION_CODE']
);
assert.deepStrictEqual(
requests
.filter((requestUrl) => requestUrl.searchParams.get('action') === 'setStatus')
.map((requestUrl) => requestUrl.searchParams.get('status')),
['3']
);
});
test('phone verification helper accepts HeroSMS WAIT_RESEND suffix as free-reuse ready before submit', async () => {
const requests = [];
const messages = [];
let statusPollCount = 0;
let currentState = {
heroSmsApiKey: 'demo-key',
freePhoneReuseEnabled: true,
freePhoneReuseAutoEnabled: true,
verificationResendCount: 0,
currentPhoneActivation: null,
freeReusablePhoneActivation: {
activationId: 'resend-info-free',
phoneNumber: '66950005656',
provider: 'hero-sms',
serviceCode: 'dr',
countryId: 52,
countryLabel: 'Thailand',
successfulUses: 0,
maxUses: 3,
source: 'free-manual-reuse',
},
};
const helpers = api.createPhoneVerificationHelpers({
addLog: async () => {},
ensureStep8SignupPageReady: async () => {},
fetchImpl: async (url) => {
const parsedUrl = new URL(url);
requests.push(parsedUrl);
const action = parsedUrl.searchParams.get('action');
const id = parsedUrl.searchParams.get('id');
if (action === 'setStatus' && id === 'resend-info-free') {
return { ok: true, text: async () => 'ACCESS_RETRY_GET' };
}
if (action === 'getStatus' && id === 'resend-info-free') {
statusPollCount += 1;
return {
ok: true,
text: async () => (statusPollCount === 1 ? 'STATUS_WAIT_RESEND:100001' : 'STATUS_OK:887766'),
};
}
if (action === 'reactivate' || action === 'getPrices' || action === 'getNumber' || action === 'getNumberV2') {
throw new Error(`${action} should not be called for accepted saved free reuse resend state`);
}
throw new Error(`Unexpected HeroSMS action: ${action}:${id || ''}`);
},
getOAuthFlowStepTimeoutMs: async (defaultTimeoutMs) => defaultTimeoutMs,
getState: async () => ({ ...currentState }),
sendToContentScriptResilient: async (_source, message) => {
messages.push(message);
if (message.type === 'SUBMIT_PHONE_NUMBER') {
assert.equal(message.payload.phoneNumber, '66950005656');
return { phoneVerificationPage: true, url: 'https://auth.openai.com/phone-verification' };
}
if (message.type === 'SUBMIT_PHONE_VERIFICATION_CODE') {
assert.equal(message.payload.code, '887766');
return { success: true, consentReady: true, url: 'https://auth.openai.com/authorize' };
}
throw new Error(`Unexpected content-script message: ${message.type}`);
},
setState: async (updates) => {
currentState = { ...currentState, ...updates };
},
sleepWithStop: async () => {},
throwIfStopped: () => {},
});
const result = await helpers.completePhoneVerificationFlow(1, {
addPhonePage: true,
phoneVerificationPage: false,
url: 'https://auth.openai.com/add-phone',
});
assert.deepStrictEqual(result, {
success: true,
consentReady: true,
url: 'https://auth.openai.com/authorize',
});
assert.deepStrictEqual(
messages.map((message) => message.type),
['SUBMIT_PHONE_NUMBER', 'SUBMIT_PHONE_VERIFICATION_CODE']
);
assert.deepStrictEqual(
requests
.filter((requestUrl) => requestUrl.searchParams.get('action') === 'setStatus')
.map((requestUrl) => requestUrl.searchParams.get('status')),
['3']
);
});
test('phone verification helper retires automatic free reuse record at max uses', async () => {
const requests = [];
let statusPollCount = 0;
let currentState = {
heroSmsApiKey: 'demo-key',
freePhoneReuseEnabled: true,
freePhoneReuseAutoEnabled: true,
verificationResendCount: 0,
currentPhoneActivation: null,
freeReusablePhoneActivation: {
activationId: 'free-max',
phoneNumber: '66950009999',
provider: 'hero-sms',
serviceCode: 'dr',
countryId: 52,
countryLabel: 'Thailand',
successfulUses: 2,
maxUses: 3,
source: 'free-manual-reuse',
},
};
const helpers = api.createPhoneVerificationHelpers({
addLog: async () => {},
ensureStep8SignupPageReady: async () => {},
fetchImpl: async (url) => {
const parsedUrl = new URL(url);
requests.push(parsedUrl);
const action = parsedUrl.searchParams.get('action');
const id = parsedUrl.searchParams.get('id');
if (action === 'setStatus' && id === 'free-max') {
return { ok: true, text: async () => 'ACCESS_RETRY_GET' };
}
if (action === 'getStatus' && id === 'free-max') {
statusPollCount += 1;
return { ok: true, text: async () => (statusPollCount === 1 ? 'STATUS_WAIT_CODE' : 'STATUS_OK:778899') };
}
throw new Error(`Unexpected HeroSMS action: ${action}:${id || ''}`);
},
getOAuthFlowStepTimeoutMs: async (defaultTimeoutMs) => defaultTimeoutMs,
getState: async () => ({ ...currentState }),
sendToContentScriptResilient: async (_source, message) => {
if (message.type === 'SUBMIT_PHONE_NUMBER') {
return { phoneVerificationPage: true, url: 'https://auth.openai.com/phone-verification' };
}
if (message.type === 'SUBMIT_PHONE_VERIFICATION_CODE') {
return { success: true, consentReady: true, url: 'https://auth.openai.com/authorize' };
}
throw new Error(`Unexpected content-script message: ${message.type}`);
},
setState: async (updates) => {
currentState = { ...currentState, ...updates };
},
sleepWithStop: async () => {},
throwIfStopped: () => {},
});
await helpers.completePhoneVerificationFlow(1, {
addPhonePage: true,
phoneVerificationPage: false,
url: 'https://auth.openai.com/add-phone',
});
assert.equal(currentState.freeReusablePhoneActivation, null);
assert.deepStrictEqual(
requests.map((requestUrl) => requestUrl.searchParams.get('action')),
['setStatus', 'getStatus', 'getStatus']
);
assert.deepStrictEqual(
requests
.filter((requestUrl) => requestUrl.searchParams.get('action') === 'setStatus')
.map((requestUrl) => requestUrl.searchParams.get('status')),
['3']
);
});
test('phone verification helper preserves coded free-reuse activation when code submission errors', async () => {
const requests = [];
let currentState = {
heroSmsApiKey: 'demo-key',
heroSmsCountryId: 52,
heroSmsCountryLabel: 'Thailand',
freePhoneReuseEnabled: true,
verificationResendCount: 0,
currentPhoneActivation: null,
freeReusablePhoneActivation: null,
reusablePhoneActivation: null,
};
const helpers = api.createPhoneVerificationHelpers({
addLog: async () => {},
ensureStep8SignupPageReady: async () => {},
fetchImpl: async (url) => {
const parsedUrl = new URL(url);
requests.push(parsedUrl);
const action = parsedUrl.searchParams.get('action');
const id = parsedUrl.searchParams.get('id');
const status = parsedUrl.searchParams.get('status');
if (action === 'getPrices') {
return { ok: true, text: async () => buildHeroSmsPricesPayload() };
}
if (action === 'getNumber') {
return { ok: true, text: async () => 'ACCESS_NUMBER:new-free-save:66950006666' };
}
if (action === 'getStatus' && id === 'new-free-save') {
return { ok: true, text: async () => 'STATUS_OK:445566' };
}
if (action === 'setStatus' && id === 'new-free-save' && status === '8') {
throw new Error('free-reuse activation should not be cancelled after SMS code was received');
}
if (action === 'setStatus' && id === 'new-free-save' && status === '6') {
throw new Error('free-reuse activation should not be completed after SMS code was received');
}
throw new Error(`Unexpected HeroSMS action: ${action}:${id || ''}:${status || ''}`);
},
getOAuthFlowStepTimeoutMs: async (defaultTimeoutMs) => defaultTimeoutMs,
getState: async () => ({ ...currentState }),
sendToContentScriptResilient: async (_source, message) => {
if (message.type === 'SUBMIT_PHONE_NUMBER') {
return { phoneVerificationPage: true, url: 'https://auth.openai.com/phone-verification' };
}
if (message.type === 'SUBMIT_PHONE_VERIFICATION_CODE') {
throw new Error('simulated auth-page failure after code submit');
}
throw new Error(`Unexpected content-script message: ${message.type}`);
},
setState: async (updates) => {
currentState = { ...currentState, ...updates };
},
sleepWithStop: async () => {},
throwIfStopped: () => {},
});
await assert.rejects(
helpers.completePhoneVerificationFlow(1, {
addPhonePage: true,
phoneVerificationPage: false,
url: 'https://auth.openai.com/add-phone',
}),
/simulated auth-page failure/
);
assert.equal(currentState.freeReusablePhoneActivation.activationId, 'new-free-save');
assert.equal(currentState.freeReusablePhoneActivation.phoneNumber, '66950006666');
assert.equal(
requests.some((requestUrl) => (
requestUrl.searchParams.get('action') === 'setStatus'
&& requestUrl.searchParams.get('id') === 'new-free-save'
&& ['6', '8'].includes(requestUrl.searchParams.get('status'))
)),
false
);
assert.deepStrictEqual(
requests
.filter((requestUrl) => (
requestUrl.searchParams.get('action') === 'setStatus'
&& requestUrl.searchParams.get('id') === 'new-free-save'
))
.map((requestUrl) => requestUrl.searchParams.get('status')),
[]
);
});
test('phone verification helper preserves newly saved free-reuse activation after OAuth success without source marker', async () => {
const requests = [];
let currentState = {
heroSmsApiKey: 'demo-key',
heroSmsCountryId: 52,
heroSmsCountryLabel: 'Thailand',
freePhoneReuseEnabled: true,
verificationResendCount: 0,
currentPhoneActivation: null,
freeReusablePhoneActivation: null,
reusablePhoneActivation: null,
};
const helpers = api.createPhoneVerificationHelpers({
addLog: async () => {},
ensureStep8SignupPageReady: async () => {},
fetchImpl: async (url) => {
const parsedUrl = new URL(url);
requests.push(parsedUrl);
const action = parsedUrl.searchParams.get('action');
const id = parsedUrl.searchParams.get('id');
const status = parsedUrl.searchParams.get('status');
if (action === 'getPrices') {
return { ok: true, text: async () => buildHeroSmsPricesPayload() };
}
if (action === 'getNumber') {
return { ok: true, text: async () => 'ACCESS_NUMBER:new-free-success:66950007777' };
}
if (action === 'getStatus' && id === 'new-free-success') {
return { ok: true, text: async () => 'STATUS_OK:778899' };
}
if (action === 'setStatus' && id === 'new-free-success' && ['6', '8'].includes(status)) {
throw new Error(`free-reuse activation should not receive terminal setStatus(${status}) after OAuth success`);
}
throw new Error(`Unexpected HeroSMS action: ${action}:${id || ''}:${status || ''}`);
},
getOAuthFlowStepTimeoutMs: async (defaultTimeoutMs) => defaultTimeoutMs,
getState: async () => ({ ...currentState }),
sendToContentScriptResilient: async (_source, message) => {
if (message.type === 'SUBMIT_PHONE_NUMBER') {
return { phoneVerificationPage: true, url: 'https://auth.openai.com/phone-verification' };
}
if (message.type === 'SUBMIT_PHONE_VERIFICATION_CODE') {
return { success: true, consentReady: true, url: 'https://auth.openai.com/authorize' };
}
throw new Error(`Unexpected content-script message: ${message.type}`);
},
setState: async (updates) => {
currentState = { ...currentState, ...updates };
},
sleepWithStop: async () => {},
throwIfStopped: () => {},
});
const result = await helpers.completePhoneVerificationFlow(1, {
addPhonePage: true,
phoneVerificationPage: false,
url: 'https://auth.openai.com/add-phone',
});
assert.deepStrictEqual(result, {
success: true,
consentReady: true,
url: 'https://auth.openai.com/authorize',
});
assert.equal(currentState.freeReusablePhoneActivation.activationId, 'new-free-success');
assert.equal(currentState.freeReusablePhoneActivation.phoneNumber, '66950007777');
assert.equal(currentState.freeReusablePhoneActivation.source, 'free-manual-reuse');
assert.equal(
requests.some((requestUrl) => (
requestUrl.searchParams.get('action') === 'setStatus'
&& requestUrl.searchParams.get('id') === 'new-free-success'
&& ['6', '8'].includes(requestUrl.searchParams.get('status'))
)),
false
);
});
test('phone verification helper replaces number immediately when resend is throttled and does not spam resend clicks', async () => {
const requests = [];
const messages = [];
+2
View File
@@ -110,6 +110,7 @@ const inputAutoSkipFailures = { disabled: false };
const autoContinueBar = { style: { display: '' } };
function setSettingsCardLocked() {}
function setFreePhoneReuseControlsLocked() {}
function getAutoRunLabel() { return ''; }
function getLockedRunCountFromEmailPool() { return lockedRunCount; }
function isCustomMailProvider() { return false; }
@@ -198,6 +199,7 @@ const inputAutoSkipFailures = { disabled: false };
const autoContinueBar = { style: { display: '' } };
function setSettingsCardLocked() {}
function setFreePhoneReuseControlsLocked() {}
function getAutoRunLabel() { return ''; }
function getLockedRunCountFromEmailPool() { return 0; }
function isCustomMailProvider() { return false; }
@@ -108,6 +108,18 @@ test('sidepanel html exposes phone verification toggle and multi-provider SMS ro
assert.match(html, /id="row-hero-sms-current-code"/);
assert.match(html, /id="row-hero-sms-preferred-activation"/);
assert.match(html, /id="select-hero-sms-preferred-activation"/);
assert.match(html, /id="row-free-phone-reuse-enabled"/);
assert.match(html, /id="input-free-phone-reuse-enabled"/);
assert.match(html, /id="row-free-phone-reuse-auto-enabled"/);
assert.match(html, /id="input-free-phone-reuse-auto-enabled"/);
assert.match(html, /id="row-free-reusable-phone"/);
assert.match(html, /id="display-free-reusable-phone"/);
assert.match(html, /id="display-free-reusable-phone-country"/);
assert.match(html, /id="input-free-reusable-phone"/);
assert.match(html, /id="btn-save-free-reusable-phone"/);
assert.match(html, /id="btn-clear-free-reusable-phone"/);
assert.match(html, /白嫖复用/);
assert.match(html, /自动白嫖复用/);
assert.match(html, /id="row-phone-replacement-limit"/);
assert.match(html, /id="row-phone-verification-resend-count"/);
assert.match(html, /id="row-phone-code-wait-seconds"/);
@@ -134,6 +146,49 @@ test('sidepanel html exposes phone verification toggle and multi-provider SMS ro
assert.doesNotMatch(html, /id="input-account-run-history-text-enabled"/);
});
test('sidepanel source wires free reusable phone save and clear actions to runtime messages', () => {
assert.match(sidepanelSource, /const inputFreePhoneReuseEnabled = document\.getElementById\('input-free-phone-reuse-enabled'\);/);
assert.match(sidepanelSource, /const inputFreePhoneReuseAutoEnabled = document\.getElementById\('input-free-phone-reuse-auto-enabled'\);/);
assert.match(sidepanelSource, /const displayFreeReusablePhone = document\.getElementById\('display-free-reusable-phone'\);/);
assert.match(sidepanelSource, /const inputFreeReusablePhone = document\.getElementById\('input-free-reusable-phone'\);/);
assert.match(sidepanelSource, /const btnSaveFreeReusablePhone = document\.getElementById\('btn-save-free-reusable-phone'\);/);
assert.match(sidepanelSource, /const btnClearFreeReusablePhone = document\.getElementById\('btn-clear-free-reusable-phone'\);/);
assert.match(sidepanelSource, /type:\s*'SET_FREE_REUSABLE_PHONE'/);
assert.match(sidepanelSource, /payload:\s*\{\s*phoneNumber\s*\}/s);
assert.match(sidepanelSource, /type:\s*'CLEAR_FREE_REUSABLE_PHONE'/);
});
test('sidepanel keeps free reuse switches realtime and locks them during auto run', () => {
assert.match(
sidepanelSource,
/message\.payload\.freePhoneReuseEnabled !== undefined[\s\S]*updatePhoneVerificationSettingsUI\(\);/
);
assert.match(
sidepanelSource,
/message\.payload\.freePhoneReuseAutoEnabled !== undefined[\s\S]*updatePhoneVerificationSettingsUI\(\);/
);
assert.match(sidepanelSource, /setFreePhoneReuseControlsLocked\(settingsCardLocked\);/);
assert.match(
sidepanelSource,
/inputFreePhoneReuseEnabled\.disabled = locked;[\s\S]*inputFreePhoneReuseAutoEnabled\.disabled = locked/
);
});
test('sidepanel free reusable phone paths avoid stale identifiers and empty-save errors', () => {
assert.doesNotMatch(
sidepanelSource,
/applyHeroSmsFallbackSelection\(\s*\[\.\.\.nextPrimaryCountries,\s*\.\.\.nextFallback\]/
);
assert.match(
sidepanelSource,
/applyHeroSmsFallbackSelection\(\s*\[\s*nextPrimary,\s*\.\.\.nextFallback\]/
);
assert.match(
sidepanelSource,
/if \(!phoneNumber\) \{[\s\S]*请先填写白嫖复用手机号[\s\S]*return;[\s\S]*chrome\.runtime\.sendMessage\(\{\s*type:\s*'SET_FREE_REUSABLE_PHONE'/
);
});
test('sidepanel source wires runtime signup phone field to background sync messages', () => {
assert.match(sidepanelSource, /function getRuntimeSignupPhoneValue\(state = latestState\)/);
assert.match(sidepanelSource, /function shouldExecuteStep3WithSignupPhoneIdentity\(state = latestState\)/);
@@ -494,6 +549,9 @@ function updateSignupMethodUI() {
function syncSignupPhoneInputFromState() {
rowSignupPhone.style.display = inputPhoneVerificationEnabled.checked && latestState.signupPhoneNumber ? '' : 'none';
}
function setFreePhoneReuseControlsLocked() {}
function isAutoRunLockedPhase() { return false; }
function isAutoRunScheduledPhase() { return false; }
${extractFunction('updatePhoneVerificationSettingsUI')}
@@ -686,6 +744,8 @@ const inputAutoDelayEnabled = { checked: false };
const inputAutoDelayMinutes = { value: '30' };
const inputAutoStepDelaySeconds = { value: '' };
const inputPhoneVerificationEnabled = { checked: true };
const inputFreePhoneReuseEnabled = { checked: true };
const inputFreePhoneReuseAutoEnabled = { checked: true };
const selectPhoneSmsProvider = { value: 'hero-sms' };
const inputVerificationResendCount = { value: '4' };
const inputHeroSmsApiKey = { value: 'demo-key' };
@@ -832,6 +892,8 @@ return { collectSettingsPayload };
assert.deepStrictEqual(payload.nexSmsCountryOrder, [1]);
assert.equal(payload.nexSmsServiceCode, 'ot');
assert.equal(payload.heroSmsReuseEnabled, true);
assert.equal(payload.freePhoneReuseEnabled, true);
assert.equal(payload.freePhoneReuseAutoEnabled, true);
assert.equal(payload.heroSmsAcquirePriority, 'price');
assert.equal(payload.heroSmsMaxPrice, '0.12');
assert.equal(payload.heroSmsPreferredPrice, '0.0512');