Skip to content
Draft
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
2 changes: 1 addition & 1 deletion env.example
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ ACCOUNT_1_EMAIL=email@example.com
#ACCOUNT_1_RECOVERY_EMAIL=
#ACCOUNT_1_GEO_LOCALE=auto
#ACCOUNT_1_LANG_CODE=en
# Browser proxy: HTTP/HTTPS/SOCKS4/SOCKS5. SOCKS proxies must not require authentication.
# Browser proxy: HTTP/HTTPS/SOCKS4/SOCKS5.
#ACCOUNT_1_PROXY_HTTP=false
#ACCOUNT_1_PROXY_URL=
#ACCOUNT_1_PROXY_PORT=0
Expand Down
71 changes: 71 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"otpauth": "^9.5.1",
"p-queue": "^9.3.0",
"patchright": "^1.61.1",
"proxy-chain": "^3.0.1",
"semver": "^7.8.1",
"ts-node": "^10.9.2",
"zod": "^4.4.3"
Expand Down
23 changes: 14 additions & 9 deletions src/browser/Browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,20 @@ class Browser {
let browser: rebrowser.Browser
try {
const proxyConfig = account.proxy.url
? {
server: formatBrowserProxyServer(account.proxy.url, account.proxy.port),
...(account.proxy.username &&
account.proxy.password && {
username: account.proxy.username,
password: account.proxy.password
})
}
: undefined
? {
server:
account.proxy.bridgeUrl ??
formatBrowserProxyServer(account.proxy.url, account.proxy.port),

...(!account.proxy.bridgeUrl &&
account.proxy.username &&
account.proxy.password && {
username: account.proxy.username,
password: account.proxy.password
})
}
: undefined


const runningAsRoot = typeof process.getuid === 'function' && process.getuid() === 0
const sandboxDisabled = process.platform === 'linux' && runningAsRoot
Expand Down
54 changes: 50 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ import { SearchManager } from './functions/activities/search/SearchManager'

import type { Account } from './interface/Account'
import HttpClient from './util/Http'
import { parseBrowserProxyUrl } from './util/Proxy'
import { startAuthenticatedSocks5Bridge } from './util/ProxyBridge'
import { sendDiscord, flushDiscordQueue } from './logging/Discord'
import { sendNtfy, flushNtfyQueue } from './logging/Ntfy'
import { sendTelegram, flushTelegramQueue } from './logging/Telegram'
Expand Down Expand Up @@ -419,6 +421,10 @@ export class MicrosoftRewardsBot {
this.userData.userName = this.utils.getEmailUsername(accountEmail)
this.userData.timezoneOffset = String(new Date().getTimezoneOffset())

let proxyBridge:
| Awaited<ReturnType<typeof startAuthenticatedSocks5Bridge>>
| undefined

try {
const cachedRegion =
account.geoLocale === 'auto' ? loadResolvedRegion(this.config.sessionPath, accountEmail) : undefined
Expand All @@ -434,11 +440,33 @@ export class MicrosoftRewardsBot {
}`
)

this.http = new HttpClient(account.proxy, {
'Accept-Language': this.accountLocale.acceptLanguage
})

const configuredProxy = account.proxy.url
? parseBrowserProxyUrl(account.proxy.url)
: undefined

if (
configuredProxy?.protocol === 'socks5:' &&
account.proxy.username &&
account.proxy.password
) {
proxyBridge = await startAuthenticatedSocks5Bridge(account.proxy)

// Browser.ts and Http.ts use this runtime-only URL.
account.proxy.bridgeUrl = proxyBridge.url

this.logger.info(
'main',
'PROXY-BRIDGE',
`Authenticated SOCKS5 bridge started for ${accountEmail}`
)
}

const result: AccountRunResult | undefined = await this.Main(account).catch(error => {
this.http = new HttpClient(account.proxy, {
'Accept-Language': this.accountLocale.acceptLanguage
})

const result: AccountRunResult | undefined = await this.Main(account).catch(error => {
void this.logger.error(
true,
'FLOW',
Expand Down Expand Up @@ -516,6 +544,24 @@ export class MicrosoftRewardsBot {
error: error instanceof Error ? error.message : String(error)
})
}

finally {
try {
if (proxyBridge) {
await proxyBridge.close()
}
} catch (error) {
this.logger.warn(
'main',
'PROXY-BRIDGE',
`Failed to close SOCKS5 bridge for ${accountEmail}: ${
error instanceof Error ? error.message : String(error)
}`
)
} finally {
delete account.proxy.bridgeUrl
}
}
}

if (this.config.clusters <= 1 && cluster.isPrimary) {
Expand Down
11 changes: 11 additions & 0 deletions src/interface/Account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,14 @@ export interface ConfigSaveFingerprint {
mobile: boolean
desktop: boolean
}

export interface AccountProxy {
proxyHttp: boolean
url: string
port: number
password: string
username: string

// Internal runtime property; not configured through .env.
bridgeUrl?: string
}
4 changes: 3 additions & 1 deletion src/util/Http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,9 @@ class HttpClient {
this.account = account
this.defaultHeaders = { ...defaultHeaders }

const proxyUrl = this.account.url && this.account.proxyHttp ? this.buildProxyUrl(this.account) : undefined
const proxyUrl = this.account.url && this.account.proxyHttp
? (this.account.bridgeUrl ?? this.buildProxyUrl(this.account))
: undefined

this.instance = new Impit({ browser: 'chrome', proxyUrl, timeout: DEFAULT_TIMEOUT })
}
Expand Down
50 changes: 50 additions & 0 deletions src/util/ProxyBridge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { anonymizeProxy, closeAnonymizedProxy } from 'proxy-chain'
import type { AccountProxy } from '../interface/Account'
import { parseBrowserProxyUrl } from './Proxy'

export async function startAuthenticatedSocks5Bridge(
proxy: AccountProxy
): Promise<{ url: string; close: () => Promise<void> }> {
const parsed = parseBrowserProxyUrl(proxy.url)

if (parsed.protocol !== 'socks5:') {
throw new Error('Authenticated SOCKS5 bridge requires a socks5:// proxy')
}

if (!proxy.username || !proxy.password) {
throw new Error('SOCKS5 bridge requires both username and password')
}

if (!Number.isInteger(proxy.port) || proxy.port < 1 || proxy.port > 65535) {
throw new Error('Invalid SOCKS5 proxy port')
}

// Use socks5h so hostname resolution is performed through the upstream proxy.
const upstream = new URL(`socks5h://${parsed.hostname}:${proxy.port}`)
upstream.username = encodeURIComponent(proxy.username)
upstream.password = encodeURIComponent(proxy.password)

const upstreamUrl = upstream.toString()

// proxy-chain opens a temporary loopback HTTP proxy.
const localUrl = await anonymizeProxy({
url: upstreamUrl,
port: 0
})

// Fail closed: never silently continue with the upstream URL directly.
if (!localUrl.startsWith('http://127.0.0.1:')) {
if (localUrl === upstreamUrl) {
throw new Error('Failed to create local SOCKS5 proxy bridge')
}

throw new Error('Unexpected local proxy bridge address')
}

return {
url: localUrl,
close: async () => {
await closeAnonymizedProxy(localUrl, true)
}
}
}
8 changes: 4 additions & 4 deletions src/util/Validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,13 +222,13 @@ const AccountProxySchema = z
})
}

if ((url.protocol === 'socks4:' || url.protocol === 'socks5:') && (hasUsername || hasPassword)) {
if (url.protocol === 'socks4:' && (hasUsername || hasPassword)) {
ctx.addIssue({
code: 'custom',
path: ['username'],
message: `${url.protocol.slice(0, -1).toUpperCase()} proxy authentication is not supported by Patchright`
})
}
message: 'SOCKS4 proxy authentication is not supported'
})
}
})

export const AccountSchema = z.object({
Expand Down