File size: 18,035 Bytes
6c6d16c a9c5abb 6c6d16c 11a8eb2 6c6d16c 11a8eb2 6c6d16c 11a8eb2 6c6d16c 0b827be 6c6d16c 11a8eb2 6c6d16c 11a8eb2 6c6d16c 8314b51 11a8eb2 8314b51 11a8eb2 8314b51 3ed7406 8314b51 11a8eb2 8314b51 11a8eb2 8314b51 6c6d16c b8a045d 6c6d16c 3f6e692 6c6d16c b8a045d 3f6e692 b8a045d 3f6e692 11a8eb2 255f23a 11a8eb2 6c6d16c b8a045d 6c6d16c b8a045d 6c6d16c 0b827be 6c6d16c b8a045d 6c6d16c b8a045d 6c6d16c 1877b95 6c6d16c b8a045d 6c6d16c 9ad5679 6c6d16c 0b827be 3f6e692 0b827be 11a8eb2 0b827be 6c6d16c 11a8eb2 6c6d16c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 |
import { Page } from 'playwright';
import BrowserManager from './browser.js';
import { getVerificationCode } from './emailVerification.js';
import { saveScreenshot, saveDebugInfo, saveErrorInfo } from './debugStorage.js';
interface Account {
email: string;
password: string;
proofEmail: string;
}
export class AuthService {
constructor(private env: Env) { }
async authenticateEmail(email: string): Promise<{ success: boolean; error?: string }> {
try {
const accountsStr = await this.env.KV.get("accounts");
const accounts: Account[] = accountsStr ? JSON.parse(accountsStr) : [];
const account = accounts.find(a => a.email === email);
if (!account) {
throw new Error("Account not found");
}
await this.performAuthentication(account);
await this.handleAuthorizationCallback(email);
return { success: true };
} catch (error: any) {
return {
success: false,
error: error.message
};
}
}
private async performAuthentication(account: Account) {
const clientId = this.env.ENTRA_CLIENT_ID;
const redirectUri = this.env.AUTH_REDIRECT_URI;
let browser;
let context;
let page;
const debugId = `auth_${account.email}_${Date.now()}`;
try {
browser = await BrowserManager.getInstance();
context = await browser.newContext();
page = await context.newPage();
const authUrl = this.buildAuthUrl(clientId, redirectUri, account.email);
await this.handleLoginProcess(page, account, authUrl);
await this.handleMultiFactorAuth(page, account);
await this.confirmLogin(page, account);
await this.handleConsent(page, redirectUri);
} catch (error) {
// 记录错误信息
const errorInfo = {
email: account.email,
error: error instanceof Error ? error.message : String(error),
timestamp: new Date().toISOString(),
debugId: debugId
};
try {
await saveErrorInfo(debugId, errorInfo);
} catch (saveError) {
console.error('Failed to save error info:', saveError);
}
throw error;
} finally {
// 截取最后的页面截图
if (page) {
try {
const screenshot = await page.screenshot({
fullPage: true,
type: 'png'
});
const screenshotInfo = {
email: account.email,
timestamp: new Date().toISOString(),
debugId: debugId,
url: page.url(),
title: await page.title().catch(() => 'Unknown')
};
// 保存截图和调试信息到本地文件
await saveScreenshot(debugId, screenshot);
await saveDebugInfo(debugId, screenshotInfo);
console.log(`Screenshot saved for debug: ${debugId}`);
} catch (screenshotError) {
console.error('Failed to take screenshot:', screenshotError);
}
}
if (context) await context.close();
}
}
private buildAuthUrl(clientId: string, redirectUri: string, email: string): string {
return `https://login.microsoftonline.com/common/oauth2/v2.0/authorize?` +
`client_id=${clientId}` +
`&response_type=code` +
`&redirect_uri=${encodeURIComponent(redirectUri)}` +
`&response_mode=query` +
`&scope=offline_access%20IMAP.AccessAsUser.All%20User.Read%20Mail.ReadWrite.Shared%20Mail.Send%20Mail.Read` +
`&prompt=consent` +
`&state=${email}`;
}
public async loginMail(email: string): Promise<{ success: boolean; error?: string }> {
let browser;
let context;
let page;
const debugId = `login_${email}_${Date.now()}`;
try {
const accountsStr = await this.env.KV.get("accounts");
const accounts: Account[] = accountsStr ? JSON.parse(accountsStr) : [];
const account = accounts.find(a => a.email === email);
if (!account) {
throw new Error("Account not found");
}
browser = await BrowserManager.getInstance();
context = await browser.newContext();
page = await context.newPage();
await this.handleLoginProcess(page, account, "https://outlook.live.com/mail/0/?prompt=select_account");
await this.handleMultiFactorAuth(page, account);
await this.confirmLogin(page, account);
await page.waitForTimeout(5000);
return { success: true };
} catch (error: any) {
// 记录错误信息
const errorInfo = {
email: email,
error: error instanceof Error ? error.message : String(error),
timestamp: new Date().toISOString(),
debugId: debugId
};
try {
await saveErrorInfo(debugId, errorInfo);
} catch (saveError) {
console.error('Failed to save error info:', saveError);
}
return {
success: false,
error: error.message
};
} finally {
// 截取最后的页面截图
if (page) {
try {
const screenshot = await page.screenshot({
fullPage: true,
type: 'png'
});
const screenshotInfo = {
email: email,
timestamp: new Date().toISOString(),
debugId: debugId,
url: page.url(),
title: await page.title().catch(() => 'Unknown')
};
// 保存截图和调试信息到本地文件
await saveScreenshot(debugId, screenshot);
await saveDebugInfo(debugId, screenshotInfo);
console.log(`Screenshot saved for debug: ${debugId}`);
} catch (screenshotError) {
console.error('Failed to take screenshot:', screenshotError);
}
}
if (context) await context.close();
}
}
private async handleLoginProcess(page: Page, account: Account, authUrl: string) {
await page.goto(authUrl);
await page.fill('input[type="email"]', account.email);
await page.click('input[type="submit"]');
try {
await page.waitForSelector('#idA_PWD_SwitchToPassword', { timeout: 3000 });
await page.click('#idA_PWD_SwitchToPassword');
} catch (error) {
console.log(account.email, `没有旧版切换到密码登录,继续执行: ${error}`);
}
try {
const passwordButtonByRole = page.getByRole('button', { name: '其他登录方法' });
if (await passwordButtonByRole.isVisible({ timeout: 3000 })) {
await passwordButtonByRole.click();
await page.waitForTimeout(1000); // 等待页面稳定
}
} catch (error) {
console.log(account.email, `没有新版切换到其他登录方法,继续执行: ${error}`);
}
try {
const passwordButtonByRole = page.getByRole('button', { name: '使用密码' });
if (await passwordButtonByRole.isVisible({ timeout: 3000 })) {
await passwordButtonByRole.click();
await page.waitForTimeout(1000); // 等待页面稳定
}
} catch (error) {
console.log(account.email, `没有新版切换到密码登录,继续执行: ${error}`);
}
try {
await page.waitForURL((url) => {
return url.href.startsWith('https://login.live.com/oauth20_authorize.srf');
}, { timeout: 30000 });
// 填写密码 - 双重填写确保成功
await page.fill('input[type="password"]', account.password);
await page.waitForTimeout(500); // 等待页面稳定
await page.fill('input[type="password"]', account.password);
await page.click('button[type="submit"]');
await page.waitForTimeout(2000); // 等待提交处理
} catch (error) {
console.log(account.email, `填写密码失败: ${error}`);
}
const proofEmail = account.proofEmail;
try {
await page.waitForURL((url) => {
return url.href.startsWith('https://account.live.com/recover');
}, { timeout: 3000 });
await page.click('input[type="submit"]#iLandingViewAction');
const timestamp = Math.floor(Date.now() / 1000);
await page.fill("#iProofEmail", proofEmail)
await page.click('input[type="submit"]')
const proofConfig = this.getProofConfig(proofEmail);
const verificationCode = await getVerificationCode(proofConfig.apiUrl, proofConfig.token!, proofEmail, timestamp);
await page.fill('input[type="tel"]', verificationCode);
await page.click('input[type="submit"]');
//可能需要修改密码..这里就不处理了
} catch (error) {
console.log(account.email, `没有帮助我们保护帐户确认,继续执行: ${error}`);
}
try {
//新版的邮箱验证
await page.waitForURL((url) => {
return url.href.startsWith('https://login.live.com/oauth20_authorize.srf');
}, { timeout: 3000 });
const timestamp = Math.floor(Date.now() / 1000);
await page.fill("#proof-confirmation-email-input", proofEmail)
await page.click('button[type="submit"]')
const proofConfig = this.getProofConfig(proofEmail);
const verificationCode = await getVerificationCode(proofConfig.apiUrl, proofConfig.token!, proofEmail, timestamp);
await page.fill('input#codeEntry-0', verificationCode[0]);
await page.fill('input#codeEntry-1', verificationCode[1]);
await page.fill('input#codeEntry-2', verificationCode[2]);
await page.fill('input#codeEntry-3', verificationCode[3]);
await page.fill('input#codeEntry-4', verificationCode[4]);
await page.fill('input#codeEntry-5', verificationCode[5]);
//可能需要修改密码..这里就不处理了
} catch (error) {
console.log(account.email, `没有帮助我们保护帐户确认,继续执行: ${error}`);
}
}
private getProofConfig(proofEmail: string) {
const proof = [
{
"suffix": "godgodgame.com",
"apiUrl": "https://seedmail.igiven.com/api/latest-email",
"token": this.env.PROOF_GODGODGAME_TOKEN
},
{
"suffix": "igiven.com",
"apiUrl": "https://mail.igiven.com/api/latest-email",
"token": this.env.PROOF_IGIVEN_TOKEN
}
];
const suffix = proofEmail.substring(proofEmail.indexOf('@') + 1);
const proofConfig = proof.find(p => p.suffix === suffix)!;
return proofConfig;
}
private async handleMultiFactorAuth(page: Page, account: Account) {
for (let i = 0; i < 3; i++) {
try {
await page.waitForURL('https://account.live.com/identity/**', { timeout: 5000 });
const proofEmail = account.proofEmail;
if (!proofEmail) {
throw new Error("No proof email provided");
}
const timestamp = Math.floor(Date.now() / 1000);
try {
await page.waitForSelector('#iProof0', { timeout: 3000 });
await page.click('#iProof0');
} catch (error) {
console.log(`没有#iProof0,继续执行: ${error}`);
}
await page.fill("#iProofEmail", proofEmail);
await page.click('input[type="submit"]');
const proofConfig = this.getProofConfig(proofEmail);
const verificationCode = await getVerificationCode(
proofConfig.apiUrl,
proofConfig.token!,
proofEmail,
timestamp
);
await page.fill('input[type="tel"]', verificationCode);
await page.click('input[type="submit"]');
await page.waitForTimeout(5 * 1000)
} catch (error) {
console.log(account.email, `没有多重验证,继续执行: ${error}`);
}
}
}
async confirmLogin(page: Page, account: Account) {
try {
await page.waitForURL('https://account.live.com/interrupt/**', { timeout: 3000 });
// 尝试查找"暂时跳过"按钮
const skipButtonExists = await page.isVisible('button[data-testid="secondaryButton"]', { timeout: 5000 });
if (skipButtonExists) {
console.log(account.email, "找到新版'暂时跳过'按钮,正在点击...");
await page.click('button[data-testid="secondaryButton"]');
}
// 最后尝试你提到的另一个按钮
const otherButtonExists = await page.isVisible('div[data-testid="textButtonContainer"] > div:first-child > button[type="button"]', { timeout: 5000 });
if (otherButtonExists) {
console.log(account.email, "找到旧版'暂时跳过'按钮,正在点击...");
await page.click('div[data-testid="textButtonContainer"] > div:first-child > button[type="button"]');
}
} catch (error) {
//暂时跳过.下一个.获取微软的通行密钥软件
console.log(account.email, `无获取通行密钥提示,继续执行: ${error}`);
}
try {
//和下面一样.随机出现
await page.waitForURL('https://login.live.com/ppsecure/**', { timeout: 3000 });
//新版可能有问题.换成如下.
//await page.click('#acceptButton', { timeout: 10000 });
//await page.locator('button[type="submit"]').nth(0).click({ timeout: 10000 });
await page.locator('button[type="submit"]').first().click({ timeout: 10000 });
} catch (error) {
console.log(account.email, `无ppsecure登录确认,继续执行: ${error}`);
}
try {
//和上面一样.随机出现
await page.waitForURL((url) => {
return url.href.startsWith('https://login.live.com/oauth20_authorize.srf');
}, { timeout: 3000 });
await page.click('button[type="submit"]', { timeout: 10000 });
} catch (error) {
console.log(account.email, `无oauth20_authorize登录确认,继续执行: ${error}`);
}
try {
//旧版的登录确认
await page.waitForURL((url) => {
return url.href.startsWith('https://login.live.com');
}, { timeout: 3000 });
await page.click('button[type="submit"]#acceptButton', { timeout: 3000 });
} catch (error) {
console.log(account.email, `无旧版的登录确认,继续执行: ${error}`);
}
}
private async handleConsent(page: Page, redirectUri: string) {
try {
await page.waitForURL("https://account.live.com/Consent/**", { timeout: 20000 });
await page.click('button[type="submit"][data-testid="appConsentPrimaryButton"]');
} catch (error) {
console.log("Consent page not found or timeout, skipping...");
}
await page.waitForURL((url: any) => url.href.startsWith(redirectUri));
}
private async handleAuthorizationCallback(email: string) {
let code = null;
const maxRetries = 30;
let retries = 0;
while (!code && retries < maxRetries) {
const codeKey = `code_${email}`;
code = await this.env.KV.get(codeKey);
if (!code) {
await new Promise(resolve => setTimeout(resolve, 1000));
retries++;
}
}
if (!code) {
throw new Error("Authorization timeout");
}
const tokenResponse = await fetch('https://login.microsoftonline.com/common/oauth2/v2.0/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
client_id: this.env.ENTRA_CLIENT_ID,
client_secret: this.env.ENTRA_CLIENT_SECRET,
code: code,
redirect_uri: this.env.AUTH_REDIRECT_URI,
grant_type: 'authorization_code'
})
});
const tokenData: any = await tokenResponse.json();
if (!tokenData.refresh_token) {
throw new Error("Failed to get refresh token");
}
if (!tokenData.expires_in) {
throw new Error("Missing expires_in in token response");
}
const tokenInfo = {
...tokenData,
timestamp: Date.now()
};
await this.env.KV.put(`refresh_token_${email}`, JSON.stringify(tokenInfo));
await this.env.KV.delete(`code_${email}`);
}
} |