Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 60 additions & 1 deletion src/browser/auth/Login.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Page } from 'patchright'
import type { MicrosoftRewardsBot } from '../../index'
import { saveSessionData } from '../../util/Load'
import { saveSessionData, setRateLimitCooldown, getRateLimitCooldown } from '../../util/Load'

import { MobileAccessLogin } from './methods/MobileAccessLogin'
import { EmailLogin } from './methods/EmailLogin'
Expand Down Expand Up @@ -30,13 +30,15 @@ type LoginState =
| 'OTP_CODE_ENTRY'
| 'UNKNOWN'
| 'CHROMEWEBDATA_ERROR'
| 'TOO_MANY_REQUESTS'

export class Login {
emailLogin: EmailLogin
passwordlessLogin: PasswordlessLogin
totp2FALogin: TotpLogin
codeLogin: CodeLogin
recoveryLogin: RecoveryLogin
private loginRetryCount = 0

private readonly selectors = {
primaryButton: 'button[data-testid="primaryButton"]',
Expand Down Expand Up @@ -76,8 +78,26 @@ export class Login {

async login(page: Page, account: Account) {
try {
this.loginRetryCount = 0
this.bot.logger.info(this.bot.isMobile, 'LOGIN', 'Starting login process')

// Check global IP-based rate limit cooldown
const remainingCooldown = getRateLimitCooldown(this.bot.config.sessionPath)
if (remainingCooldown > 0) {
const { maxAttempts } = this.bot.config.loginRateLimit!
if (this.loginRetryCount >= maxAttempts) {
const msg = 'IP is rate limited and max retries exhausted, skipping account'
this.bot.logger.error(this.bot.isMobile, 'LOGIN', msg)
throw new Error(msg)
}
this.bot.logger.warn(
this.bot.isMobile,
'LOGIN',
`IP rate limit active, waiting remaining ${Math.ceil(remainingCooldown / 1000)}s`
)
await this.bot.utils.wait(remainingCooldown)
}

await page
.goto('https://rewards.bing.com/createuser?idru=%2F&userScenarioId=anonsignin', {
waitUntil: 'domcontentloaded'
Expand Down Expand Up @@ -168,6 +188,15 @@ export class Login {
return 'CHROMEWEBDATA_ERROR'
}

// Check for "too many requests" rate limiting on post-srf page
if (url.hostname === 'login.live.com' && url.pathname === '/ppsecure/post.srf') {
const pageContent = await page.content().catch(() => '')
if (pageContent.toLowerCase().includes('too many requests')) {
this.bot.logger.debug(this.bot.isMobile, 'DETECT-STATE', 'Detected "too many requests" rate limit page')
return 'TOO_MANY_REQUESTS'
}
}

const isLocked = await this.checkSelector(page, this.selectors.accountLocked)
if (isLocked) {
this.bot.logger.debug(this.bot.isMobile, 'DETECT-STATE', 'Account locked selector found')
Expand Down Expand Up @@ -457,6 +486,36 @@ export class Login {
}
}

case 'TOO_MANY_REQUESTS': {
const { delay, maxAttempts } = this.bot.config.loginRateLimit!
this.loginRetryCount++

if (this.loginRetryCount > maxAttempts) {
const msg = `Rate limit retry exhausted after ${maxAttempts} attempts, skipping account`
this.bot.logger.error(this.bot.isMobile, 'LOGIN', msg)
throw new Error(msg)
}

const delayMs = this.bot.utils.stringToNumber(delay)

// Set global cooldown so other accounts/workers are aware
setRateLimitCooldown(this.bot.config.sessionPath, delayMs)
this.bot.logger.warn(
this.bot.isMobile,
'LOGIN',
`Too many requests detected, retrying in ${delay} (${this.loginRetryCount}/${maxAttempts})`
)
await this.bot.utils.wait(delayMs)
await page.reload({ waitUntil: 'domcontentloaded' }).catch(() => {})
await this.bot.utils.wait(2000)
this.bot.logger.info(
this.bot.isMobile,
'LOGIN',
`Retry ${this.loginRetryCount}/${maxAttempts} after rate limit`
)
return true
}

case '2FA_TOTP': {
this.bot.logger.info(this.bot.isMobile, 'LOGIN', 'TOTP 2FA authentication required')
await this.totp2FALogin.handle(page, account.totpSecret)
Expand Down
4 changes: 4 additions & 0 deletions src/config.example.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
},
"searchOnBingLocalQueries": false,
"globalTimeout": "30sec",
"loginRateLimit": {
"delay": "5min",
"maxAttempts": 3
},
"searchSettings": {
"scrollRandomResults": false,
"clickRandomResults": false,
Expand Down
6 changes: 6 additions & 0 deletions src/interface/Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,19 @@ export interface Config {
workers: ConfigWorkers
searchOnBingLocalQueries: boolean
globalTimeout: number | string
loginRateLimit?: ConfigLoginRateLimit
searchSettings: ConfigSearchSettings
debugLogs: boolean
proxy: ConfigProxy
consoleLogFilter: LogFilter
webhook: ConfigWebhook
}

export interface ConfigLoginRateLimit {
delay: number | string
maxAttempts: number
}

export type QueryEngine = 'google' | 'wikipedia' | 'reddit' | 'local'

export interface ConfigSearchSettings {
Expand Down
41 changes: 41 additions & 0 deletions src/util/Load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,44 @@ export async function saveFingerprintData(
throw new Error(error as string)
}
}

const RATE_LIMIT_FILE = '.rate-limit-cooldown'

function getRateLimitFilePath(sessionPath: string): string {
return path.join(__dirname, '../browser/', sessionPath, RATE_LIMIT_FILE)
}

export function setRateLimitCooldown(sessionPath: string, delayMs: number): void {
const filePath = getRateLimitFilePath(sessionPath)
const dir = path.dirname(filePath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
const expiry = Date.now() + delayMs
fs.writeFileSync(filePath, String(expiry))
}

export function getRateLimitCooldown(sessionPath: string): number {
const filePath = getRateLimitFilePath(sessionPath)
if (!fs.existsSync(filePath)) {
return 0
}
const expiry = parseInt(fs.readFileSync(filePath, 'utf-8').trim(), 10)
if (isNaN(expiry)) {
fs.unlinkSync(filePath)
return 0
}
const remaining = expiry - Date.now()
if (remaining <= 0) {
fs.unlinkSync(filePath)
return 0
}
return remaining
}

export function clearRateLimitCooldown(sessionPath: string): void {
const filePath = getRateLimitFilePath(sessionPath)
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath)
}
}
7 changes: 7 additions & 0 deletions src/util/Validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ export const ConfigSchema = z.object({
}),
searchOnBingLocalQueries: z.boolean(),
globalTimeout: NumberOrString,
loginRateLimit: z
.object({
delay: NumberOrString,
maxAttempts: z.number().int().positive().max(100)
})
.optional()
.default({ delay: '5min', maxAttempts: 3 }),
searchSettings: z.object({
scrollRandomResults: z.boolean(),
clickRandomResults: z.boolean(),
Expand Down