32 Commits
v3.0.2 ... v2

Author SHA1 Message Date
Netsky
cb3c249d8b Remove thumbnail and icon_url from ConclusionWebhook
Removed thumbnail and icon_url from footer.
2025-12-27 15:11:38 +01:00
Netsky
d76106d3cc Update URL for fetching queries from GitHub (v2) 2025-12-13 15:33:52 +01:00
Netsky
f5c7ff4907 Delete setup directory 2025-11-11 11:17:41 +01:00
Netsky
d6d3b05836 Revise Nix setup instructions in README
Updated Nix setup instructions for clarity and structure.
2025-11-11 11:16:19 +01:00
Netsky
ba4155bf3f Update run.sh 2025-11-11 11:15:04 +01:00
Netsky
03aa7f167f Add pre-build step before starting script 2025-11-11 11:14:26 +01:00
Netsky
a37d60a9df Revise README for clarity and structure
Updated the README to improve setup instructions and organization.
2025-11-11 11:12:58 +01:00
TheNetsky
2738c85030 2.4.1
THIS IS A HOTFIX TO THE CURRENT STATE TO FIX SOME DOCKER AND STABILITY RELATED ISSUES. ALSO TO REMOVE SOME DEAD CODE.
A PROPER VERSION OF "V2" IS BEING WORKED ON!

- Migrated configuration files from JSONC to JSON
- Removed deprecated setup scripts
- Updated dependencies in package.json and package-lock.json
- Updated README with expanded setup, configuration, and feature documentation
2025-11-10 10:56:57 +01:00
Michael Cammarata
bd96aeb20c Update permissions and line endings in dockerfile (#410)
* Preliminary dockerization with scheduling

Porting working docker implementation (scheduling, etc.) into revised v2

* Update dockerfile to fix line endings for non-unix docker users

* Update dockerfile to fix line endings for non-unix docker users

* Update dockerfile permissions and line endings

Ensure proper permissions and line endings for all scripts for non-Unix docker users

---------

Co-authored-by: Netsky <56271887+TheNetsky@users.noreply.github.com>
2025-11-06 07:42:08 +01:00
Michael Cammarata
996d9485cd Dockerfile, handle non-unix docker users (#409)
* Preliminary dockerization with scheduling

Porting working docker implementation (scheduling, etc.) into revised v2

* Update dockerfile to fix line endings for non-unix docker users

* Update dockerfile to fix line endings for non-unix docker users

---------

Co-authored-by: Netsky <56271887+TheNetsky@users.noreply.github.com>
2025-11-05 15:18:45 +01:00
1OSA
6b6028bb52 Enable health check for cron daemon (#408)
Thanks!
2025-11-05 13:39:30 +01:00
Netsky
368417c5d8 Change login URL to Bing rewards dashboard 2025-11-05 13:12:48 +01:00
Michael Cammarata
49b607d78c Preliminary dockerization with scheduling (#406)
Porting working docker implementation (scheduling, etc.) into revised v2

Co-authored-by: Netsky <56271887+TheNetsky@users.noreply.github.com>
2025-11-04 21:10:46 +01:00
Netsky
8c8bdaf3e5 Change command from 'start:schedule' to 'start' 2025-11-04 19:42:33 +01:00
Netsky
7f0da3098d Change CMD to run 'start' instead of 'start:schedule' 2025-11-04 15:11:13 +01:00
Simon Gardling
398c6db4ad Delete BanPredictor + RiskManager (#404)
Both are completely bogus code and is never even imported or used
2025-11-04 07:33:38 +01:00
Simon Gardling
169faf2b70 Cleanup v2 codebase (#403)
* Remove diagnostics system

* Remove Analytics system

* Remove Buy Mode feature

* Remove Scheduler/heartbeat

* Index: remove printBanner

* Remove auto-update functionality
2025-11-03 21:16:38 +01:00
Simon Gardling
8e9c6308d5 Login: Fix 'Other Ways to Sign In' menu (#402) 2025-11-03 17:17:32 +01:00
Netsky
b2ed289bba Add GNU General Public License v3
Added the GNU General Public License version 3 to the project.
2025-11-03 11:35:51 +01:00
Netsky
2c413dad99 Delete LICENSE 2025-11-03 11:35:01 +01:00
Netsky
5aa05804be Delete docs directory 2025-11-03 11:34:44 +01:00
Netsky
3c1778a7e5 Delete SECURITY.md 2025-11-03 11:33:20 +01:00
Netsky
b78cea16ae Revise README 2025-11-03 11:32:45 +01:00
Light
a9e5693b71 V2.4.0 complete (#395)
* V2.4.0 (#381)

* Updated README.md to reflect version 2.1 and improve the presentation of Microsoft Rewards Automation features.

* Updated version to 2.1.5 in README.md and package.json, added new license and legal notice sections, and improved the configuration script for a better user experience.

* Mise à jour des messages de journalisation et ajout de vérifications pour le chargement des quiz et la présence des options avant de procéder. Suppression de fichiers de configuration obsolètes.

* Added serial protection dialog management for message forwarding, including closing by button or escape.

* feat: Implement BanPredictor for predicting ban risks based on historical data and real-time events

feat: Add ConfigValidator to validate configuration files and catch common issues

feat: Create QueryDiversityEngine to fetch diverse search queries from multiple sources

feat: Develop RiskManager to monitor account activity and assess risk levels dynamically

* Refactor code for consistency and readability; unify string quotes, improve logging with contextual emojis, enhance configuration validation, and streamline risk management logic.

* feat: Refactor BrowserUtil and Login classes for improved button handling and selector management; implement unified selector system and enhance activity processing logic in Workers class.

* feat: Improve logging with ASCII context icons for better compatibility with Windows PowerShell

* feat: Add sample account setup

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* feat: Update Node.js engine requirement to >=20.0.0 and improve webhook avatar handling and big fix Schedule

* Update README.md

* feat: Improve logging for Google Trends search queries and adjust fallback condition

* feat: Update version to 2.2.1 and enhance dashboard data retrieval with improved error handling

* feat: Update version to 2.2.2 and add terms update dialog dismissal functionality

* feat: Update version to 2.2.2 and require Node.js engine >=20.0.0

* feat: Ajouter un fichier de configuration complet pour la gestion des tâches et des performances

* feat: Mettre à jour la version à 2.2.3, modifier le fuseau horaire par défaut et activer les rapports d'analyse

* feat: update doc

* feat: update doc

* Refactor documentation for proxy setup, security guide, and auto-update system

- Updated proxy documentation to streamline content and improve clarity.
- Revised security guide to emphasize best practices and incident response.
- Simplified auto-update documentation, enhancing user understanding of the update process.
- Removed redundant sections and improved formatting for better readability.

* feat: update version to 2.2.7 in package.json

* feat: update version to 2.2.7 in README.md

* feat: improve quiz data retrieval with alternative variables and debug logs

* feat: refactor timeout and selector constants for improved maintainability

* feat: update version to 2.2.8 in package.json and add retry limits in constants

* feat: enhance webhook logging with username, avatar, and color-coded messages

* feat: update .gitignore to include diagnostic folder and bump version to 2.2.8 in package-lock.json

* feat: updated version to 2.3.0 and added new constants to improve the handling of delays and colors in logs

* feat: refactor ConclusionWebhook to improve structure and enhance message formatting

* feat: update setup scripts and version to 2.3.3, refactor paths for improved structure

* feat: refactor setup scripts to run via npm and improve error handling for package.json

* feat: refactor webhook avatar handling to use centralized constant from constants.ts

* feat: mettre à jour la version à 2.3.7 et améliorer le script de mise à jour avec des options de contrôle d'auto-mise à jour

* feat: activer la mise à jour automatique pour la configuration et les comptes

* feat: mettre à jour la version à 2.3.7 et améliorer la gestion des erreurs dans plusieurs fichiers

* feat: améliorer la gestion des erreurs et des délais dans plusieurs fichiers, y compris Axios et ConclusionWebhook

* feat: mettre à jour la version à 2.4.0 et améliorer la documentation sur le contrôle de mise à jour automatique

* feat: increase the number of passes per execution to 3 to improve task capture

* feat: update account management with new file format and filter disabled accounts

* feat: update version to 2.4.0, add reinstallation warning and support .jsonc extensions for configuration files

* fix: fix formatting of reinstallation message in README

* feat: add an important update notice in the README to recommend a complete reinstallation

* fix: remove backup instructions from installation guide in README

* fix: update notice in README for configuration file changes and fresh installation instructions

* fix: fix typographical error in README update notice

* Fix: Update avatar URL in Discord config and remove optional webhook properties

* exploit: add customization options for webhooks and improve notification format

* Fix build
2025-10-23 16:35:32 +02:00
Netsky
2a8ab7242f Revert "V2.4.0 (#381)" (#392)
This reverts commit f2d00225c9.
2025-10-23 13:36:09 +02:00
Light
f2d00225c9 V2.4.0 (#381)
* Updated README.md to reflect version 2.1 and improve the presentation of Microsoft Rewards Automation features.

* Updated version to 2.1.5 in README.md and package.json, added new license and legal notice sections, and improved the configuration script for a better user experience.

* Mise à jour des messages de journalisation et ajout de vérifications pour le chargement des quiz et la présence des options avant de procéder. Suppression de fichiers de configuration obsolètes.

* Added serial protection dialog management for message forwarding, including closing by button or escape.

* feat: Implement BanPredictor for predicting ban risks based on historical data and real-time events

feat: Add ConfigValidator to validate configuration files and catch common issues

feat: Create QueryDiversityEngine to fetch diverse search queries from multiple sources

feat: Develop RiskManager to monitor account activity and assess risk levels dynamically

* Refactor code for consistency and readability; unify string quotes, improve logging with contextual emojis, enhance configuration validation, and streamline risk management logic.

* feat: Refactor BrowserUtil and Login classes for improved button handling and selector management; implement unified selector system and enhance activity processing logic in Workers class.

* feat: Improve logging with ASCII context icons for better compatibility with Windows PowerShell

* feat: Add sample account setup

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* feat: Update Node.js engine requirement to >=20.0.0 and improve webhook avatar handling and big fix Schedule

* Update README.md

* feat: Improve logging for Google Trends search queries and adjust fallback condition

* feat: Update version to 2.2.1 and enhance dashboard data retrieval with improved error handling

* feat: Update version to 2.2.2 and add terms update dialog dismissal functionality

* feat: Update version to 2.2.2 and require Node.js engine >=20.0.0

* feat: Ajouter un fichier de configuration complet pour la gestion des tâches et des performances

* feat: Mettre à jour la version à 2.2.3, modifier le fuseau horaire par défaut et activer les rapports d'analyse

* feat: update doc

* feat: update doc

* Refactor documentation for proxy setup, security guide, and auto-update system

- Updated proxy documentation to streamline content and improve clarity.
- Revised security guide to emphasize best practices and incident response.
- Simplified auto-update documentation, enhancing user understanding of the update process.
- Removed redundant sections and improved formatting for better readability.

* feat: update version to 2.2.7 in package.json

* feat: update version to 2.2.7 in README.md

* feat: improve quiz data retrieval with alternative variables and debug logs

* feat: refactor timeout and selector constants for improved maintainability

* feat: update version to 2.2.8 in package.json and add retry limits in constants

* feat: enhance webhook logging with username, avatar, and color-coded messages

* feat: update .gitignore to include diagnostic folder and bump version to 2.2.8 in package-lock.json

* feat: updated version to 2.3.0 and added new constants to improve the handling of delays and colors in logs

* feat: refactor ConclusionWebhook to improve structure and enhance message formatting

* feat: update setup scripts and version to 2.3.3, refactor paths for improved structure

* feat: refactor setup scripts to run via npm and improve error handling for package.json

* feat: refactor webhook avatar handling to use centralized constant from constants.ts

* feat: mettre à jour la version à 2.3.7 et améliorer le script de mise à jour avec des options de contrôle d'auto-mise à jour

* feat: activer la mise à jour automatique pour la configuration et les comptes

* feat: mettre à jour la version à 2.3.7 et améliorer la gestion des erreurs dans plusieurs fichiers

* feat: améliorer la gestion des erreurs et des délais dans plusieurs fichiers, y compris Axios et ConclusionWebhook

* feat: mettre à jour la version à 2.4.0 et améliorer la documentation sur le contrôle de mise à jour automatique

* feat: increase the number of passes per execution to 3 to improve task capture

* feat: update account management with new file format and filter disabled accounts

* feat: update version to 2.4.0, add reinstallation warning and support .jsonc extensions for configuration files

* fix: fix formatting of reinstallation message in README

* feat: add an important update notice in the README to recommend a complete reinstallation

* fix: remove backup instructions from installation guide in README

* fix: update notice in README for configuration file changes and fresh installation instructions

* fix: fix typographical error in README update notice

* Fix: Update avatar URL in Discord config and remove optional webhook properties

* exploit: add customization options for webhooks and improve notification format
2025-10-23 12:56:14 +02:00
Light
abd6117db3 V2.3.0 Optimization (#380)
* Updated README.md to reflect version 2.1 and improve the presentation of Microsoft Rewards Automation features.

* Updated version to 2.1.5 in README.md and package.json, added new license and legal notice sections, and improved the configuration script for a better user experience.

* Mise à jour des messages de journalisation et ajout de vérifications pour le chargement des quiz et la présence des options avant de procéder. Suppression de fichiers de configuration obsolètes.

* Added serial protection dialog management for message forwarding, including closing by button or escape.

* feat: Implement BanPredictor for predicting ban risks based on historical data and real-time events

feat: Add ConfigValidator to validate configuration files and catch common issues

feat: Create QueryDiversityEngine to fetch diverse search queries from multiple sources

feat: Develop RiskManager to monitor account activity and assess risk levels dynamically

* Refactor code for consistency and readability; unify string quotes, improve logging with contextual emojis, enhance configuration validation, and streamline risk management logic.

* feat: Refactor BrowserUtil and Login classes for improved button handling and selector management; implement unified selector system and enhance activity processing logic in Workers class.

* feat: Improve logging with ASCII context icons for better compatibility with Windows PowerShell

* feat: Add sample account setup

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* feat: Update Node.js engine requirement to >=20.0.0 and improve webhook avatar handling and big fix Schedule

* Update README.md

* feat: Improve logging for Google Trends search queries and adjust fallback condition

* feat: Update version to 2.2.1 and enhance dashboard data retrieval with improved error handling

* feat: Update version to 2.2.2 and add terms update dialog dismissal functionality

* feat: Update version to 2.2.2 and require Node.js engine >=20.0.0

* feat: Ajouter un fichier de configuration complet pour la gestion des tâches et des performances

* feat: Mettre à jour la version à 2.2.3, modifier le fuseau horaire par défaut et activer les rapports d'analyse

* feat: update doc

* feat: update doc

* Refactor documentation for proxy setup, security guide, and auto-update system

- Updated proxy documentation to streamline content and improve clarity.
- Revised security guide to emphasize best practices and incident response.
- Simplified auto-update documentation, enhancing user understanding of the update process.
- Removed redundant sections and improved formatting for better readability.

* feat: update version to 2.2.7 in package.json

* feat: update version to 2.2.7 in README.md

* feat: improve quiz data retrieval with alternative variables and debug logs

* feat: refactor timeout and selector constants for improved maintainability

* feat: update version to 2.2.8 in package.json and add retry limits in constants

* feat: enhance webhook logging with username, avatar, and color-coded messages

* feat: update .gitignore to include diagnostic folder and bump version to 2.2.8 in package-lock.json

* feat: updated version to 2.3.0 and added new constants to improve the handling of delays and colors in logs
2025-10-16 17:59:53 +02:00
Light
4d928d7dd9 V2.1.5 (#379)
* Updated README.md to reflect version 2.1 and improve the presentation of Microsoft Rewards Automation features.

* Updated version to 2.1.5 in README.md and package.json, added new license and legal notice sections, and improved the configuration script for a better user experience.

* Mise à jour des messages de journalisation et ajout de vérifications pour le chargement des quiz et la présence des options avant de procéder. Suppression de fichiers de configuration obsolètes.

* Added serial protection dialog management for message forwarding, including closing by button or escape.

* feat: Implement BanPredictor for predicting ban risks based on historical data and real-time events

feat: Add ConfigValidator to validate configuration files and catch common issues

feat: Create QueryDiversityEngine to fetch diverse search queries from multiple sources

feat: Develop RiskManager to monitor account activity and assess risk levels dynamically

* Refactor code for consistency and readability; unify string quotes, improve logging with contextual emojis, enhance configuration validation, and streamline risk management logic.

* feat: Refactor BrowserUtil and Login classes for improved button handling and selector management; implement unified selector system and enhance activity processing logic in Workers class.

* feat: Improve logging with ASCII context icons for better compatibility with Windows PowerShell

* feat: Add sample account setup

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md
2025-10-15 16:12:15 +02:00
Light
dc7e122bce V2.1 (#375)
* feat: Implement edge version fetching with retry logic and caching

* chore: Update version to 2.1.0 in package.json

* fix: Update package version to 2.1.0 and enhance user agent metadata

* feat: Enhance 2FA handling with improved TOTP input and submission logic

* fix: Refactor getSystemComponents to improve mobile user agent string generation

* feat: Add support for cron expressions for advanced scheduling

* feat: Improve humanization feature with detailed logging for off-days configuration

* feat: Add live log streaming via webhook and enhance logging configuration

* fix: Remove unused @types/cron-parser dependency from devDependencies

* feat: Add cron-parser dependency and enhance Axios error handling for proxy authentication

* feat: Enhance dashboard data retrieval with retry logic and diagnostics capture

* feat: Add ready-to-use sample configurations and update configuration settings for better customization

* feat: Add buy mode detection and configuration methods for enhanced manual redemption

* feat: Migrate configuration from JSON to JSONC format for improved readability and comments support

feat: Implement centralized diagnostics capture for better error handling and reporting

fix: Update documentation references from config.json to config.jsonc

chore: Add .vscode to .gitignore for cleaner project structure

refactor: Enhance humanization and diagnostics capture logic in BrowserUtil and Login classes

* feat: Reintroduce ambiance declarations for the 'luxon' module to unlock TypeScript

* feat: Update search delay settings for improved performance and reliability

* feat: Update README and SECURITY documentation for clarity and improved data handling guidelines

* Enhance README and SECURITY documentation for Microsoft Rewards Script V2

- Updated README.md to improve structure, add badges, and enhance clarity on features and setup instructions.
- Expanded SECURITY.md to provide detailed data handling practices, security guidelines, and best practices for users.
- Included sections on data flow, credential management, and responsible use of the automation tool.
- Added a security checklist for users to ensure safe practices while using the script.

* feat: Réorganiser et enrichir la documentation du README pour une meilleure clarté et accessibilité

* feat: Updated and reorganized the README for better presentation and clarity

* feat: Revised and simplified the README for better clarity and accessibility

* Update README.md
2025-10-11 16:54:07 +02:00
hmcdat
3e499be8a9 fix scheduler exit suddenly (#368) 2025-10-01 18:22:36 +02:00
Michael Cammarata
554227e200 Dockerfile and image optimization (#369)
Refactor of dockerfile to reduce final image from 2.55 gb to 766 mb to support pre-build
2025-10-01 15:50:33 +02:00
Light
15f62963f8 V2 (#365)
* first commit

* Addition of a personalized activity manager and refactoring of the logic of activities

* Adding diagnostics management, including screenshot and HTML content, as well as improvements to humanize page interactions and +.

* Adding the management of newspapers and webhook settings, including filtering messages and improving the structure of the summaries sent.

* Adding a post-execution auto-date functionality, including options to update via Git and Docker, as well as a new configuration interface to manage these parameters.

* Adding accounts in Docker, with options to use an environmental file or online JSON data, as well as minimum validations for responsible accounts.

* Improving the Microsoft Rewards script display with a new headband and better log management, including colors and improved formatting for the console.

* v2

* Refactor ESLint configuration and scripts for improved TypeScript support and project structure

* Addition of the detection of suspended accounts with the gesture of the improved errors and journalization of banishment reasons

* Adding an integrated planner for programmed task execution, with configuration in Config.json and +

* Edit

* Remove texte

* Updating of documentation and adding the management of humanization in the configuration and +.

* Adding manual purchase method allowing users to spend points without automation, with monitoring of expenses and notifications.

* Correction of documentation and improvement of configuration management for manual purchase mode, adding complete documentation and appropriate banner display.

* Add comprehensive documentation for job state persistence, NTFY notifications, proxy configuration, scheduling, and auto-update features

- Introduced job state persistence documentation to track progress and resume tasks.
- Added NTFY push notifications integration guide for real-time alerts.
- Documented proxy configuration options for enhanced privacy and network management.
- Included scheduling configuration for automated script execution.
- Implemented auto-update configuration to keep installations current with Git and Docker options.

* Ajout d'Unt Système de Rapport d'Erreurs Communautaire pour Améliorerer le Débogage, incluant la Configuration et l'Envoi de Résumés D'Erreurs Anonyés à un webhook Discord.

* Mini Edit

* Mise à Jour du Readme.md pour Améliorerer la Présentation et La Claté, Ajout d'Un section sur les notifications en Temps Raine et Mise à Jour des badges pour la meille unibilité.

* Documentation update

* Edit README.md

* Edit

* Update README with legacy version link

* Improvement of location data management and webhooks, adding configurations normalization

* Force update for PR

* Improvement of documentation and configuration options for Cron integration and Docker use

* Improvement of planning documentation and adding a multi-pan-pancake in the daily execution script

* Deletion of the CommunityReport functionality in accordance with the project policy

* Addition of randomization of start -up schedules and surveillance time for planner executions

* Refactor Docker setup to use built-in scheduler, removing cron dependencies and simplifying configuration options

* Adding TOTP support for authentication, update of interfaces and configuration files to include Totp secret, and automatic generation of the Totp code when connecting.

* Fix [LOGIN-NO-PROMPT] No dialogs (xX)

* Reset the Totp field for email_1 in the accounts.example.json file

* Reset the Totp field for email_1 in the Readme.md file

* Improvement of Bing Research: Use of the 'Attacked' method for the research field, management of overlays and adding direct navigation in the event of entry failure.

* Adding a complete security policy, including directives on vulnerability management, coordinated disclosure and user security advice.

* Remove advanced environment variables section from README

* Configuration and dockerfile update: Passage to Node 22, addition of management of the purchase method, deletion of obsolete scripts

* Correction of the order of the sections in the Readme.md for better readability

* Update of Readm and Security Policy: Addition of the method of purchase and clarification of security and confidentiality practices.

* Improvement of the readability of the Readm and deletion of the mention of reporting of vulnerabilities in the security document.

* Addition of humanization management and adaptive throttling to simulate more human behavior in bot activities.

* Addition of humanization management: activation/deactivation of human gestures, configuration update and adding documentation on human mode.

* Deletion of community error report functionality to respect the privacy policy

* Addition of immediate banning alerts and vacation configuration in the Microsoft Rewards bot

* Addition of immediate banning alerts and vacation configuration in the Microsoft Rewards bot

* Added scheduling support: support for 12h and 24h formats, added options for time zone, and immediate execution on startup.

* Added window size normalization and page rendering to fit typical screens, with injected CSS styles to prevent excessive zooming.

* Added security incident management: detection of hidden recovery emails, automation blocking, and global alerts. Updated configuration files and interfaces to include recovery emails. Improved security incident documentation.

* Refactor incident alert handling: unified alert sender

* s

* Added security incident management: detect recovery email inconsistencies and send unified alerts. Implemented helper methods to manage alerts and compromised modes.

* Added heartbeat management for the scheduler: integrated a heartbeat file to report liveliness and adjusted the watchdog configuration to account for heartbeat updates.

* Edit webook

* Updated security alert management: fixed the recovery email hidden in the documentation and enabled the conclusion webhook for notifications.

* Improved security alert handling: added structured sending to webhooks for better visibility and updated callback interval in compromised mode.

* Edit conf

* Improved dependency installation: Added the --ignore-scripts option for npm ci and npm install. Updated comments in compose.yaml for clarity.

* Refactor documentation structure and enhance logging:
- Moved documentation files from 'information' to 'docs' directory for better organization.
- Added live logging configuration to support webhook logs with email redaction.
- Updated file paths in configuration and loading functions to accommodate new structure.
- Adjusted scheduler behavior to prevent immediate runs unless explicitly set.
- Improved error handling for account and config file loading.
- Enhanced security incident documentation with detailed recovery steps.

* Fix docs

* Remove outdated documentation on NTFY, Proxy, Scheduling, Security, and Auto-Update configurations; update Browser class to prioritize headless mode based on environment variable.

* Addition of documentation for account management and Totp, Docker Guide, and Update of the Documentation Index.

* Updating Docker documentation: simplification of instructions and adding links to detailed guides. Revision of configuration options and troubleshooting sections.

* Edit

* Edit docs

* Enhance documentation for Scheduler, Security, and Auto-Update features

- Revamped the Scheduler documentation to include detailed features, configuration options, and usage examples.
- Expanded the Security guide with comprehensive incident response strategies, privacy measures, and monitoring practices.
- Updated the Auto-Update section to clarify configuration, methods, and best practices for maintaining system integrity.

* Improved error handling and added crash recovery in the Microsoft Rewards bot. Added configuration for automatic restart and handling of local search queries when trends fail.

* Fixed initial point counting in MicrosoftRewardsBot and improved error handling when sending summaries to webhooks.

* Added unified support for notifications and improved handling of webhook configurations in the normalizeConfig and log functions.

* UPDATE LOGIN

* EDIT LOGIN

* Improved login error handling: added recovery mismatch detection and the ability to switch to password authentication.

* Added a full reference to configuration in the documentation and improved log and error handling in the code.

* Added context management for conclusion webhooks and improved user configuration for notifications.

* Mini edit

* Improved logic for extracting masked emails for more accurate matching during account recovery.
2025-09-26 18:58:33 +02:00
89 changed files with 11156 additions and 10369 deletions

View File

@@ -1,2 +0,0 @@
dist
node_modules

3
.eslintignore Normal file
View File

@@ -0,0 +1,3 @@
dist/
node_modules/
setup/

View File

@@ -1,28 +1,37 @@
module.exports = {
env: {
es2021: true,
node: true
'env': {
'es2021': true,
'node': true
},
extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 12,
sourceType: 'module'
'extends': [
'eslint:recommended',
'plugin:@typescript-eslint/recommended'
],
'parser': '@typescript-eslint/parser',
'parserOptions': {
'ecmaVersion': 12,
'sourceType': 'module'
},
plugins: ['@typescript-eslint'],
rules: {
'linebreak-style': ['error', 'unix'],
quotes: ['error', 'single'],
semi: ['error', 'never'],
'@typescript-eslint/no-explicit-any': [
'warn',
{
fixToUnknown: false
}
'plugins': [
'@typescript-eslint'
],
'rules': {
'linebreak-style': 'off',
'quotes': [
'error',
'single'
],
'semi': [
'error',
'never'
],
'@typescript-eslint/no-explicit-any':
['warn', {
fixToUnknown: true // This line is optional and only relevant if you are using TypeScript
}],
'comma-dangle': 'off',
'@typescript-eslint/comma-dangle': 'error',
'prefer-arrow-callback': 'error',
'no-empty': 'off'
'prefer-arrow-callback': 'error'
// Add any other rules you want to enforce here
}
}
}

28
.eslintrc.json Normal file
View File

@@ -0,0 +1,28 @@
{
"root": true,
"env": {
"es2021": true,
"node": true
},
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": ["./tsconfig.json"],
"sourceType": "module",
"ecmaVersion": 2021
},
"plugins": ["@typescript-eslint", "modules-newline"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"rules": {
"modules-newline/import-declaration-newline": ["warn", { "count": 3 }],
"@typescript-eslint/consistent-type-imports": ["warn", { "prefer": "type-imports" }],
"@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_", "varsIgnorePattern": "^_" }],
"@typescript-eslint/no-explicit-any": "off",
"no-console": ["warn", { "allow": ["error", "warn"] }],
"quotes": ["error", "double", { "avoidEscape": true }],
"linebreak-style": "off"
},
"ignorePatterns": ["dist/**", "node_modules/**", "setup/**"]
}

View File

@@ -1,51 +0,0 @@
name: Build and Push Docker Image on Release
on:
release:
types: [published]
workflow_dispatch:
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=raw,value=latest,enable={{is_default_branch}}
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max

13
.gitignore vendored
View File

@@ -1,13 +1,12 @@
sessions/
dist/
.dev/
node_modules/
src/accounts.json
src/config.json
/.vscode
/diagnostics
note
.vscode/
.github/
diagnostic/
report/
accounts.json
notes
accounts.dev.json
accounts.main.json
.DS_Store
.playwright-chromium-installed

View File

@@ -1,11 +0,0 @@
{
"semi": false,
"singleQuote": true,
"trailingComma": "none",
"tabWidth": 4,
"useTabs": false,
"printWidth": 120,
"bracketSpacing": true,
"arrowParens": "avoid",
"endOfLine": "lf"
}

View File

@@ -23,7 +23,7 @@ RUN rm -rf node_modules \
&& npm cache clean --force
# Install Chromium Headless Shell, and cleanup
RUN npx patchright install --with-deps --only-shell chromium \
RUN npx playwright install --with-deps --only-shell chromium \
&& rm -rf /root/.cache /tmp/* /var/tmp/*
###############################################################################
@@ -79,10 +79,12 @@ COPY --from=builder /usr/src/microsoft-rewards-script/dist ./dist
COPY --from=builder /usr/src/microsoft-rewards-script/package*.json ./
COPY --from=builder /usr/src/microsoft-rewards-script/node_modules ./node_modules
# Copy runtime scripts with proper permissions from the start
COPY --chmod=755 scripts/docker/run_daily.sh ./scripts/docker/run_daily.sh
# Copy runtime scripts with proper permissions and normalize line endings for non-Unix users
COPY --chmod=755 src/run_daily.sh ./src/run_daily.sh
COPY --chmod=644 src/crontab.template /etc/cron.d/microsoft-rewards-cron.template
COPY --chmod=755 scripts/docker/entrypoint.sh /usr/local/bin/entrypoint.sh
COPY --chmod=755 entrypoint.sh /usr/local/bin/entrypoint.sh
RUN sed -i 's/\r$//' /usr/local/bin/entrypoint.sh \
&& sed -i 's/\r$//' ./src/run_daily.sh
# Entrypoint handles TZ, initial run toggle, cron templating & launch
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]

343
README.md
View File

@@ -2,9 +2,348 @@
---
TODO
## Table of Contents
- [Setup](#setup)
- [1. Clone the Repository](#1-clone-the-repository)
- [2. Copy Configuration Files](#2-copy-configuration-files)
- [3. Install Dependencies and Prepare the Browser](#3-install-dependencies-and-prepare-the-browser)
- [4. Build and Run](#4-build-and-run)
- [Nix Users](#nix-setup)
- [Docker Setup](#docker-setup)
- [Before Starting](#before-starting)
- [Quick Start](#quick-start)
- [Example compose.yaml](#example-composeyaml)
- [Configuration Reference](#configuration-reference)
- [Account Configuration](#account-configuration)
- [Features Overview](#features-overview)
- [Disclaimer](#disclaimer)
[For installation see the main (v1) or v2 branch (mostly the same)](https://github.com/TheNetsky/Microsoft-Rewards-Script/tree/main?tab=readme-ov-file#setup)
---
## Setup
**Requirements:** Node.js ≥ 20 and Git
Works on Windows, Linux, macOS, and WSL.
---
### 1. Clone the Repository
**All systems:**
```bash
git clone https://github.com/TheNetsky/Microsoft-Rewards-Script.git
cd Microsoft-Rewards-Script
```
Or download the latest release ZIP and extract it.
---
### 2. Copy Configuration Files
**Windows:**
Rename manually:
```
src/accounts.example.json → src/accounts.json
```
**Linux / macOS / WSL:**
```bash
cp src/accounts.example.json src/accounts.json
```
Then edit:
- `src/accounts.json` — fill in your Microsoft account credentials.
- `src/config.json` — review or customize options.
---
### 3. Install Dependencies and Prepare the Browser
**All systems:**
```bash
npm run pre-build
```
This command:
- Installs all dependencies
- Clears old builds (`dist/`)
- Installs Playwright Chromium (required browser)
---
### 4. Build and Run
**All systems:**
```bash
npm run build
npm run start
```
---
## Nix Setup
If using Nix:
1. Run the pre-build step first:
```bash
npm run pre-build
```
2. Then start the script:
```bash
./run.sh
```
This will launch the script headlessly using `xvfb-run`.
## Docker Setup
### Before Starting
- Remove local `/node_modules` and `/dist` if previously built.
- Remove old Docker volumes if upgrading from older versions.
- You can reuse your existing `accounts.json`.
---
### Quick Start
1. Clone the repository and configure your `accounts.json`.
2. Ensure `config.json` has `"headless": true`.
3. Edit `compose.yaml`:
- Set your timezone (`TZ`)
- Set the cron schedule (`CRON_SCHEDULE`)
- Optionally enable `RUN_ON_START=true`
4. Start the container:
```bash
docker compose up -d
```
5. Monitor logs:
```bash
docker logs microsoft-rewards-script
```
The container includes a randomized delay (about 550 minutes by default)
before each scheduled run to appear more natural. This can be configured or disabled via environment variables.
---
### Example compose.yaml
```yaml
services:
microsoft-rewards-script:
image: ghcr.io/your-org/microsoft-rewards-script:latest
container_name: microsoft-rewards-script
restart: unless-stopped
volumes:
- ./src/accounts.json:/usr/src/microsoft-rewards-script/dist/accounts.json:ro
- ./src/config.json:/usr/src/microsoft-rewards-script/dist/config.json:ro
- ./sessions:/usr/src/microsoft-rewards-script/dist/sessions
# - ./jobstate:/usr/src/microsoft-rewards-script/dist/jobstate
environment:
TZ: "Europe/Amsterdam"
NODE_ENV: "production"
CRON_SCHEDULE: "0 7,16,20 * * *"
RUN_ON_START: "true"
# MIN_SLEEP_MINUTES: "5"
# MAX_SLEEP_MINUTES: "50"
# SKIP_RANDOM: "true"
deploy:
resources:
limits:
cpus: "1.0"
memory: "1g"
```
#### compose.yaml Notes
- **volumes**
- `accounts.json` and `config.json` are mounted read-only to prevent accidental edits.
- `sessions` persists login sessions and fingerprints across runs.
- If `jobState.enabled` is used, mount its directory as a volume.
- **CRON_SCHEDULE**
- Uses standard crontab syntax (e.g., via [crontab.guru](https://crontab.guru/)).
- Schedule is evaluated inside the container using the configured `TZ`.
- **RUN_ON_START**
- Runs the script once immediately on startup, then continues on schedule.
- **Randomization**
- Default delay: 550 minutes.
- Adjustable via `MIN_SLEEP_MINUTES` and `MAX_SLEEP_MINUTES`, or disable with `SKIP_RANDOM`.
---
## Configuration Reference
Edit `src/config.json` to customize behavior.
Below is a summary of key configuration sections.
### Core
| Setting | Description | Default |
|----------|-------------|----------|
| `baseURL` | Microsoft Rewards base URL | `https://rewards.bing.com` |
| `sessionPath` | Folder to store browser sessions | `sessions` |
| `dryRun` | Simulate execution without running tasks | `false` |
### Browser
| Setting | Description | Default |
|----------|-------------|----------|
| `browser.headless` | Run browser invisibly | `false` |
| `browser.globalTimeout` | Timeout for actions | `"30s"` |
### Fingerprinting
| Setting | Description | Default |
|----------|-------------|----------|
| `fingerprinting.saveFingerprint.mobile` | Reuse mobile fingerprint | `true` |
| `fingerprinting.saveFingerprint.desktop` | Reuse desktop fingerprint | `true` |
### Execution
| Setting | Description | Default |
|----------|-------------|----------|
| `execution.parallel` | Run desktop and mobile simultaneously | `false` |
| `execution.runOnZeroPoints` | Run even with zero points | `false` |
| `execution.clusters` | Number of concurrent account clusters | `1` |
### Job State
| Setting | Description | Default |
|----------|-------------|----------|
| `jobState.enabled` | Save last job state | `true` |
| `jobState.dir` | Directory for job data | `""` |
### Workers (Tasks)
| Setting | Description | Default |
|----------|-------------|----------|
| `doDailySet` | Complete daily set | `true` |
| `doMorePromotions` | Complete more promotions | `true` |
| `doPunchCards` | Complete punchcards | `true` |
| `doDesktopSearch` | Perform desktop searches | `true` |
| `doMobileSearch` | Perform mobile searches | `true` |
| `doDailyCheckIn` | Complete daily check-in | `true` |
| `doReadToEarn` | Complete Read-to-Earn | `true` |
| `bundleDailySetWithSearch` | Combine daily set and searches | `true` |
### Search
| Setting | Description | Default |
|----------|-------------|----------|
| `search.useLocalQueries` | Use local query list | `true` |
| `search.settings.useGeoLocaleQueries` | Use region-based queries | `true` |
| `search.settings.scrollRandomResults` | Random scrolling | `true` |
| `search.settings.clickRandomResults` | Random link clicking | `true` |
| `search.settings.retryMobileSearchAmount` | Retry mobile searches | `2` |
| `search.settings.delay.min` | Minimum delay between searches | `1min` |
| `search.settings.delay.max` | Maximum delay between searches | `5min` |
### Query Diversity
| Setting | Description | Default |
|----------|-------------|----------|
| `queryDiversity.enabled` | Enable multiple query sources | `true` |
| `queryDiversity.sources` | Query providers | `["google-trends", "reddit", "local-fallback"]` |
| `queryDiversity.maxQueriesPerSource` | Limit per source | `10` |
| `queryDiversity.cacheMinutes` | Cache lifetime | `30` |
### Humanization
| Setting | Description | Default |
|----------|-------------|----------|
| `humanization.enabled` | Enable human behavior | `true` |
| `stopOnBan` | Stop immediately on ban | `true` |
| `immediateBanAlert` | Alert instantly if banned | `true` |
| `actionDelay.min` | Minimum delay per action (ms) | `500` |
| `actionDelay.max` | Maximum delay per action (ms) | `2200` |
| `gestureMoveProb` | Chance of random mouse movement | `0.65` |
| `gestureScrollProb` | Chance of random scrolls | `0.4` |
### Vacation Mode
| Setting | Description | Default |
|----------|-------------|----------|
| `vacation.enabled` | Enable random pauses | `true` |
| `minDays` | Minimum days off | `2` |
| `maxDays` | Maximum days off | `4` |
### Risk Management
| Setting | Description | Default |
|----------|-------------|----------|
| `enabled` | Enable risk-based adjustments | `true` |
| `autoAdjustDelays` | Adapt delays dynamically | `true` |
| `stopOnCritical` | Stop on critical warning | `false` |
| `banPrediction` | Predict bans based on signals | `true` |
| `riskThreshold` | Risk tolerance level | `75` |
### Retry Policy
| Setting | Description | Default |
|----------|-------------|----------|
| `maxAttempts` | Maximum retry attempts | `3` |
| `baseDelay` | Initial retry delay | `1000` |
| `maxDelay` | Maximum retry delay | `30s` |
| `multiplier` | Backoff multiplier | `2` |
| `jitter` | Random jitter factor | `0.2` |
### Proxy
| Setting | Description | Default |
|----------|-------------|----------|
| `proxy.proxyGoogleTrends` | Proxy Google Trends requests | `true` |
| `proxy.proxyBingTerms` | Proxy Bing terms requests | `true` |
### Notifications
| Setting | Description | Default |
|----------|-------------|----------|
| `notifications.webhook.enabled` | Enable Discord webhook | `false` |
| `notifications.webhook.url` | Discord webhook URL | `""` |
| `notifications.conclusionWebhook.enabled` | Enable summary webhook | `false` |
| `notifications.conclusionWebhook.url` | Summary webhook URL | `""` |
| `notifications.ntfy.enabled` | Enable Ntfy push alerts | `false` |
| `notifications.ntfy.url` | Ntfy server URL | `""` |
| `notifications.ntfy.topic` | Ntfy topic name | `"rewards"` |
### Logging
| Setting | Description | Default |
|----------|-------------|----------|
| `excludeFunc` | Exclude from console logs | `["SEARCH-CLOSE-TABS", "LOGIN-NO-PROMPT", "FLOW"]` |
| `webhookExcludeFunc` | Exclude from webhook logs | `["SEARCH-CLOSE-TABS", "LOGIN-NO-PROMPT", "FLOW"]` |
| `redactEmails` | Hide emails in logs | `true` |
---
## Account Configuration
Edit `src/accounts.json`:
```json
{
"accounts": [
{
"enabled": true,
"email": "email_1@outlook.com",
"password": "password_1",
"totp": "",
"recoveryEmail": "your_email@domain.com",
"proxy": {
"proxyAxios": true,
"url": "",
"port": 0,
"username": "",
"password": ""
}
}
]
}
```
---
## Features Overview
- Multi-account and session handling
- Persistent browser fingerprints
- Parallel task execution
- Proxy and retry support
- Human-like behavior simulation
- Full daily set automation
- Mobile and desktop search support
- Vacation and risk protection
- Webhook and Ntfy notifications
- Docker scheduling support
---
## Disclaimer

View File

@@ -1,42 +1,42 @@
services:
microsoft-rewards-script:
build: .
container_name: microsoft-rewards-script
restart: unless-stopped
microsoft-rewards-script:
build: .
container_name: microsoft-rewards-script
restart: unless-stopped
# Volume mounts: Specify a location where you want to save the files on your local machine.
volumes:
- ./src/accounts.json:/usr/src/microsoft-rewards-script/dist/accounts.json:ro
- ./src/config.json:/usr/src/microsoft-rewards-script/dist/config.json:ro
- ./sessions:/usr/src/microsoft-rewards-script/dist/browser/sessions # Optional, saves your login session
# Volume mounts: Specify a location where you want to save the files on your local machine.
volumes:
- ./src/accounts.json:/usr/src/microsoft-rewards-script/dist/accounts.json:ro
- ./src/config.json:/usr/src/microsoft-rewards-script/dist/config.json:ro
- ./sessions:/usr/src/microsoft-rewards-script/dist/browser/sessions # Optional, saves your login session
environment:
TZ: 'America/Toronto' # Set your timezone for proper scheduling
NODE_ENV: 'production'
CRON_SCHEDULE: '0 7 * * *' # Customize your schedule, use crontab.guru for formatting
RUN_ON_START: 'true' # Runs the script immediately on container startup
environment:
TZ: "America/Toronto" # Set your timezone for proper scheduling
NODE_ENV: "production"
CRON_SCHEDULE: "0 7,16,20 * * *" # Customize your schedule, use crontab.guru for formatting
RUN_ON_START: "true" # Runs the script immediately on container startup
# Add scheduled start-time randomization (uncomment to customize or disable, default: enabled)
#MIN_SLEEP_MINUTES: "5"
#MAX_SLEEP_MINUTES: "50"
SKIP_RANDOM_SLEEP: 'false'
# Add scheduled start-time randomization (uncomment to customize or disable, default: enabled)
#MIN_SLEEP_MINUTES: "5"
#MAX_SLEEP_MINUTES: "50"
SKIP_RANDOM_SLEEP: "false"
# Optionally set how long to wait before killing a stuck script run (prevents blocking future runs, default: 8 hours)
#STUCK_PROCESS_TIMEOUT_HOURS: "8"
# Optionally set how long to wait before killing a stuck script run (prevents blocking future runs, default: 8 hours)
#STUCK_PROCESS_TIMEOUT_HOURS: "8"
# Optional resource limits for the container
mem_limit: 4g
cpus: 2
# Optional resource limits for the container
mem_limit: 4g
cpus: 2
# Health check - monitors if cron daemon is running to ensure scheduled jobs can execute
# Container marked unhealthy if cron process dies
healthcheck:
test: ['CMD', 'sh', '-c', 'pgrep cron > /dev/null || exit 1']
interval: 60s
timeout: 10s
retries: 3
start_period: 30s
# Security hardening
security_opt:
- no-new-privileges:true
# Health check - monitors if cron daemon is running to ensure scheduled jobs can execute
# Container marked unhealthy if cron process dies
healthcheck:
test: ["CMD", "sh", "-c", "pgrep cron > /dev/null || exit 1"]
interval: 60s
timeout: 10s
retries: 3
start_period: 30s
# Security hardening
security_opt:
- no-new-privileges:true

2
scripts/docker/entrypoint.sh → entrypoint.sh Normal file → Executable file
View File

@@ -26,7 +26,7 @@ if [ "${RUN_ON_START:-false}" = "true" ]; then
exit 1
}
# Skip random sleep for initial run, but preserve setting for cron jobs
SKIP_RANDOM_SLEEP=true scripts/docker/run_daily.sh
SKIP_RANDOM_SLEEP=true src/run_daily.sh
echo "[entrypoint-bg] Initial run completed at $(date)"
) &
echo "[entrypoint] Background process started (PID: $!)"

6140
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,59 +1,67 @@
{
"name": "microsoft-rewards-script",
"version": "3.0.1",
"description": "Automatically do tasks for Microsoft Rewards but in TS!",
"author": "Netsky",
"license": "GPL-3.0-or-later",
"main": "dist/index.js",
"engines": {
"node": ">=18.0.0"
},
"scripts": {
"pre-build": "npm i && rimraf dist && npx patchright install chromium",
"build": "rimraf dist && tsc",
"start": "node ./dist/index.js",
"ts-start": "ts-node ./src/index.ts",
"dev": "ts-node ./src/index.ts -dev",
"kill-chrome-win": "powershell -Command \"Get-Process | Where-Object { $_.MainModule.FileVersionInfo.FileDescription -eq 'Google Chrome for Testing' } | ForEach-Object { Stop-Process -Id $_.Id -Force }\"",
"create-docker": "docker build -t microsoft-rewards-script-docker .",
"format": "prettier --write .",
"format:check": "prettier --check .",
"clear-sessions": "node ./scripts/clearSessions.js",
"clear-diagnostics": "rimraf diagnostics"
},
"keywords": [
"Bing Rewards",
"Microsoft Rewards",
"Bot",
"Script",
"TypeScript",
"Playwright",
"Cheerio"
],
"devDependencies": {
"@types/ms": "^2.1.0",
"@types/node": "^24.10.1",
"@typescript-eslint/eslint-plugin": "^8.48.0",
"eslint": "^9.39.1",
"eslint-plugin-modules-newline": "^0.0.6",
"prettier": "^3.7.1",
"rimraf": "^6.1.2",
"typescript": "^5.9.3"
},
"dependencies": {
"axios": "^1.13.2",
"axios-retry": "^4.5.0",
"chalk": "^4.1.2",
"cheerio": "^1.0.0",
"fingerprint-generator": "^2.1.77",
"fingerprint-injector": "^2.1.77",
"ghost-cursor-playwright-port": "^1.4.3",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.6",
"ms": "^2.1.3",
"otpauth": "^9.4.1",
"p-queue": "^9.0.1",
"patchright": "^1.57.0",
"ts-node": "^10.9.2"
}
}
"name": "microsoft-rewards-script",
"version": "2.4.1",
"description": "Automatically do tasks for Microsoft Rewards but in TS!",
"private": true,
"main": "index.js",
"engines": {
"node": ">=20.0.0"
},
"repository": {
"type": "git",
"url": "https://github.com/TheNetsky/Microsoft-Rewards-Script.git"
},
"bugs": {
"url": "https://github.com/TheNetsky/Microsoft-Rewards-Script/issues"
},
"homepage": "https://github.com/TheNetsky/Microsoft-Rewards-Script#readme",
"scripts": {
"clean": "rimraf dist",
"pre-build": "npm i && npm run clean && node -e \"process.exit(process.env.SKIP_PLAYWRIGHT_INSTALL?0:1)\" || npx playwright install chromium",
"typecheck": "tsc --noEmit",
"build": "tsc",
"start": "node --enable-source-maps ./dist/index.js",
"ts-start": "node --loader ts-node/esm ./src/index.ts",
"dev": "ts-node ./src/index.ts -dev",
"lint": "eslint \"src/**/*.{ts,tsx}\"",
"prepare": "npm run build",
"kill-chrome-win": "powershell -Command \"Get-Process | Where-Object { $_.MainModule.FileVersionInfo.FileDescription -eq 'Google Chrome for Testing' } | ForEach-Object { Stop-Process -Id $_.Id -Force }\"",
"create-docker": "docker build -t microsoft-rewards-script-docker ."
},
"keywords": [
"Bing Rewards",
"Microsoft Rewards",
"Bot",
"Script",
"TypeScript",
"Playwright",
"Cheerio"
],
"author": "Netsky",
"license": "ISC",
"devDependencies": {
"@types/ms": "^0.7.34",
"@types/node": "^20.14.11",
"@typescript-eslint/eslint-plugin": "^7.17.0",
"eslint": "^8.57.0",
"eslint-plugin-modules-newline": "^0.0.6",
"rimraf": "^6.0.1",
"typescript": "^5.5.4"
},
"dependencies": {
"axios": "^1.13.2",
"chalk": "^4.1.2",
"cheerio": "^1.0.0",
"cron-parser": "^5.4.0",
"fingerprint-generator": "^2.1.76",
"fingerprint-injector": "^2.1.76",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.6",
"luxon": "^3.5.0",
"ms": "^2.1.3",
"playwright": "1.52.0",
"rebrowser-playwright": "1.52.0",
"socks-proxy-agent": "^8.0.5",
"ts-node": "^10.9.2"
}
}

View File

@@ -1,104 +0,0 @@
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const projectRoot = path.resolve(__dirname, '..')
const possibleConfigPaths = [
path.join(projectRoot, 'config.json'),
path.join(projectRoot, 'src', 'config.json'),
path.join(projectRoot, 'dist', 'config.json')
]
console.log('[DEBUG] Project root:', projectRoot)
console.log('[DEBUG] Searching for config.json...')
let configPath = null
for (const p of possibleConfigPaths) {
console.log('[DEBUG] Checking:', p)
if (fs.existsSync(p)) {
configPath = p
console.log('[DEBUG] Found config at:', p)
break
}
}
if (!configPath) {
console.error('[ERROR] config.json not found in any expected location!')
console.error('[ERROR] Searched:', possibleConfigPaths)
process.exit(1)
}
console.log('[INFO] Using config:', configPath)
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'))
if (!config.sessionPath) {
console.error("[ERROR] config.json missing 'sessionPath' key!")
process.exit(1)
}
console.log('[INFO] Session path from config:', config.sessionPath)
const configDir = path.dirname(configPath)
const possibleSessionDirs = [
path.resolve(configDir, config.sessionPath),
path.join(projectRoot, 'src/browser', config.sessionPath),
path.join(projectRoot, 'dist/browser', config.sessionPath)
]
console.log('[DEBUG] Searching for session directory...')
let sessionDir = null
for (const p of possibleSessionDirs) {
console.log('[DEBUG] Checking:', p)
if (fs.existsSync(p)) {
sessionDir = p
console.log('[DEBUG] Found session directory at:', p)
break
}
}
if (!sessionDir) {
sessionDir = path.resolve(configDir, config.sessionPath)
console.log('[DEBUG] Using fallback session directory:', sessionDir)
}
const normalizedSessionDir = path.normalize(sessionDir)
const normalizedProjectRoot = path.normalize(projectRoot)
if (!normalizedSessionDir.startsWith(normalizedProjectRoot)) {
console.error('[ERROR] Session directory is outside project root!')
console.error('[ERROR] Project root:', normalizedProjectRoot)
console.error('[ERROR] Session directory:', normalizedSessionDir)
process.exit(1)
}
if (normalizedSessionDir === normalizedProjectRoot) {
console.error('[ERROR] Session directory cannot be the project root!')
process.exit(1)
}
const pathSegments = normalizedSessionDir.split(path.sep)
if (pathSegments.length < 3) {
console.error('[ERROR] Session path is too shallow (safety check failed)!')
console.error('[ERROR] Path:', normalizedSessionDir)
process.exit(1)
}
if (fs.existsSync(sessionDir)) {
console.log('[INFO] Removing session folder:', sessionDir)
try {
fs.rmSync(sessionDir, { recursive: true, force: true })
console.log('[SUCCESS] Session folder removed successfully')
} catch (error) {
console.error('[ERROR] Failed to remove session folder:', error.message)
process.exit(1)
}
} else {
console.log('[INFO] Session folder does not exist:', sessionDir)
}
console.log('[INFO] Done.')

View File

@@ -1,28 +1,32 @@
[
{
"accounts": [
{
"email": "email_1",
"password": "password_1",
"totp": "",
"geoLocale": "auto",
"proxy": {
"proxyAxios": true,
"url": "",
"port": 0,
"username": "",
"password": ""
}
"enabled": true,
"email": "email_1@outlook.com",
"password": "password_1",
"totp": "",
"recoveryEmail": "your_email@domain.com",
"proxy": {
"proxyAxios": true,
"url": "",
"port": 0,
"username": "",
"password": ""
}
},
{
"email": "email_2",
"password": "password_2",
"totp": "",
"geoLocale": "auto",
"proxy": {
"proxyAxios": true,
"url": "",
"port": 0,
"username": "",
"password": ""
}
"enabled": false,
"email": "email_2@outlook.com",
"password": "password_2",
"totp": "",
"recoveryEmail": "your_email@domain.com",
"proxy": {
"proxyAxios": true,
"url": "",
"port": 0,
"username": "",
"password": ""
}
}
]
]
}

View File

@@ -1,13 +1,13 @@
import rebrowser, { BrowserContext } from 'patchright'
import playwright, { BrowserContext } from 'rebrowser-playwright'
import { newInjectedContext } from 'fingerprint-injector'
import { BrowserFingerprintWithHeaders, FingerprintGenerator } from 'fingerprint-generator'
import { FingerprintGenerator } from 'fingerprint-generator'
import type { MicrosoftRewardsBot } from '../index'
import { MicrosoftRewardsBot } from '../index'
import { loadSessionData, saveFingerprintData } from '../util/Load'
import { UserAgentManager } from './UserAgent'
import { updateFingerprintUserAgent } from '../util/UserAgent'
import type { AccountProxy } from '../interface/Account'
import { AccountProxy } from '../interface/Account'
/* Test Stuff
https://abrahamjuliot.github.io/creepjs/
@@ -24,100 +24,117 @@ class Browser {
this.bot = bot
}
async createBrowser(
proxy: AccountProxy,
email: string
): Promise<{
context: BrowserContext
fingerprint: BrowserFingerprintWithHeaders
}> {
let browser: rebrowser.Browser
async createBrowser(proxy: AccountProxy, email: string): Promise<BrowserContext> {
let browser: playwright.Browser
try {
browser = await rebrowser.chromium.launch({
headless: this.bot.config.headless,
...(proxy.url && {
proxy: { username: proxy.username, password: proxy.password, server: `${proxy.url}:${proxy.port}` }
}),
// FORCE_HEADLESS env takes precedence (used in Docker with headless shell only)
const envForceHeadless = process.env.FORCE_HEADLESS === '1'
// Support legacy config.headless OR nested config.browser.headless
const legacyHeadless = (this.bot.config as { headless?: boolean }).headless
const nestedHeadless = (this.bot.config.browser as { headless?: boolean } | undefined)?.headless
const headlessValue = envForceHeadless ? true : (legacyHeadless ?? nestedHeadless ?? false)
const headless: boolean = Boolean(headlessValue)
const engineName = 'chromium' // current hard-coded engine
this.bot.log(this.bot.isMobile, 'BROWSER', `Launching ${engineName} (headless=${headless})`) // explicit engine log
browser = await playwright.chromium.launch({
// Optional: uncomment to use Edge instead of Chromium
// channel: 'msedge',
headless,
...(proxy.url && { proxy: { username: proxy.username, password: proxy.password, server: `${proxy.url}:${proxy.port}` } }),
args: [
'--no-sandbox',
'--mute-audio',
'--disable-setuid-sandbox',
'--ignore-certificate-errors',
'--ignore-certificate-errors-spki-list',
'--ignore-ssl-errors',
'--no-first-run',
'--no-default-browser-check',
'--disable-user-media-security=true',
'--disable-blink-features=Attestation',
'--disable-features=WebAuthentication,PasswordManagerOnboarding,PasswordManager,EnablePasswordsAccountStorage,Passkeys',
'--disable-save-password-bubble'
'--ignore-ssl-errors'
]
})
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'BROWSER',
`Launch failed: ${error instanceof Error ? error.message : String(error)}`
)
throw error
} catch (e: unknown) {
const msg = (e instanceof Error ? e.message : String(e))
// Common missing browser executable guidance
if (/Executable doesn't exist/i.test(msg)) {
this.bot.log(this.bot.isMobile, 'BROWSER', 'Chromium not installed for Playwright. Run "npm run pre-build" to install all dependencies', 'error')
} else {
this.bot.log(this.bot.isMobile, 'BROWSER', 'Failed to launch browser: ' + msg, 'error')
}
throw e
}
const sessionData = await loadSessionData(
this.bot.config.sessionPath,
email,
this.bot.config.saveFingerprint,
this.bot.isMobile
)
// Resolve saveFingerprint from legacy root or new fingerprinting.saveFingerprint
const legacyFp = (this.bot.config as { saveFingerprint?: { mobile: boolean; desktop: boolean } }).saveFingerprint
const nestedFp = (this.bot.config.fingerprinting as { saveFingerprint?: { mobile: boolean; desktop: boolean } } | undefined)?.saveFingerprint
const saveFingerprint = legacyFp || nestedFp || { mobile: false, desktop: false }
const fingerprint = sessionData.fingerprint
? sessionData.fingerprint
: await this.generateFingerprint(this.bot.isMobile)
const sessionData = await loadSessionData(this.bot.config.sessionPath, email, this.bot.isMobile, saveFingerprint)
const context = await newInjectedContext(browser as any, { fingerprint: fingerprint })
const fingerprint = sessionData.fingerprint ? sessionData.fingerprint : await this.generateFingerprint()
await context.addInitScript(() => {
Object.defineProperty(navigator, 'credentials', {
value: {
create: () => Promise.reject(new Error('WebAuthn disabled')),
get: () => Promise.reject(new Error('WebAuthn disabled'))
}
const context = await newInjectedContext(browser as unknown as import('playwright').Browser, { fingerprint: fingerprint })
// Set timeout to preferred amount (supports legacy globalTimeout or browser.globalTimeout)
const legacyTimeout = (this.bot.config as { globalTimeout?: number | string }).globalTimeout
const nestedTimeout = (this.bot.config.browser as { globalTimeout?: number | string } | undefined)?.globalTimeout
const globalTimeout = legacyTimeout ?? nestedTimeout ?? 30000
context.setDefaultTimeout(this.bot.utils.stringToMs(globalTimeout))
// Normalize viewport and page rendering so content fits typical screens
try {
const desktopViewport = { width: 1280, height: 800 }
const mobileViewport = { width: 390, height: 844 }
context.on('page', async (page) => {
try {
// Set a reasonable viewport size depending on device type
if (this.bot.isMobile) {
await page.setViewportSize(mobileViewport)
} else {
await page.setViewportSize(desktopViewport)
}
// Inject a tiny CSS to avoid gigantic scaling on some environments
await page.addInitScript(() => {
try {
const style = document.createElement('style')
style.id = '__mrs_fit_style'
style.textContent = `
html, body { overscroll-behavior: contain; }
/* Mild downscale to keep content within window on very large DPI */
@media (min-width: 1000px) {
html { zoom: 0.9 !important; }
}
`
document.documentElement.appendChild(style)
} catch { /* ignore */ }
})
} catch { /* ignore */ }
})
})
context.setDefaultTimeout(this.bot.utils.stringToNumber(this.bot.config?.globalTimeout ?? 30000))
} catch { /* ignore */ }
await context.addCookies(sessionData.cookies)
if (this.bot.config.saveFingerprint) {
// Persist fingerprint when feature is configured
if (saveFingerprint.mobile || saveFingerprint.desktop) {
await saveFingerprintData(this.bot.config.sessionPath, email, this.bot.isMobile, fingerprint)
}
this.bot.logger.info(
this.bot.isMobile,
'BROWSER',
`Created browser with User-Agent: "${fingerprint.fingerprint.navigator.userAgent}"`
)
this.bot.log(this.bot.isMobile, 'BROWSER', `Created browser with User-Agent: "${fingerprint.fingerprint.navigator.userAgent}"`)
this.bot.logger.debug(this.bot.isMobile, 'BROWSER-FINGERPRINT', JSON.stringify(fingerprint))
return {
context: context as unknown as BrowserContext,
fingerprint: fingerprint
}
return context as BrowserContext
}
async generateFingerprint(isMobile: boolean) {
async generateFingerprint() {
const fingerPrintData = new FingerprintGenerator().getFingerprint({
devices: isMobile ? ['mobile'] : ['desktop'],
operatingSystems: isMobile ? ['android', 'ios'] : ['windows', 'linux'],
devices: this.bot.isMobile ? ['mobile'] : ['desktop'],
operatingSystems: this.bot.isMobile ? ['android'] : ['windows'],
browsers: [{ name: 'edge' }]
})
const userAgentManager = new UserAgentManager(this.bot)
const updatedFingerPrintData = await userAgentManager.updateFingerprintUserAgent(fingerPrintData, isMobile)
const updatedFingerPrintData = await updateFingerprintUserAgent(fingerPrintData, this.bot.isMobile)
return updatedFingerPrintData
}
}
export default Browser
export default Browser

View File

@@ -1,14 +1,16 @@
import type { BrowserContext, Cookie } from 'patchright'
import type { AxiosRequestConfig, AxiosResponse } from 'axios'
import { BrowserContext, Page } from 'rebrowser-playwright'
import { CheerioAPI, load } from 'cheerio'
import { AxiosRequestConfig } from 'axios'
import type { MicrosoftRewardsBot } from '../index'
import { MicrosoftRewardsBot } from '../index'
import { saveSessionData } from '../util/Load'
import { TIMEOUTS, RETRY_LIMITS, SELECTORS, URLS } from '../constants'
import { Counters, DashboardData, MorePromotion, PromotionalItem } from '../interface/DashboardData'
import { QuizData } from '../interface/QuizData'
import { AppUserData } from '../interface/AppUserData'
import { EarnablePoints } from '../interface/Points'
import type { Counters, DashboardData } from './../interface/DashboardData'
import type { AppUserData } from '../interface/AppUserData'
import type { XboxDashboardData } from '../interface/XboxDashboardData'
import type { AppEarnablePoints, BrowserEarnablePoints, MissingSearchPoints } from '../interface/Points'
import type { AppDashboardData } from '../interface/AppDashBoardData'
export default class BrowserFunc {
private bot: MicrosoftRewardsBot
@@ -17,154 +19,316 @@ export default class BrowserFunc {
this.bot = bot
}
/**
* Fetch user desktop dashboard data
* Navigate the provided page to rewards homepage
* @param {Page} page Playwright page
*/
async goHome(page: Page) {
const navigateHome = async () => {
try {
await page.goto(this.bot.config.baseURL, {
waitUntil: 'domcontentloaded',
timeout: 30000
})
} catch (e: any) {
if (typeof e?.message === 'string' && e.message.includes('ERR_ABORTED')) {
this.bot.log(this.bot.isMobile, 'GO-HOME', 'Navigation aborted, retrying...', 'warn')
await this.bot.utils.wait(1500)
await page.goto(this.bot.config.baseURL, {
waitUntil: 'domcontentloaded',
timeout: 30000
})
} else {
throw e
}
}
}
try {
const dashboardURL = new URL(this.bot.config.baseURL)
if (new URL(page.url()).hostname !== dashboardURL.hostname) {
await navigateHome()
}
let success = false
for (let iteration = 1; iteration <= RETRY_LIMITS.GO_HOME_MAX; iteration++) {
await this.bot.utils.wait(TIMEOUTS.LONG)
await this.bot.browser.utils.tryDismissAllMessages(page)
try {
await page.waitForSelector(SELECTORS.MORE_ACTIVITIES, { timeout: 1000 })
this.bot.log(this.bot.isMobile, 'GO-HOME', 'Visited homepage successfully')
success = true
break
} catch {
const suspendedByHeader = await page
.waitForSelector(SELECTORS.SUSPENDED_ACCOUNT, { state: 'visible', timeout: 500 })
.then(() => true)
.catch(() => false)
if (suspendedByHeader) {
this.bot.log(
this.bot.isMobile,
'GO-HOME',
`Account suspension detected by header selector (iteration ${iteration})`,
'error'
)
throw new Error('Account has been suspended!')
}
try {
const mainContent =
(await page
.locator('#contentContainer, #main, .main-content')
.first()
.textContent({ timeout: 500 })
.catch(() => '')) || ''
const suspensionPatterns = [
/account\s+has\s+been\s+suspended/i,
/suspended\s+due\s+to\s+unusual\s+activity/i,
/your\s+account\s+is\s+temporarily\s+suspended/i
]
const isSuspended = suspensionPatterns.some((p) => p.test(mainContent))
if (isSuspended) {
this.bot.log(
this.bot.isMobile,
'GO-HOME',
`Account suspension detected by content text (iteration ${iteration})`,
'error'
)
throw new Error('Account has been suspended!')
}
} catch (e) {
this.bot.log(
this.bot.isMobile,
'GO-HOME',
`Suspension text check skipped: ${e instanceof Error ? e.message : String(e)}`,
'warn'
)
}
const currentURL = new URL(page.url())
if (currentURL.hostname !== dashboardURL.hostname) {
await this.bot.browser.utils.tryDismissAllMessages(page)
await this.bot.utils.wait(TIMEOUTS.MEDIUM_LONG)
try {
await navigateHome()
} catch (e: any) {
if (typeof e?.message === 'string' && e.message.includes('ERR_ABORTED')) {
this.bot.log(this.bot.isMobile, 'GO-HOME', 'Navigation aborted again; continuing...', 'warn')
} else {
throw e
}
}
} else {
this.bot.log(
this.bot.isMobile,
'GO-HOME',
`Activities not found yet (iteration ${iteration}/${RETRY_LIMITS.GO_HOME_MAX}), retrying...`,
'warn'
)
}
}
const backoff = Math.min(TIMEOUTS.VERY_LONG, 1000 + iteration * 500)
await this.bot.utils.wait(backoff)
}
if (!success) {
throw new Error('Failed to reach homepage or find activities within retry limit')
}
} catch (error) {
throw this.bot.log(
this.bot.isMobile,
'GO-HOME',
'An error occurred:' + (error instanceof Error ? ` ${error.message}` : ` ${String(error)}`),
'error'
)
}
}
/**
* Fetch user dashboard data
* @returns {DashboardData} Object of user bing rewards dashboard data
*/
async getDashboardData(): Promise<DashboardData> {
try {
const cookieHeader = this.bot.cookies.mobile
.map((c: { name: string; value: string }) => `${c.name}=${c.value}`)
.join('; ')
*/
async getDashboardData(page?: Page): Promise<DashboardData> {
const target = page ?? this.bot.homePage
const dashboardURL = new URL(this.bot.config.baseURL)
const currentURL = new URL(target.url())
const request: AxiosRequestConfig = {
url: `https://rewards.bing.com/api/getuserinfo?type=1&X-Requested-With=XMLHttpRequest&_=${Date.now()}`,
method: 'GET',
headers: {
...(this.bot.fingerprint?.headers ?? {}),
Cookie: cookieHeader,
Referer: 'https://rewards.bing.com/',
Origin: 'https://rewards.bing.com'
try {
// Should never happen since tasks are opened in a new tab!
if (currentURL.hostname !== dashboardURL.hostname) {
this.bot.log(this.bot.isMobile, 'DASHBOARD-DATA', 'Provided page did not equal dashboard page, redirecting to dashboard page')
await this.goHome(target)
}
let lastError: unknown = null
for (let attempt = 1; attempt <= 2; attempt++) {
try {
// Reload the page to get new data
await target.reload({ waitUntil: 'domcontentloaded' })
lastError = null
break
} catch (re) {
lastError = re
const msg = (re instanceof Error ? re.message : String(re))
this.bot.log(this.bot.isMobile, 'GET-DASHBOARD-DATA', `Reload failed attempt ${attempt}: ${msg}`, 'warn')
// If page/context closed => bail early after first retry
if (msg.includes('has been closed')) {
if (attempt === 1) {
this.bot.log(this.bot.isMobile, 'GET-DASHBOARD-DATA', 'Page appears closed; trying one navigation fallback', 'warn')
try {
await this.goHome(target)
} catch {/* ignore */ }
} else {
break
}
}
if (attempt === 2 && lastError) throw lastError
await this.bot.utils.wait(1000)
}
}
const response = await this.bot.axios.request(request)
return response.data.dashboard as DashboardData
} catch (error) {
this.bot.logger.info(
this.bot.isMobile,
'GET-DASHBOARD-DATA',
`Error fetching dashboard data: ${error instanceof Error ? error.message : String(error)}`
)
throw error
}
}
// Wait a bit longer for scripts to load, especially on mobile
await this.bot.utils.wait(this.bot.isMobile ? TIMEOUTS.LONG : TIMEOUTS.MEDIUM)
/**
* Fetch user app dashboard data
* @returns {AppDashboardData} Object of user bing rewards dashboard data
*/
async getAppDashboardData(): Promise<AppDashboardData> {
try {
const request: AxiosRequestConfig = {
url: 'https://prod.rewardsplatform.microsoft.com/dapi/me?channel=SAIOS&options=613',
method: 'GET',
headers: {
Authorization: `Bearer ${this.bot.accessToken}`,
'User-Agent':
'Bing/32.5.431027001 (com.microsoft.bing; build:431027001; iOS 17.6.1) Alamofire/5.10.2'
// Wait for the more-activities element to ensure page is fully loaded
await target.waitForSelector(SELECTORS.MORE_ACTIVITIES, { timeout: TIMEOUTS.DASHBOARD_WAIT }).catch(() => {
this.bot.log(this.bot.isMobile, 'GET-DASHBOARD-DATA', 'Activities element not found, continuing anyway', 'warn')
})
let scriptContent = await target.evaluate(() => {
const scripts = Array.from(document.querySelectorAll('script'))
const targetScript = scripts.find(script => script.innerText.includes('var dashboard'))
return targetScript?.innerText ? targetScript.innerText : null
})
if (!scriptContent) {
this.bot.log(this.bot.isMobile, 'GET-DASHBOARD-DATA', 'Dashboard script not found on first try, attempting recovery', 'warn')
// Force a navigation retry once before failing hard
try {
await this.goHome(target)
await target.waitForLoadState('domcontentloaded', { timeout: TIMEOUTS.VERY_LONG }).catch((e) => {
this.bot.log(this.bot.isMobile, 'GET-DASHBOARD-DATA', `Wait for load state failed: ${e}`, 'warn')
})
await this.bot.utils.wait(this.bot.isMobile ? TIMEOUTS.LONG : TIMEOUTS.MEDIUM)
} catch (e) {
this.bot.log(this.bot.isMobile, 'GET-DASHBOARD-DATA', `Recovery navigation failed: ${e}`, 'warn')
}
const retryContent = await target.evaluate(() => {
const scripts = Array.from(document.querySelectorAll('script'))
const targetScript = scripts.find(script => script.innerText.includes('var dashboard'))
return targetScript?.innerText ? targetScript.innerText : null
}).catch(() => null)
if (!retryContent) {
// Log additional debug info
const scriptsDebug = await target.evaluate(() => {
const scripts = Array.from(document.querySelectorAll('script'))
return scripts.map(s => s.innerText.substring(0, 100)).join(' | ')
}).catch(() => 'Unable to get script debug info')
this.bot.log(this.bot.isMobile, 'GET-DASHBOARD-DATA', `Available scripts preview: ${scriptsDebug}`, 'warn')
throw this.bot.log(this.bot.isMobile, 'GET-DASHBOARD-DATA', 'Dashboard data not found within script', 'error')
}
scriptContent = retryContent
}
const response = await this.bot.axios.request(request)
return response.data as AppDashboardData
} catch (error) {
this.bot.logger.info(
this.bot.isMobile,
'GET-APP-DASHBOARD-DATA',
`Error fetching dashboard data: ${error instanceof Error ? error.message : String(error)}`
)
throw error
}
}
// Extract the dashboard object from the script content
const dashboardData = await target.evaluate((scriptContent: string) => {
// Try multiple regex patterns for better compatibility
const patterns = [
/var dashboard = (\{.*?\});/s, // Original pattern
/var dashboard=(\{.*?\});/s, // No spaces
/var\s+dashboard\s*=\s*(\{.*?\});/s, // Flexible whitespace
/dashboard\s*=\s*(\{[\s\S]*?\});/ // More permissive
]
/**
* Fetch user xbox dashboard data
* @returns {XboxDashboardData} Object of user bing rewards dashboard data
*/
async getXBoxDashboardData(): Promise<XboxDashboardData> {
try {
const request: AxiosRequestConfig = {
url: 'https://prod.rewardsplatform.microsoft.com/dapi/me?channel=xboxapp&options=6',
method: 'GET',
headers: {
Authorization: `Bearer ${this.bot.accessToken}`,
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; Xbox; Xbox One X) AppleWebKit/537.36 (KHTML, like Gecko) Edge/18.19041'
for (const regex of patterns) {
const match = regex.exec(scriptContent)
if (match && match[1]) {
try {
return JSON.parse(match[1])
} catch (e) {
// Try next pattern if JSON parsing fails
continue
}
}
}
return null
}, scriptContent)
if (!dashboardData) {
// Log a snippet of the script content for debugging
const scriptPreview = scriptContent.substring(0, 200)
this.bot.log(this.bot.isMobile, 'GET-DASHBOARD-DATA', `Script preview: ${scriptPreview}`, 'warn')
throw this.bot.log(this.bot.isMobile, 'GET-DASHBOARD-DATA', 'Unable to parse dashboard script', 'error')
}
const response = await this.bot.axios.request(request)
return response.data as XboxDashboardData
return dashboardData
} catch (error) {
this.bot.logger.info(
this.bot.isMobile,
'GET-XBOX-DASHBOARD-DATA',
`Error fetching dashboard data: ${error instanceof Error ? error.message : String(error)}`
)
throw error
throw this.bot.log(this.bot.isMobile, 'GET-DASHBOARD-DATA', `Error fetching dashboard data: ${error}`, 'error')
}
}
/**
* Get search point counters
*/
* @returns {Counters} Object of search counter data
*/
async getSearchPoints(): Promise<Counters> {
const dashboardData = await this.getDashboardData() // Always fetch newest data
return dashboardData.userStatus.counters
}
missingSearchPoints(counters: Counters, isMobile: boolean): MissingSearchPoints {
const mobileData = counters.mobileSearch?.[0]
const desktopData = counters.pcSearch?.[0]
const edgeData = counters.pcSearch?.[1]
const mobilePoints = mobileData ? Math.max(0, mobileData.pointProgressMax - mobileData.pointProgress) : 0
const desktopPoints = desktopData ? Math.max(0, desktopData.pointProgressMax - desktopData.pointProgress) : 0
const edgePoints = edgeData ? Math.max(0, edgeData.pointProgressMax - edgeData.pointProgress) : 0
const totalPoints = isMobile ? mobilePoints : desktopPoints + edgePoints
return { mobilePoints, desktopPoints, edgePoints, totalPoints }
}
/**
* Get total earnable points with web browser
*/
async getBrowserEarnablePoints(): Promise<BrowserEarnablePoints> {
* @returns {number} Total earnable points
*/
async getBrowserEarnablePoints(): Promise<EarnablePoints> {
try {
let desktopSearchPoints = 0
let mobileSearchPoints = 0
let dailySetPoints = 0
let morePromotionsPoints = 0
const data = await this.getDashboardData()
const desktopSearchPoints =
data.userStatus.counters.pcSearch?.reduce(
(sum, x) => sum + (x.pointProgressMax - x.pointProgress),
0
) ?? 0
// Desktop Search Points
if (data.userStatus.counters.pcSearch?.length) {
data.userStatus.counters.pcSearch.forEach(x => desktopSearchPoints += (x.pointProgressMax - x.pointProgress))
}
const mobileSearchPoints =
data.userStatus.counters.mobileSearch?.reduce(
(sum, x) => sum + (x.pointProgressMax - x.pointProgress),
0
) ?? 0
// Mobile Search Points
if (data.userStatus.counters.mobileSearch?.length) {
data.userStatus.counters.mobileSearch.forEach(x => mobileSearchPoints += (x.pointProgressMax - x.pointProgress))
}
const todayDate = this.bot.utils.getFormattedDate()
const dailySetPoints =
data.dailySetPromotions[todayDate]?.reduce(
(sum, x) => sum + (x.pointProgressMax - x.pointProgress),
0
) ?? 0
// Daily Set
data.dailySetPromotions[this.bot.utils.getFormattedDate()]?.forEach(x => dailySetPoints += (x.pointProgressMax - x.pointProgress))
const morePromotionsPoints =
data.morePromotions?.reduce((sum, x) => {
if (
['quiz', 'urlreward'].includes(x.promotionType) &&
x.exclusiveLockedFeatureStatus !== 'locked'
) {
return sum + (x.pointProgressMax - x.pointProgress)
// More Promotions
if (data.morePromotions?.length) {
data.morePromotions.forEach(x => {
// Only count points from supported activities
if (['quiz', 'urlreward'].includes(x.promotionType) && x.exclusiveLockedFeatureStatus !== 'locked') {
morePromotionsPoints += (x.pointProgressMax - x.pointProgress)
}
return sum
}, 0) ?? 0
})
}
const totalEarnablePoints = desktopSearchPoints + mobileSearchPoints + dailySetPoints + morePromotionsPoints
@@ -176,258 +340,217 @@ export default class BrowserFunc {
totalEarnablePoints
}
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'GET-BROWSER-EARNABLE-POINTS',
`An error occurred: ${error instanceof Error ? error.message : String(error)}`
)
throw error
throw this.bot.log(this.bot.isMobile, 'GET-BROWSER-EARNABLE-POINTS', 'An error occurred:' + error, 'error')
}
}
/**
* Get total earnable points with mobile app
*/
async getAppEarnablePoints(): Promise<AppEarnablePoints> {
* @returns {number} Total earnable points
*/
async getAppEarnablePoints(accessToken: string) {
try {
const eligibleOffers = ['ENUS_readarticle3_30points', 'Gamification_Sapphire_DailyCheckIn']
const points = {
readToEarn: 0,
checkIn: 0,
totalEarnablePoints: 0
}
const request: AxiosRequestConfig = {
url: 'https://prod.rewardsplatform.microsoft.com/dapi/me?channel=SAAndroid&options=613',
const eligibleOffers = [
'ENUS_readarticle3_30points',
'Gamification_Sapphire_DailyCheckIn'
]
const data = await this.getDashboardData()
// Guard against missing profile/attributes and undefined settings
let geoLocale = data?.userProfile?.attributes?.country || 'US'
const useGeo = !!(this.bot?.config?.searchSettings?.useGeoLocaleQueries)
geoLocale = (useGeo && typeof geoLocale === 'string' && geoLocale.length === 2)
? geoLocale.toLowerCase()
: 'us'
const userDataRequest: AxiosRequestConfig = {
url: URLS.APP_USER_DATA,
method: 'GET',
headers: {
Authorization: `Bearer ${this.bot.accessToken}`,
'X-Rewards-Country': this.bot.userData.geoLocale,
'X-Rewards-Language': 'en',
'X-Rewards-ismobile': 'true'
'Authorization': `Bearer ${accessToken}`,
'X-Rewards-Country': geoLocale,
'X-Rewards-Language': 'en'
}
}
const response = await this.bot.axios.request(request)
const userData: AppUserData = response.data
const eligibleActivities = userData.response.promotions.filter(x =>
eligibleOffers.includes(x.attributes.offerid ?? '')
)
let readToEarn = 0
let checkIn = 0
const userDataResponse: AppUserData = (await this.bot.axios.request(userDataRequest)).data
const userData = userDataResponse.response
const eligibleActivities = userData.promotions.filter((x) => eligibleOffers.includes(x.attributes.offerid ?? ''))
for (const item of eligibleActivities) {
const attrs = item.attributes
if (item.attributes.type === 'msnreadearn') {
points.readToEarn = parseInt(item.attributes.pointmax ?? '') - parseInt(item.attributes.pointprogress ?? '')
break
} else if (item.attributes.type === 'checkin') {
const checkInDay = parseInt(item.attributes.progress ?? '') % 7
if (attrs.type === 'msnreadearn') {
const pointMax = parseInt(attrs.pointmax ?? '0')
const pointProgress = parseInt(attrs.pointprogress ?? '0')
readToEarn = Math.max(0, pointMax - pointProgress)
} else if (attrs.type === 'checkin') {
const progress = parseInt(attrs.progress ?? '0')
const checkInDay = progress % 7
const lastUpdated = new Date(attrs.last_updated ?? '')
const today = new Date()
if (checkInDay < 6 && today.getDate() !== lastUpdated.getDate()) {
checkIn = parseInt(attrs[`day_${checkInDay + 1}_points`] ?? '0')
if (checkInDay < 6 && (new Date()).getDate() != (new Date(item.attributes.last_updated ?? '')).getDate()) {
points.checkIn = parseInt(item.attributes['day_' + (checkInDay + 1) + '_points'] ?? '')
}
break
}
}
const totalEarnablePoints = readToEarn + checkIn
points.totalEarnablePoints = points.readToEarn + points.checkIn
return {
readToEarn,
checkIn,
totalEarnablePoints
}
return points
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'GET-APP-EARNABLE-POINTS',
`An error occurred: ${error instanceof Error ? error.message : String(error)}`
)
throw error
throw this.bot.log(this.bot.isMobile, 'GET-APP-EARNABLE-POINTS', 'An error occurred:' + error, 'error')
}
}
/**
* Get current point amount
* @returns {number} Current total point amount
*/
*/
async getCurrentPoints(): Promise<number> {
try {
const data = await this.getDashboardData()
return data.userStatus.availablePoints
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'GET-CURRENT-POINTS',
`An error occurred: ${error instanceof Error ? error.message : String(error)}`
)
throw error
throw this.bot.log(this.bot.isMobile, 'GET-CURRENT-POINTS', 'An error occurred:' + error, 'error')
}
}
/**
* Parse quiz data from provided page
* @param {Page} page Playwright page
* @returns {QuizData} Quiz data object
*/
async getQuizData(page: Page): Promise<QuizData> {
try {
// Wait for page to be fully loaded
await page.waitForLoadState('domcontentloaded')
await this.bot.utils.wait(TIMEOUTS.MEDIUM)
const html = await page.content()
const $ = load(html)
// Try multiple possible variable names
const possibleVariables = [
'_w.rewardsQuizRenderInfo',
'rewardsQuizRenderInfo',
'_w.quizRenderInfo',
'quizRenderInfo'
]
let scriptContent = ''
let foundVariable = ''
for (const varName of possibleVariables) {
scriptContent = $('script')
.toArray()
.map(el => $(el).text())
.find(t => t.includes(varName)) || ''
if (scriptContent) {
foundVariable = varName
break
}
}
if (scriptContent && foundVariable) {
// Escape dots in variable name for regex
const escapedVar = foundVariable.replace(/\./g, '\\.')
const regex = new RegExp(`${escapedVar}\\s*=\\s*({.*?});`, 's')
const match = regex.exec(scriptContent)
if (match && match[1]) {
const quizData = JSON.parse(match[1])
this.bot.log(this.bot.isMobile, 'GET-QUIZ-DATA', `Found quiz data using variable: ${foundVariable}`, 'log')
return quizData
} else {
throw this.bot.log(this.bot.isMobile, 'GET-QUIZ-DATA', `Variable ${foundVariable} found but could not extract JSON data`, 'error')
}
} else {
// Log available scripts for debugging
const allScripts = $('script')
.toArray()
.map(el => $(el).text())
.filter(t => t.length > 0)
.map(t => t.substring(0, 100))
this.bot.log(this.bot.isMobile, 'GET-QUIZ-DATA', `Script not found. Tried variables: ${possibleVariables.join(', ')}`, 'error')
this.bot.log(this.bot.isMobile, 'GET-QUIZ-DATA', `Found ${allScripts.length} scripts on page`, 'warn')
throw this.bot.log(this.bot.isMobile, 'GET-QUIZ-DATA', 'Script containing quiz data not found', 'error')
}
} catch (error) {
throw this.bot.log(this.bot.isMobile, 'GET-QUIZ-DATA', 'An error occurred: ' + error, 'error')
}
}
async waitForQuizRefresh(page: Page): Promise<boolean> {
try {
await page.waitForSelector(SELECTORS.QUIZ_CREDITS, { state: 'visible', timeout: TIMEOUTS.DASHBOARD_WAIT })
await this.bot.utils.wait(TIMEOUTS.MEDIUM_LONG)
return true
} catch (error) {
this.bot.log(this.bot.isMobile, 'QUIZ-REFRESH', 'An error occurred:' + error, 'error')
return false
}
}
async checkQuizCompleted(page: Page): Promise<boolean> {
try {
await page.waitForSelector(SELECTORS.QUIZ_COMPLETE, { state: 'visible', timeout: TIMEOUTS.MEDIUM_LONG })
await this.bot.utils.wait(TIMEOUTS.MEDIUM_LONG)
return true
} catch (error) {
return false
}
}
async loadInCheerio(page: Page): Promise<CheerioAPI> {
const html = await page.content()
const $ = load(html)
return $
}
async getPunchCardActivity(page: Page, activity: PromotionalItem | MorePromotion): Promise<string> {
let selector = ''
try {
const html = await page.content()
const $ = load(html)
const element = $('.offer-cta').toArray().find((x: unknown) => {
const el = x as { attribs?: { href?: string } }
return !!el.attribs?.href?.includes(activity.offerId)
})
if (element) {
selector = `a[href*="${element.attribs.href}"]`
}
} catch (error) {
this.bot.log(this.bot.isMobile, 'GET-PUNCHCARD-ACTIVITY', 'An error occurred:' + error, 'error')
}
return selector
}
async closeBrowser(browser: BrowserContext, email: string) {
try {
const cookies = await browser.cookies()
// Save cookies
this.bot.logger.debug(
this.bot.isMobile,
'CLOSE-BROWSER',
`Saving ${cookies.length} cookies to session folder!`
)
await saveSessionData(this.bot.config.sessionPath, cookies, email, this.bot.isMobile)
await saveSessionData(this.bot.config.sessionPath, browser, email, this.bot.isMobile)
await this.bot.utils.wait(2000)
await this.bot.utils.wait(TIMEOUTS.MEDIUM_LONG)
// Close browser
await browser.close()
this.bot.logger.info(this.bot.isMobile, 'CLOSE-BROWSER', 'Browser closed cleanly!')
this.bot.log(this.bot.isMobile, 'CLOSE-BROWSER', 'Browser closed cleanly!')
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'CLOSE-BROWSER',
`An error occurred: ${error instanceof Error ? error.message : String(error)}`
)
throw error
throw this.bot.log(this.bot.isMobile, 'CLOSE-BROWSER', 'An error occurred:' + error, 'error')
}
}
mergeCookies(response: AxiosResponse, currentCookieHeader: string = '', whitelist?: string[]): string {
const cookieMap = new Map<string, string>(
currentCookieHeader
.split(';')
.map(pair => pair.split('=').map(s => s.trim()))
.filter(([name, value]) => name && value)
.map(([name, value]) => [name, value] as [string, string])
)
const setCookieList = [response.headers['set-cookie']].flat().filter(Boolean) as string[]
const cookiesByName = new Map(this.bot.cookies.mobile.map(c => [c.name, c]))
for (const setCookie of setCookieList) {
const [nameValue, ...attributes] = setCookie.split(';').map(s => s.trim())
if (!nameValue) continue
const [name, value] = nameValue.split('=').map(s => s.trim())
if (!name) continue
if (whitelist && !whitelist?.includes(name)) {
continue
}
const attrs = this.parseAttributes(attributes)
const existing = cookiesByName.get(name)
if (!value) {
if (existing) {
cookiesByName.delete(name)
this.bot.cookies.mobile = this.bot.cookies.mobile.filter(c => c.name !== name)
}
cookieMap.delete(name)
continue
}
if (attrs.expires !== undefined && attrs.expires < Date.now() / 1000) {
if (existing) {
cookiesByName.delete(name)
this.bot.cookies.mobile = this.bot.cookies.mobile.filter(c => c.name !== name)
}
cookieMap.delete(name)
continue
}
cookieMap.set(name, value)
if (existing) {
this.updateCookie(existing, value, attrs)
} else {
this.bot.cookies.mobile.push(this.createCookie(name, value, attrs))
}
}
return Array.from(cookieMap, ([name, value]) => `${name}=${value}`).join('; ')
}
private parseAttributes(attributes: string[]) {
const attrs: {
domain?: string
path?: string
expires?: number
httpOnly?: boolean
secure?: boolean
sameSite?: Cookie['sameSite']
} = {}
for (const attr of attributes) {
const [key, val] = attr.split('=').map(s => s?.trim())
const lowerKey = key?.toLowerCase()
switch (lowerKey) {
case 'domain':
case 'path': {
if (val) attrs[lowerKey] = val
break
}
case 'expires': {
if (val) {
const ts = Date.parse(val)
if (!isNaN(ts)) attrs.expires = Math.floor(ts / 1000)
}
break
}
case 'max-age': {
if (val) {
const maxAge = Number(val)
if (!isNaN(maxAge)) attrs.expires = Math.floor(Date.now() / 1000) + maxAge
}
break
}
case 'httponly': {
attrs.httpOnly = true
break
}
case 'secure': {
attrs.secure = true
break
}
case 'samesite': {
const normalized = val?.toLowerCase()
if (normalized && ['lax', 'strict', 'none'].includes(normalized)) {
attrs.sameSite = (normalized.charAt(0).toUpperCase() +
normalized.slice(1)) as Cookie['sameSite']
}
break
}
}
}
return attrs
}
private updateCookie(cookie: Cookie, value: string, attrs: ReturnType<typeof this.parseAttributes>) {
cookie.value = value
if (attrs.domain) cookie.domain = attrs.domain
if (attrs.path) cookie.path = attrs.path
//if (attrs.expires !== undefined) cookie.expires = attrs.expires
//if (attrs.httpOnly) cookie.httpOnly = true
//if (attrs.secure) cookie.secure = true
//if (attrs.sameSite) cookie.sameSite = attrs.sameSite
}
private createCookie(name: string, value: string, attrs: ReturnType<typeof this.parseAttributes>): Cookie {
return {
name,
value,
domain: attrs.domain || '.bing.com',
path: attrs.path || '/'
/*
...(attrs.expires !== undefined && { expires: attrs.expires }),
...(attrs.httpOnly && { httpOnly: true }),
...(attrs.secure && { secure: true }),
...(attrs.sameSite && { sameSite: attrs.sameSite })
*/
} as Cookie
}
}
}

219
src/browser/BrowserUtil.ts Normal file
View File

@@ -0,0 +1,219 @@
import { Page } from 'rebrowser-playwright'
import { load } from 'cheerio'
import { MicrosoftRewardsBot } from '../index'
type DismissButton = { selector: string; label: string; isXPath?: boolean }
export default class BrowserUtil {
private bot: MicrosoftRewardsBot
private static readonly DISMISS_BUTTONS: readonly DismissButton[] = [
{ selector: '#acceptButton', label: 'AcceptButton' },
{ selector: '.optanon-allow-all, .optanon-alert-box-button', label: 'OneTrust Accept' },
{ selector: '.ext-secondary.ext-button', label: 'Skip For Now' },
{ selector: '#iLandingViewAction', label: 'Landing Continue' },
{ selector: '#iShowSkip', label: 'Show Skip' },
{ selector: '#iNext', label: 'Next' },
{ selector: '#iLooksGood', label: 'LooksGood' },
{ selector: '#idSIButton9', label: 'PrimaryLoginButton' },
{ selector: '.ms-Button.ms-Button--primary', label: 'Primary Generic' },
{ selector: '.c-glyph.glyph-cancel', label: 'Mobile Welcome Cancel' },
{ selector: '.maybe-later, button[data-automation-id*="maybeLater" i]', label: 'Maybe Later' },
{ selector: '#bnp_btn_reject', label: 'Bing Cookie Reject' },
{ selector: '#bnp_btn_accept', label: 'Bing Cookie Accept' },
{ selector: '#bnp_close_link', label: 'Bing Cookie Close' },
{ selector: '#reward_pivot_earn', label: 'Rewards Pivot Earn' },
{ selector: '//div[@id="cookieConsentContainer"]//button[contains(text(), "Accept")]', label: 'Legacy Cookie Accept', isXPath: true }
]
private static readonly OVERLAY_SELECTORS = {
container: '#bnp_overlay_wrapper',
reject: '#bnp_btn_reject, button[aria-label*="Reject" i]',
accept: '#bnp_btn_accept'
} as const
private static readonly STREAK_DIALOG_SELECTORS = {
container: '[role="dialog"], div[role="alert"], div.ms-Dialog',
textFilter: /streak protection has run out/i,
closeButtons: 'button[aria-label*="close" i], button:has-text("Close"), button:has-text("Dismiss"), button:has-text("Got it"), button:has-text("OK"), button:has-text("Ok")'
} as const
private static readonly TERMS_UPDATE_SELECTORS = {
titleId: '#iTOUTitle',
titleText: /we're updating our terms/i,
nextButton: 'button[data-testid="primaryButton"]:has-text("Next"), button[type="submit"]:has-text("Next")'
} as const
constructor(bot: MicrosoftRewardsBot) {
this.bot = bot
}
async tryDismissAllMessages(page: Page): Promise<void> {
const maxRounds = 3
for (let round = 0; round < maxRounds; round++) {
const dismissCount = await this.dismissRound(page)
if (dismissCount === 0) break
}
}
private async dismissRound(page: Page): Promise<number> {
let count = 0
count += await this.dismissStandardButtons(page)
count += await this.dismissOverlayButtons(page)
count += await this.dismissStreakDialog(page)
count += await this.dismissTermsUpdateDialog(page)
return count
}
private async dismissStandardButtons(page: Page): Promise<number> {
let count = 0
for (const btn of BrowserUtil.DISMISS_BUTTONS) {
const dismissed = await this.tryClickButton(page, btn)
if (dismissed) {
count++
await page.waitForTimeout(150)
}
}
return count
}
private async tryClickButton(page: Page, btn: DismissButton): Promise<boolean> {
try {
const loc = btn.isXPath ? page.locator(`xpath=${btn.selector}`) : page.locator(btn.selector)
const visible = await loc.first().isVisible({ timeout: 200 }).catch(() => false)
if (!visible) return false
await loc.first().click({ timeout: 500 }).catch(() => {})
this.bot.log(this.bot.isMobile, 'DISMISS-ALL-MESSAGES', `Dismissed: ${btn.label}`)
return true
} catch {
return false
}
}
private async dismissOverlayButtons(page: Page): Promise<number> {
try {
const { container, reject, accept } = BrowserUtil.OVERLAY_SELECTORS
const overlay = page.locator(container)
const visible = await overlay.isVisible({ timeout: 200 }).catch(() => false)
if (!visible) return 0
const rejectBtn = overlay.locator(reject)
if (await rejectBtn.first().isVisible().catch(() => false)) {
await rejectBtn.first().click({ timeout: 500 }).catch(() => {})
this.bot.log(this.bot.isMobile, 'DISMISS-ALL-MESSAGES', 'Dismissed: Overlay Reject')
return 1
}
const acceptBtn = overlay.locator(accept)
if (await acceptBtn.first().isVisible().catch(() => false)) {
await acceptBtn.first().click({ timeout: 500 }).catch(() => {})
this.bot.log(this.bot.isMobile, 'DISMISS-ALL-MESSAGES', 'Dismissed: Overlay Accept')
return 1
}
return 0
} catch {
return 0
}
}
private async dismissStreakDialog(page: Page): Promise<number> {
try {
const { container, textFilter, closeButtons } = BrowserUtil.STREAK_DIALOG_SELECTORS
const dialog = page.locator(container).filter({ hasText: textFilter })
const visible = await dialog.first().isVisible({ timeout: 200 }).catch(() => false)
if (!visible) return 0
const closeBtn = dialog.locator(closeButtons).first()
if (await closeBtn.isVisible({ timeout: 200 }).catch(() => false)) {
await closeBtn.click({ timeout: 500 }).catch(() => {})
this.bot.log(this.bot.isMobile, 'DISMISS-ALL-MESSAGES', 'Dismissed: Streak Protection Dialog Button')
return 1
}
await page.keyboard.press('Escape').catch(() => {})
this.bot.log(this.bot.isMobile, 'DISMISS-ALL-MESSAGES', 'Dismissed: Streak Protection Dialog Escape')
return 1
} catch {
return 0
}
}
private async dismissTermsUpdateDialog(page: Page): Promise<number> {
try {
const { titleId, titleText, nextButton } = BrowserUtil.TERMS_UPDATE_SELECTORS
// Check if terms update page is present
const titleById = page.locator(titleId)
const titleByText = page.locator('h1').filter({ hasText: titleText })
const hasTitle = await titleById.isVisible({ timeout: 200 }).catch(() => false) ||
await titleByText.first().isVisible({ timeout: 200 }).catch(() => false)
if (!hasTitle) return 0
// Click the Next button
const nextBtn = page.locator(nextButton).first()
if (await nextBtn.isVisible({ timeout: 500 }).catch(() => false)) {
await nextBtn.click({ timeout: 1000 }).catch(() => {})
this.bot.log(this.bot.isMobile, 'DISMISS-ALL-MESSAGES', 'Dismissed: Terms Update Dialog (Next)')
// Wait a bit for navigation
await page.waitForTimeout(1000)
return 1
}
return 0
} catch {
return 0
}
}
async getLatestTab(page: Page): Promise<Page> {
try {
await this.bot.utils.wait(1000)
const browser = page.context()
const pages = browser.pages()
const newTab = pages[pages.length - 1]
if (newTab) {
return newTab
}
throw this.bot.log(this.bot.isMobile, 'GET-NEW-TAB', 'Unable to get latest tab', 'error')
} catch (error) {
throw this.bot.log(this.bot.isMobile, 'GET-NEW-TAB', 'An error occurred:' + error, 'error')
}
}
async reloadBadPage(page: Page): Promise<void> {
try {
const html = await page.content().catch(() => '')
const $ = load(html)
const isNetworkError = $('body.neterror').length
if (isNetworkError) {
this.bot.log(this.bot.isMobile, 'RELOAD-BAD-PAGE', 'Bad page detected, reloading!')
await page.reload()
}
} catch (error) {
throw this.bot.log(this.bot.isMobile, 'RELOAD-BAD-PAGE', 'An error occurred:' + error, 'error')
}
}
/**
* Perform small human-like gestures: short waits, minor mouse moves and occasional scrolls.
* This should be called sparingly between actions to avoid a fixed cadence.
*/
async humanizePage(page: Page): Promise<void> {
try {
await this.bot.humanizer.microGestures(page)
await this.bot.humanizer.actionPause()
} catch { /* swallow */ }
}
}

View File

@@ -1,273 +0,0 @@
import { type Page, type BrowserContext } from 'patchright'
import { CheerioAPI, load } from 'cheerio'
import { ClickOptions, createCursor } from 'ghost-cursor-playwright-port'
import type { MicrosoftRewardsBot } from '../index'
export default class BrowserUtils {
private bot: MicrosoftRewardsBot
constructor(bot: MicrosoftRewardsBot) {
this.bot = bot
}
async tryDismissAllMessages(page: Page): Promise<void> {
try {
const buttons = [
{ selector: '#acceptButton', label: 'AcceptButton' },
{ selector: '#wcpConsentBannerCtrl > * > button:first-child', label: 'Bing Cookies Accept' },
{ selector: '.ext-secondary.ext-button', label: '"Skip for now" Button' },
{ selector: '#iLandingViewAction', label: 'iLandingViewAction' },
{ selector: '#iShowSkip', label: 'iShowSkip' },
{ selector: '#iNext', label: 'iNext' },
{ selector: '#iLooksGood', label: 'iLooksGood' },
{ selector: '#idSIButton9', label: 'idSIButton9' },
{ selector: '.ms-Button.ms-Button--primary', label: 'Primary Button' },
{ selector: '.c-glyph.glyph-cancel', label: 'Mobile Welcome Button' },
{ selector: '.maybe-later', label: 'Mobile Rewards App Banner' },
{ selector: '#bnp_btn_accept', label: 'Bing Cookie Banner' },
{ selector: '#reward_pivot_earn', label: 'Reward Coupon Accept' }
]
const checkVisible = await Promise.allSettled(
buttons.map(async b => ({
...b,
isVisible: await page
.locator(b.selector)
.isVisible()
.catch(() => false)
}))
)
const visibleButtons = checkVisible
.filter(r => r.status === 'fulfilled' && r.value.isVisible)
.map(r => (r.status === 'fulfilled' ? r.value : null))
.filter(Boolean)
if (visibleButtons.length > 0) {
await Promise.allSettled(
visibleButtons.map(async b => {
if (b) {
const clicked = await this.ghostClick(page, b.selector)
if (clicked) {
this.bot.logger.debug(
this.bot.isMobile,
'DISMISS-ALL-MESSAGES',
`Dismissed: ${b.label}`
)
}
}
})
)
await this.bot.utils.wait(300)
}
// Overlay
const overlay = await page.$('#bnp_overlay_wrapper')
if (overlay) {
const rejected = await this.ghostClick(page, '#bnp_btn_reject, button[aria-label*="Reject" i]')
if (rejected) {
this.bot.logger.debug(this.bot.isMobile, 'DISMISS-ALL-MESSAGES', 'Dismissed: Bing Overlay Reject')
} else {
const accepted = await this.ghostClick(page, '#bnp_btn_accept')
if (accepted) {
this.bot.logger.debug(
this.bot.isMobile,
'DISMISS-ALL-MESSAGES',
'Dismissed: Bing Overlay Accept'
)
}
}
await this.bot.utils.wait(250)
}
} catch (error) {
this.bot.logger.warn(
this.bot.isMobile,
'DISMISS-ALL-MESSAGES',
`Handler error: ${error instanceof Error ? error.message : String(error)}`
)
}
}
async getLatestTab(page: Page): Promise<Page> {
try {
const browser: BrowserContext = page.context()
const pages = browser.pages()
const newTab = pages[pages.length - 1]
if (!newTab) {
throw this.bot.logger.error(this.bot.isMobile, 'GET-NEW-TAB', 'No tabs could be found!')
}
return newTab
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'GET-NEW-TAB',
`Unable to get latest tab: ${error instanceof Error ? error.message : String(error)}`
)
throw error
}
}
async reloadBadPage(page: Page): Promise<boolean> {
try {
const html = await page.content().catch(() => '')
const $ = load(html)
if ($('body.neterror').length) {
this.bot.logger.info(this.bot.isMobile, 'RELOAD-BAD-PAGE', 'Bad page detected, reloading!')
try {
await page.reload({ waitUntil: 'load' })
} catch {
await page.reload().catch(() => {})
}
return true
} else {
return false
}
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'RELOAD-BAD-PAGE',
`Reload check failed: ${error instanceof Error ? error.message : String(error)}`
)
return true
}
}
async closeTabs(page: Page, config = { minTabs: 1, maxTabs: 1 }): Promise<Page> {
try {
const browser = page.context()
const tabs = browser.pages()
this.bot.logger.debug(
this.bot.isMobile,
'SEARCH-CLOSE-TABS',
`Found ${tabs.length} tab(s) open (min: ${config.minTabs}, max: ${config.maxTabs})`
)
// Check if valid
if (config.minTabs < 1 || config.maxTabs < config.minTabs) {
this.bot.logger.warn(this.bot.isMobile, 'SEARCH-CLOSE-TABS', 'Invalid config, using defaults')
config = { minTabs: 1, maxTabs: 1 }
}
// Close if more than max config
if (tabs.length > config.maxTabs) {
const tabsToClose = tabs.slice(config.maxTabs)
const closeResults = await Promise.allSettled(tabsToClose.map(tab => tab.close()))
const closedCount = closeResults.filter(r => r.status === 'fulfilled').length
this.bot.logger.debug(
this.bot.isMobile,
'SEARCH-CLOSE-TABS',
`Closed ${closedCount}/${tabsToClose.length} excess tab(s) to reach max of ${config.maxTabs}`
)
// Open more tabs
} else if (tabs.length < config.minTabs) {
const tabsNeeded = config.minTabs - tabs.length
this.bot.logger.debug(
this.bot.isMobile,
'SEARCH-CLOSE-TABS',
`Opening ${tabsNeeded} tab(s) to reach min of ${config.minTabs}`
)
const newTabPromises = Array.from({ length: tabsNeeded }, async () => {
try {
const newPage = await browser.newPage()
await newPage.goto(this.bot.config.baseURL, { waitUntil: 'domcontentloaded', timeout: 15000 })
return newPage
} catch (error) {
this.bot.logger.warn(
this.bot.isMobile,
'SEARCH-CLOSE-TABS',
`Failed to create new tab: ${error instanceof Error ? error.message : String(error)}`
)
return null
}
})
await Promise.allSettled(newTabPromises)
}
const latestTab = await this.getLatestTab(page)
return latestTab
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'SEARCH-CLOSE-TABS',
`Error: ${error instanceof Error ? error.message : String(error)}`
)
return page
}
}
async loadInCheerio(data: Page | string): Promise<CheerioAPI> {
const html: string = typeof data === 'string' ? data : await data.content()
const $ = load(html)
return $
}
async ghostClick(page: Page, selector: string, options?: ClickOptions): Promise<boolean> {
try {
this.bot.logger.debug(
this.bot.isMobile,
'GHOST-CLICK',
`Trying to click selector: ${selector}, options: ${JSON.stringify(options)}`
)
// Wait for selector to exist before clicking
await page.waitForSelector(selector, { timeout: 10000 })
const cursor = createCursor(page as any)
await cursor.click(selector, options)
return true
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'GHOST-CLICK',
`Failed for ${selector}: ${error instanceof Error ? error.message : String(error)}`
)
return false
}
}
async disableFido(page: Page) {
const routePattern = '**/GetCredentialType.srf*'
await page.route(routePattern, route => {
try {
const request = route.request()
const postData = request.postData()
const body = postData ? JSON.parse(postData) : {}
body.isFidoSupported = false
this.bot.logger.debug(
this.bot.isMobile,
'DISABLE-FIDO',
`Modified request body: isFidoSupported set to ${body.isFidoSupported}`
)
route.continue({
postData: JSON.stringify(body),
headers: {
...request.headers(),
'Content-Type': 'application/json'
}
})
} catch (error) {
this.bot.logger.debug(
this.bot.isMobile,
'DISABLE-FIDO',
`An error occurred: ${error instanceof Error ? error.message : String(error)}`
)
route.continue()
}
})
}
}

View File

@@ -1,164 +0,0 @@
import axios from 'axios'
import type { BrowserFingerprintWithHeaders } from 'fingerprint-generator'
import type { ChromeVersion, EdgeVersion } from '../interface/UserAgentUtil'
import type { MicrosoftRewardsBot } from '../index'
export class UserAgentManager {
private static readonly NOT_A_BRAND_VERSION = '99'
constructor(private bot: MicrosoftRewardsBot) {}
async getUserAgent(isMobile: boolean) {
const system = this.getSystemComponents(isMobile)
const app = await this.getAppComponents(isMobile)
const uaTemplate = isMobile
? `Mozilla/5.0 (${system}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${app.chrome_reduced_version} Mobile Safari/537.36 EdgA/${app.edge_version}`
: `Mozilla/5.0 (${system}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${app.chrome_reduced_version} Safari/537.36 Edg/${app.edge_version}`
const platformVersion = `${isMobile ? Math.floor(Math.random() * 5) + 9 : Math.floor(Math.random() * 15) + 1}.0.0`
const uaMetadata = {
isMobile,
platform: isMobile ? 'Android' : 'Windows',
fullVersionList: [
{ brand: 'Not/A)Brand', version: `${UserAgentManager.NOT_A_BRAND_VERSION}.0.0.0` },
{ brand: 'Microsoft Edge', version: app['edge_version'] },
{ brand: 'Chromium', version: app['chrome_version'] }
],
brands: [
{ brand: 'Not/A)Brand', version: UserAgentManager.NOT_A_BRAND_VERSION },
{ brand: 'Microsoft Edge', version: app['edge_major_version'] },
{ brand: 'Chromium', version: app['chrome_major_version'] }
],
platformVersion,
architecture: isMobile ? '' : 'x86',
bitness: isMobile ? '' : '64',
model: ''
}
return { userAgent: uaTemplate, userAgentMetadata: uaMetadata }
}
async getChromeVersion(isMobile: boolean): Promise<string> {
try {
const request = {
url: 'https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions.json',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
const response = await axios(request)
const data: ChromeVersion = response.data
return data.channels.Stable.version
} catch (error) {
this.bot.logger.error(
isMobile,
'USERAGENT-CHROME-VERSION',
`An error occurred: ${error instanceof Error ? error.message : String(error)}`
)
throw error
}
}
async getEdgeVersions(isMobile: boolean) {
try {
const request = {
url: 'https://edgeupdates.microsoft.com/api/products',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
const response = await axios(request)
const data: EdgeVersion[] = response.data
const stable = data.find(x => x.Product == 'Stable') as EdgeVersion
return {
android: stable.Releases.find(x => x.Platform == 'Android')?.ProductVersion,
windows: stable.Releases.find(x => x.Platform == 'Windows' && x.Architecture == 'x64')?.ProductVersion
}
} catch (error) {
this.bot.logger.error(
isMobile,
'USERAGENT-EDGE-VERSION',
`An error occurred: ${error instanceof Error ? error.message : String(error)}`
)
throw error
}
}
getSystemComponents(mobile: boolean): string {
if (mobile) {
const androidVersion = 10 + Math.floor(Math.random() * 5)
return `Linux; Android ${androidVersion}; K`
}
return 'Windows NT 10.0; Win64; x64'
}
async getAppComponents(isMobile: boolean) {
const versions = await this.getEdgeVersions(isMobile)
const edgeVersion = isMobile ? versions.android : (versions.windows as string)
const edgeMajorVersion = edgeVersion?.split('.')[0]
const chromeVersion = await this.getChromeVersion(isMobile)
const chromeMajorVersion = chromeVersion?.split('.')[0]
const chromeReducedVersion = `${chromeMajorVersion}.0.0.0`
return {
not_a_brand_version: `${UserAgentManager.NOT_A_BRAND_VERSION}.0.0.0`,
not_a_brand_major_version: UserAgentManager.NOT_A_BRAND_VERSION,
edge_version: edgeVersion as string,
edge_major_version: edgeMajorVersion as string,
chrome_version: chromeVersion as string,
chrome_major_version: chromeMajorVersion as string,
chrome_reduced_version: chromeReducedVersion as string
}
}
async updateFingerprintUserAgent(
fingerprint: BrowserFingerprintWithHeaders,
isMobile: boolean
): Promise<BrowserFingerprintWithHeaders> {
try {
const userAgentData = await this.getUserAgent(isMobile)
const componentData = await this.getAppComponents(isMobile)
//@ts-expect-error Errors due it not exactly matching
fingerprint.fingerprint.navigator.userAgentData = userAgentData.userAgentMetadata
fingerprint.fingerprint.navigator.userAgent = userAgentData.userAgent
fingerprint.fingerprint.navigator.appVersion = userAgentData.userAgent.replace(
`${fingerprint.fingerprint.navigator.appCodeName}/`,
''
)
fingerprint.headers['user-agent'] = userAgentData.userAgent
fingerprint.headers['sec-ch-ua'] =
`"Microsoft Edge";v="${componentData.edge_major_version}", "Not=A?Brand";v="${componentData.not_a_brand_major_version}", "Chromium";v="${componentData.chrome_major_version}"`
fingerprint.headers['sec-ch-ua-full-version-list'] =
`"Microsoft Edge";v="${componentData.edge_version}", "Not=A?Brand";v="${componentData.not_a_brand_version}", "Chromium";v="${componentData.chrome_version}"`
/*
Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Mobile Safari/537.36 EdgA/129.0.0.0
sec-ch-ua-full-version-list: "Microsoft Edge";v="129.0.2792.84", "Not=A?Brand";v="8.0.0.0", "Chromium";v="129.0.6668.90"
sec-ch-ua: "Microsoft Edge";v="129", "Not=A?Brand";v="8", "Chromium";v="129"
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36
"Google Chrome";v="129.0.6668.90", "Not=A?Brand";v="8.0.0.0", "Chromium";v="129.0.6668.90"
*/
return fingerprint
} catch (error) {
this.bot.logger.error(
isMobile,
'USER-AGENT-UPDATE',
`An error occurred: ${error instanceof Error ? error.message : String(error)}`
)
throw error
}
}
}

View File

@@ -1,509 +0,0 @@
import type { Page } from 'patchright'
import type { MicrosoftRewardsBot } from '../../index'
import { saveSessionData } from '../../util/Load'
// Methods
import { MobileAccessLogin } from './methods/MobileAccessLogin'
import { EmailLogin } from './methods/EmailLogin'
import { PasswordlessLogin } from './methods/PasswordlessLogin'
import { TotpLogin } from './methods/Totp2FALogin'
type LoginState =
| 'EMAIL_INPUT'
| 'PASSWORD_INPUT'
| 'SIGN_IN_ANOTHER_WAY'
| 'PASSKEY_ERROR'
| 'PASSKEY_VIDEO'
| 'KMSI_PROMPT'
| 'LOGGED_IN'
| 'ACCOUNT_LOCKED'
| 'ERROR_ALERT'
| '2FA_TOTP'
| 'LOGIN_PASSWORDLESS'
| 'GET_A_CODE'
| 'UNKNOWN'
| 'CHROMEWEBDATA_ERROR'
export class Login {
emailLogin: EmailLogin
passwordlessLogin: PasswordlessLogin
totp2FALogin: TotpLogin
constructor(private bot: MicrosoftRewardsBot) {
this.emailLogin = new EmailLogin(this.bot)
this.passwordlessLogin = new PasswordlessLogin(this.bot)
this.totp2FALogin = new TotpLogin(this.bot)
}
private readonly primaryButtonSelector = 'button[data-testid="primaryButton"]'
private readonly secondaryButtonSelector = 'button[data-testid="secondaryButton"]'
async login(page: Page, email: string, password: string, totpSecret?: string) {
try {
this.bot.logger.info(this.bot.isMobile, 'LOGIN', 'Starting login process')
await page.goto('https://www.bing.com/rewards/dashboard', { waitUntil: 'domcontentloaded' }).catch(() => {})
await this.bot.utils.wait(2000)
await this.bot.browser.utils.reloadBadPage(page)
await this.bot.browser.utils.disableFido(page)
const maxIterations = 25
let iteration = 0
let previousState: LoginState = 'UNKNOWN'
let sameStateCount = 0
while (iteration < maxIterations) {
if (page.isClosed()) throw new Error('Page closed unexpectedly')
iteration++
this.bot.logger.debug(this.bot.isMobile, 'LOGIN', `State check iteration ${iteration}/${maxIterations}`)
const state = await this.detectCurrentState(page)
this.bot.logger.debug(this.bot.isMobile, 'LOGIN', `Current state: ${state}`)
if (state !== previousState && previousState !== 'UNKNOWN') {
this.bot.logger.info(this.bot.isMobile, 'LOGIN', `State transition: ${previousState}${state}`)
}
if (state === previousState && state !== 'LOGGED_IN' && state !== 'UNKNOWN') {
sameStateCount++
if (sameStateCount >= 4) {
this.bot.logger.warn(
this.bot.isMobile,
'LOGIN',
`Stuck in state "${state}" for 4 loops. Refreshing page...`
)
await page.reload({ waitUntil: 'domcontentloaded' })
await this.bot.utils.wait(3000)
sameStateCount = 0
previousState = 'UNKNOWN'
continue
}
} else {
sameStateCount = 0
}
previousState = state
if (state === 'LOGGED_IN') {
this.bot.logger.info(this.bot.isMobile, 'LOGIN', 'Successfully logged in')
break
}
const shouldContinue = await this.handleState(state, page, email, password, totpSecret)
if (!shouldContinue) {
throw new Error(`Login failed or aborted at state: ${state}`)
}
await this.bot.utils.wait(1000)
}
if (iteration >= maxIterations) {
throw new Error('Login timeout: exceeded maximum iterations')
}
await this.finalizeLogin(page, email)
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'LOGIN',
`An error occurred: ${error instanceof Error ? error.message : String(error)}`
)
throw error
}
}
private async detectCurrentState(page: Page): Promise<LoginState> {
// Make sure we settled before getting a URL
await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {})
const url = new URL(page.url())
this.bot.logger.debug(this.bot.isMobile, 'DETECT-CURRENT-STATE', `Current URL: ${url}`)
if (url.hostname === 'chromewebdata') {
this.bot.logger.warn(this.bot.isMobile, 'DETECT-CURRENT-STATE', 'Detected chromewebdata error page')
return 'CHROMEWEBDATA_ERROR'
}
const isLocked = await page
.waitForSelector('#serviceAbuseLandingTitle', { state: 'visible', timeout: 200 })
.then(() => true)
.catch(() => false)
if (isLocked) {
return 'ACCOUNT_LOCKED'
}
// If instantly loading rewards dash, logged in
if (url.hostname === 'rewards.bing.com') {
return 'LOGGED_IN'
}
// If account dash, logged in
if (url.hostname === 'account.microsoft.com') {
return 'LOGGED_IN'
}
const check = async (selector: string, state: LoginState): Promise<LoginState | null> => {
return page
.waitForSelector(selector, { state: 'visible', timeout: 200 })
.then(visible => (visible ? state : null))
.catch(() => null)
}
const results = await Promise.all([
check('div[role="alert"]', 'ERROR_ALERT'),
check('[data-testid="passwordEntry"]', 'PASSWORD_INPUT'),
check('input#usernameEntry', 'EMAIL_INPUT'),
check('[data-testid="kmsiVideo"]', 'KMSI_PROMPT'),
check('[data-testid="biometricVideo"]', 'PASSKEY_VIDEO'),
check('[data-testid="registrationImg"]', 'PASSKEY_ERROR'),
check('[data-testid="tile"]:has(svg path[d*="M11.78 10.22a.75.75"])', 'SIGN_IN_ANOTHER_WAY'),
check('[data-testid="deviceShieldCheckmarkVideo"]', 'LOGIN_PASSWORDLESS'),
check('input[name="otc"]', '2FA_TOTP'),
check('form[name="OneTimeCodeViewForm"]', '2FA_TOTP')
])
// Get a code
const identityBanner = await page
.waitForSelector('[data-testid="identityBanner"]', { state: 'visible', timeout: 200 })
.then(() => true)
.catch(() => false)
const primaryButton = await page
.waitForSelector(this.primaryButtonSelector, { state: 'visible', timeout: 200 })
.then(() => true)
.catch(() => false)
const passwordEntry = await page
.waitForSelector('[data-testid="passwordEntry"]', { state: 'visible', timeout: 200 })
.then(() => true)
.catch(() => false)
if (identityBanner && primaryButton && !passwordEntry && !results.includes('2FA_TOTP')) {
results.push('GET_A_CODE') // Lower prio
}
// Final
let foundStates = results.filter((s): s is LoginState => s !== null)
if (foundStates.length === 0) return 'UNKNOWN'
if (foundStates.includes('ERROR_ALERT')) {
if (url.hostname !== 'login.live.com') {
// Remove ERROR_ALERT if not on login.live.com
foundStates = foundStates.filter(s => s !== 'ERROR_ALERT')
}
if (foundStates.includes('2FA_TOTP')) {
// Don't throw on TOTP if expired code is entered
foundStates = foundStates.filter(s => s !== 'ERROR_ALERT')
}
// On login.live.com, keep it
return 'ERROR_ALERT'
}
if (foundStates.includes('ERROR_ALERT')) return 'ERROR_ALERT'
if (foundStates.includes('ACCOUNT_LOCKED')) return 'ACCOUNT_LOCKED'
if (foundStates.includes('PASSKEY_VIDEO')) return 'PASSKEY_VIDEO'
if (foundStates.includes('PASSKEY_ERROR')) return 'PASSKEY_ERROR'
if (foundStates.includes('KMSI_PROMPT')) return 'KMSI_PROMPT'
if (foundStates.includes('PASSWORD_INPUT')) return 'PASSWORD_INPUT'
if (foundStates.includes('EMAIL_INPUT')) return 'EMAIL_INPUT'
if (foundStates.includes('SIGN_IN_ANOTHER_WAY')) return 'SIGN_IN_ANOTHER_WAY'
if (foundStates.includes('LOGIN_PASSWORDLESS')) return 'LOGIN_PASSWORDLESS'
if (foundStates.includes('2FA_TOTP')) return '2FA_TOTP'
const mainState = foundStates[0] as LoginState
return mainState
}
private async handleState(
state: LoginState,
page: Page,
email: string,
password: string,
totpSecret?: string
): Promise<boolean> {
switch (state) {
case 'ACCOUNT_LOCKED': {
const msg = 'This account has been locked! Remove from config and restart!'
this.bot.logger.error(this.bot.isMobile, 'CHECK-LOCKED', msg)
throw new Error(msg)
}
case 'ERROR_ALERT': {
const alertEl = page.locator('div[role="alert"]')
const errorMsg = await alertEl.innerText().catch(() => 'Unknown Error')
this.bot.logger.error(this.bot.isMobile, 'LOGIN', `Account error: ${errorMsg}`)
throw new Error(`Microsoft login error message: ${errorMsg}`)
}
case 'LOGGED_IN':
return true
case 'EMAIL_INPUT': {
this.bot.logger.info(this.bot.isMobile, 'LOGIN', 'Entering email')
await this.emailLogin.enterEmail(page, email)
await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {})
return true
}
case 'PASSWORD_INPUT': {
this.bot.logger.info(this.bot.isMobile, 'LOGIN', 'Entering password')
await this.emailLogin.enterPassword(page, password)
await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {})
return true
}
case 'GET_A_CODE': {
this.bot.logger.info(this.bot.isMobile, 'LOGIN', 'Attempting to bypass "Get code"')
// Select sign in other way
await this.bot.browser.utils.ghostClick(page, '[data-testid="viewFooter"] span[role="button"]')
await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {})
return true
}
case 'CHROMEWEBDATA_ERROR': {
this.bot.logger.warn(
this.bot.isMobile,
'LOGIN',
'chromewebdata error page detected, attempting to recover to Rewards home'
)
// Try go to Rewards dashboard
try {
await page
.goto(this.bot.config.baseURL, {
waitUntil: 'domcontentloaded',
timeout: 10000
})
.catch(() => {})
await this.bot.utils.wait(3000)
return true
} catch {
// If even that fails, fall back to login.live.com
this.bot.logger.warn(
this.bot.isMobile,
'LOGIN',
'Failed to navigate to baseURL from chromewebdata, retrying login.live.com'
)
await page
.goto('https://login.live.com/', {
waitUntil: 'domcontentloaded',
timeout: 10000
})
.catch(() => {})
await this.bot.utils.wait(3000)
return true
}
}
case '2FA_TOTP': {
this.bot.logger.info(this.bot.isMobile, 'LOGIN', 'TOTP 2FA required')
await this.totp2FALogin.handle(page, totpSecret)
return true
}
case 'SIGN_IN_ANOTHER_WAY': {
this.bot.logger.info(this.bot.isMobile, 'LOGIN', 'Selecting "Use my password"')
const passwordOption = '[data-testid="tile"]:has(svg path[d*="M11.78 10.22a.75.75"])'
await this.bot.browser.utils.ghostClick(page, passwordOption)
await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {})
return true
}
case 'KMSI_PROMPT': {
this.bot.logger.info(this.bot.isMobile, 'LOGIN', 'Accepting KMSI prompt')
await this.bot.browser.utils.ghostClick(page, this.primaryButtonSelector)
await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {})
return true
}
case 'PASSKEY_VIDEO':
case 'PASSKEY_ERROR': {
this.bot.logger.info(this.bot.isMobile, 'LOGIN', 'Skipping Passkey prompt')
await this.bot.browser.utils.ghostClick(page, this.secondaryButtonSelector)
await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {})
return true
}
case 'LOGIN_PASSWORDLESS': {
this.bot.logger.info(this.bot.isMobile, 'LOGIN', 'Handling passwordless authentication')
await this.passwordlessLogin.handle(page)
await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {})
return true
}
case 'UNKNOWN': {
const url = new URL(page.url())
this.bot.logger.warn(
this.bot.isMobile,
'LOGIN',
`Unknown state at host:${url.hostname} path:${url.pathname}. Waiting...`
)
return true
}
default:
return true
}
}
private async finalizeLogin(page: Page, email: string) {
this.bot.logger.info(this.bot.isMobile, 'LOGIN', 'Finalizing login')
await page.goto(this.bot.config.baseURL, { waitUntil: 'networkidle', timeout: 10000 }).catch(() => {})
const loginRewardsSuccess = new URL(page.url()).hostname === 'rewards.bing.com'
if (loginRewardsSuccess) {
this.bot.logger.info(this.bot.isMobile, 'LOGIN', 'Logged into Microsoft Rewards successfully')
} else {
this.bot.logger.warn(
this.bot.isMobile,
'LOGIN',
'Could not verify Rewards Dashboard. Assuming login valid anyway.'
)
}
await this.verifyBingSession(page)
await this.getRewardsSession(page)
const browser = page.context()
const cookies = await browser.cookies()
await saveSessionData(this.bot.config.sessionPath, cookies, email, this.bot.isMobile)
this.bot.logger.info(this.bot.isMobile, 'LOGIN', 'Login completed! Session saved!')
}
async verifyBingSession(page: Page) {
const url =
'https://www.bing.com/fd/auth/signin?action=interactive&provider=windows_live_id&return_url=https%3A%2F%2Fwww.bing.com%2F'
const loopMax = 5
this.bot.logger.info(this.bot.isMobile, 'LOGIN-BING', 'Verifying Bing session')
try {
await page.goto(url, { waitUntil: 'networkidle', timeout: 10000 }).catch(() => {})
for (let i = 0; i < loopMax; i++) {
if (page.isClosed()) break
// Rare error state
const state = await this.detectCurrentState(page)
if (state === 'PASSKEY_ERROR') {
this.bot.logger.debug(
this.bot.isMobile,
'LOGIN-BING',
'Verification landed on Passkey error state! Trying to dismiss.'
)
await this.bot.browser.utils.ghostClick(page, this.secondaryButtonSelector)
}
const u = new URL(page.url())
const atBingHome = u.hostname === 'www.bing.com' && u.pathname === '/'
if (atBingHome) {
await this.bot.browser.utils.tryDismissAllMessages(page).catch(() => {})
const signedIn = await page
.waitForSelector('#id_n', { timeout: 3000 })
.then(() => true)
.catch(() => false)
if (signedIn || this.bot.isMobile) {
this.bot.logger.info(this.bot.isMobile, 'LOGIN-BING', 'Bing session established')
return
}
}
await this.bot.utils.wait(1000)
}
this.bot.logger.warn(
this.bot.isMobile,
'LOGIN-BING',
'Could not confirm Bing session after retries; continuing'
)
} catch (error) {
this.bot.logger.warn(
this.bot.isMobile,
'LOGIN-BING',
`Bing verification error: ${error instanceof Error ? error.message : String(error)}`
)
}
}
private async getRewardsSession(page: Page) {
const loopMax = 5
this.bot.logger.info(this.bot.isMobile, 'GET-REQUEST-TOKEN', 'Fetching request token')
try {
await page
.goto(`${this.bot.config.baseURL}?_=${Date.now()}`, { waitUntil: 'networkidle', timeout: 10000 })
.catch(() => {})
for (let i = 0; i < loopMax; i++) {
if (page.isClosed()) break
this.bot.logger.debug(
this.bot.isMobile,
'GET-REWARD-SESSION',
`Loop ${i + 1}/${loopMax} | URL=${page.url()}`
)
const u = new URL(page.url())
const atRewardHome = u.hostname === 'rewards.bing.com' && u.pathname === '/'
if (atRewardHome) {
await this.bot.browser.utils.tryDismissAllMessages(page)
const html = await page.content()
const $ = await this.bot.browser.utils.loadInCheerio(html)
const token =
$('input[name="__RequestVerificationToken"]').attr('value') ??
$('meta[name="__RequestVerificationToken"]').attr('content') ??
null
if (token) {
this.bot.requestToken = token
this.bot.logger.info(this.bot.isMobile, 'GET-REQUEST-TOKEN', 'Request token has been set!')
this.bot.logger.debug(
this.bot.isMobile,
'GET-REWARD-SESSION',
`Token extracted: ${token.substring(0, 10)}...`
)
return
}
this.bot.logger.debug(this.bot.isMobile, 'GET-REWARD-SESSION', 'Token NOT found on page')
}
await this.bot.utils.wait(1000)
}
this.bot.logger.warn(
this.bot.isMobile,
'GET-REQUEST-TOKEN',
'No RequestVerificationToken found — some activities may not work'
)
} catch (error) {
throw this.bot.logger.error(
this.bot.isMobile,
'GET-REQUEST-TOKEN',
`Reward session error: ${error instanceof Error ? error.message : String(error)}`
)
}
}
async getAppAccessToken(page: Page, email: string) {
return await new MobileAccessLogin(this.bot, page).get(email)
}
}

View File

@@ -1,86 +0,0 @@
import type { Page } from 'patchright'
import type { MicrosoftRewardsBot } from '../../../index'
export class EmailLogin {
private submitButton = 'button[type="submit"]'
constructor(private bot: MicrosoftRewardsBot) {}
async enterEmail(page: Page, email: string): Promise<'ok' | 'error'> {
try {
const emailInputSelector = 'input[type="email"]'
const emailField = await page
.waitForSelector(emailInputSelector, { state: 'visible', timeout: 1000 })
.catch(() => {})
if (!emailField) {
this.bot.logger.warn(this.bot.isMobile, 'LOGIN-ENTER-EMAIL', 'Email field not found')
return 'error'
}
await this.bot.utils.wait(1000)
const prefilledEmail = await page
.waitForSelector('#userDisplayName', { state: 'visible', timeout: 1000 })
.catch(() => {})
if (!prefilledEmail) {
await page.fill(emailInputSelector, '').catch(() => {})
await this.bot.utils.wait(500)
await page.fill(emailInputSelector, email).catch(() => {})
await this.bot.utils.wait(1000)
} else {
this.bot.logger.info(this.bot.isMobile, 'LOGIN-ENTER-EMAIL', 'Email prefilled')
}
await page.waitForSelector(this.submitButton, { state: 'visible', timeout: 2000 }).catch(() => {})
await this.bot.browser.utils.ghostClick(page, this.submitButton)
this.bot.logger.info(this.bot.isMobile, 'LOGIN-ENTER-EMAIL', 'Email submitted')
return 'ok'
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'LOGIN-ENTER-EMAIL',
`An error occurred: ${error instanceof Error ? error.message : String(error)}`
)
return 'error'
}
}
async enterPassword(page: Page, password: string): Promise<'ok' | 'needs-2fa' | 'error'> {
try {
const passwordInputSelector = 'input[type="password"]'
const passwordField = await page
.waitForSelector(passwordInputSelector, { state: 'visible', timeout: 1000 })
.catch(() => {})
if (!passwordField) {
this.bot.logger.warn(this.bot.isMobile, 'LOGIN-ENTER-PASSWORD', 'Password field not found')
return 'error'
}
await this.bot.utils.wait(1000)
await page.fill(passwordInputSelector, '').catch(() => {})
await this.bot.utils.wait(500)
await page.fill(passwordInputSelector, password).catch(() => {})
await this.bot.utils.wait(1000)
const submitButton = await page
.waitForSelector(this.submitButton, { state: 'visible', timeout: 2000 })
.catch(() => null)
if (submitButton) {
await this.bot.browser.utils.ghostClick(page, this.submitButton)
this.bot.logger.info(this.bot.isMobile, 'LOGIN-ENTER-PASSWORD', 'Password submitted')
}
return 'ok'
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'LOGIN-ENTER-PASSWORD',
`An error occurred: ${error instanceof Error ? error.message : String(error)}`
)
return 'error'
}
}
}

View File

@@ -1,88 +0,0 @@
import type { Page } from 'patchright'
import { randomBytes } from 'crypto'
import { URLSearchParams } from 'url'
import type { AxiosRequestConfig } from 'axios'
import type { MicrosoftRewardsBot } from '../../../index'
export class MobileAccessLogin {
private clientId = '0000000040170455'
private authUrl = 'https://login.live.com/oauth20_authorize.srf'
private redirectUrl = 'https://login.live.com/oauth20_desktop.srf'
private tokenUrl = 'https://login.microsoftonline.com/consumers/oauth2/v2.0/token'
private scope = 'service::prod.rewardsplatform.microsoft.com::MBI_SSL'
private maxTimeout = 180_000 // 3min
constructor(
private bot: MicrosoftRewardsBot,
private page: Page
) {}
async get(email: string): Promise<string> {
try {
const authorizeUrl = new URL(this.authUrl)
authorizeUrl.searchParams.append('response_type', 'code')
authorizeUrl.searchParams.append('client_id', this.clientId)
authorizeUrl.searchParams.append('redirect_uri', this.redirectUrl)
authorizeUrl.searchParams.append('scope', this.scope)
authorizeUrl.searchParams.append('state', randomBytes(16).toString('hex'))
authorizeUrl.searchParams.append('access_type', 'offline_access')
authorizeUrl.searchParams.append('login_hint', email)
await this.bot.browser.utils.disableFido(this.page)
await this.page.goto(authorizeUrl.href).catch(() => {})
this.bot.logger.info(this.bot.isMobile, 'LOGIN-APP', 'Waiting for mobile OAuth code...')
const start = Date.now()
let code = ''
while (Date.now() - start < this.maxTimeout) {
const url = new URL(this.page.url())
if (url.hostname === 'login.live.com' && url.pathname === '/oauth20_desktop.srf') {
code = url.searchParams.get('code') || ''
if (code) break
}
await this.bot.utils.wait(1000)
}
if (!code) {
this.bot.logger.warn(this.bot.isMobile, 'LOGIN-APP', 'Timed out waiting for OAuth code')
return ''
}
const data = new URLSearchParams()
data.append('grant_type', 'authorization_code')
data.append('client_id', this.clientId)
data.append('code', code)
data.append('redirect_uri', this.redirectUrl)
const request: AxiosRequestConfig = {
url: this.tokenUrl,
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: data.toString()
}
const response = await this.bot.axios.request(request)
const token = (response?.data?.access_token as string) ?? ''
if (!token) {
this.bot.logger.warn(this.bot.isMobile, 'LOGIN-APP', 'No access_token in token response')
return ''
}
this.bot.logger.info(this.bot.isMobile, 'LOGIN-APP', 'Mobile access token received')
return token
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'LOGIN-APP',
`MobileAccess error: ${error instanceof Error ? error.message : String(error)}`
)
return ''
} finally {
await this.page.goto(this.bot.config.baseURL, { timeout: 10000 }).catch(() => {})
}
}
}

View File

@@ -1,110 +0,0 @@
import type { Page } from 'patchright'
import type { MicrosoftRewardsBot } from '../../../index'
export class PasswordlessLogin {
private readonly maxAttempts = 60
private readonly numberDisplaySelector = 'div[data-testid="displaySign"]'
private readonly approvalPath = '/ppsecure/post.srf'
constructor(private bot: MicrosoftRewardsBot) {}
private async getDisplayedNumber(page: Page): Promise<string | null> {
try {
const numberElement = await page
.waitForSelector(this.numberDisplaySelector, {
timeout: 5000
})
.catch(() => null)
if (numberElement) {
const number = await numberElement.textContent()
return number?.trim() || null
}
} catch (error) {
this.bot.logger.warn(this.bot.isMobile, 'LOGIN-PASSWORDLESS', 'Could not retrieve displayed number')
}
return null
}
private async waitForApproval(page: Page): Promise<boolean> {
try {
this.bot.logger.info(
this.bot.isMobile,
'LOGIN-PASSWORDLESS',
`Waiting for approval... (timeout after ${this.maxAttempts} seconds)`
)
for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {
const currentUrl = new URL(page.url())
if (currentUrl.pathname === this.approvalPath) {
this.bot.logger.info(this.bot.isMobile, 'LOGIN-PASSWORDLESS', 'Approval detected')
return true
}
// Every 5 seconds to show it's still waiting
if (attempt % 5 === 0) {
this.bot.logger.info(
this.bot.isMobile,
'LOGIN-PASSWORDLESS',
`Still waiting... (${attempt}/${this.maxAttempts} seconds elapsed)`
)
}
await this.bot.utils.wait(1000)
}
this.bot.logger.warn(
this.bot.isMobile,
'LOGIN-PASSWORDLESS',
`Approval timeout after ${this.maxAttempts} seconds!`
)
return false
} catch (error: any) {
this.bot.logger.error(
this.bot.isMobile,
'LOGIN-PASSWORDLESS',
`Approval failed, an error occurred: ${error instanceof Error ? error.message : String(error)}`
)
throw error
}
}
async handle(page: Page): Promise<void> {
try {
this.bot.logger.info(this.bot.isMobile, 'LOGIN-PASSWORDLESS', 'Passwordless authentication requested')
const displayedNumber = await this.getDisplayedNumber(page)
if (displayedNumber) {
this.bot.logger.info(
this.bot.isMobile,
'LOGIN-PASSWORDLESS',
`Please approve login and select number: ${displayedNumber}`
)
} else {
this.bot.logger.info(
this.bot.isMobile,
'LOGIN-PASSWORDLESS',
'Please approve login on your authenticator app'
)
}
const approved = await this.waitForApproval(page)
if (approved) {
this.bot.logger.info(this.bot.isMobile, 'LOGIN-PASSWORDLESS', 'Login approved successfully')
await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {})
} else {
this.bot.logger.error(this.bot.isMobile, 'LOGIN-PASSWORDLESS', 'Login approval failed or timed out')
throw new Error('Passwordless authentication timeout')
}
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'LOGIN-PASSWORDLESS',
`An error occurred: ${error instanceof Error ? error.message : String(error)}`
)
throw error
}
}
}

View File

@@ -1,163 +0,0 @@
import type { Page } from 'patchright'
import * as OTPAuth from 'otpauth'
import readline from 'readline'
import type { MicrosoftRewardsBot } from '../../../index'
export class TotpLogin {
private readonly textInputSelector =
'form[name="OneTimeCodeViewForm"] input[type="text"], input#floatingLabelInput5'
private readonly hiddenInputSelector = 'input[id="otc-confirmation-input"], input[name="otc"]'
private readonly submitButtonSelector = 'button[type="submit"]'
private readonly maxManualSeconds = 60
private readonly maxManualAttempts = 5
constructor(private bot: MicrosoftRewardsBot) {}
private generateTotpCode(secret: string): string {
return new OTPAuth.TOTP({ secret, digits: 6 }).generate()
}
private async promptManualCode(): Promise<string | null> {
return await new Promise(resolve => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
let resolved = false
const cleanup = (result: string | null) => {
if (resolved) return
resolved = true
clearTimeout(timer)
rl.close()
resolve(result)
}
const timer = setTimeout(() => cleanup(null), this.maxManualSeconds * 1000)
rl.question(`Enter the 6-digit TOTP code (waiting ${this.maxManualSeconds}s): `, answer => {
cleanup(answer.trim())
})
})
}
private async fillCode(page: Page, code: string): Promise<boolean> {
try {
const visibleInput = await page
.waitForSelector(this.textInputSelector, { state: 'visible', timeout: 500 })
.catch(() => null)
if (visibleInput) {
await visibleInput.fill(code)
this.bot.logger.info(this.bot.isMobile, 'LOGIN-TOTP', 'Filled visible TOTP text input')
return true
}
const hiddenInput = await page.$(this.hiddenInputSelector)
if (hiddenInput) {
await hiddenInput.fill(code)
this.bot.logger.info(this.bot.isMobile, 'LOGIN-TOTP', 'Filled hidden TOTP input')
return true
}
this.bot.logger.warn(this.bot.isMobile, 'LOGIN-TOTP', 'No TOTP input field found (visible or hidden)')
return false
} catch (error) {
this.bot.logger.warn(
this.bot.isMobile,
'LOGIN-TOTP',
`Failed to fill TOTP input: ${error instanceof Error ? error.message : String(error)}`
)
return false
}
}
async handle(page: Page, totpSecret?: string): Promise<void> {
try {
this.bot.logger.info(this.bot.isMobile, 'LOGIN-TOTP', 'TOTP 2FA authentication requested')
if (totpSecret) {
const code = this.generateTotpCode(totpSecret)
this.bot.logger.info(this.bot.isMobile, 'LOGIN-TOTP', 'Generated TOTP code from secret')
const filled = await this.fillCode(page, code)
if (!filled) {
this.bot.logger.error(this.bot.isMobile, 'LOGIN-TOTP', 'Unable to locate or fill TOTP input field')
throw new Error('TOTP input field not found')
}
await this.bot.utils.wait(500)
await this.bot.browser.utils.ghostClick(page, this.submitButtonSelector)
await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {})
this.bot.logger.info(this.bot.isMobile, 'LOGIN-TOTP', 'TOTP authentication completed successfully')
return
}
this.bot.logger.info(this.bot.isMobile, 'LOGIN-TOTP', 'No TOTP secret provided, awaiting manual input')
for (let attempt = 1; attempt <= this.maxManualAttempts; attempt++) {
const code = await this.promptManualCode()
if (!code || !/^\d{6}$/.test(code)) {
this.bot.logger.warn(
this.bot.isMobile,
'LOGIN-TOTP',
`Invalid or missing TOTP code (attempt ${attempt}/${this.maxManualAttempts})`
)
if (attempt === this.maxManualAttempts) {
throw new Error('Manual TOTP input failed or timed out')
}
this.bot.logger.info(
this.bot.isMobile,
'LOGIN-TOTP',
'Retrying manual TOTP input due to invalid code'
)
continue
}
const filled = await this.fillCode(page, code)
if (!filled) {
this.bot.logger.error(
this.bot.isMobile,
'LOGIN-TOTP',
`Unable to locate or fill TOTP input field (attempt ${attempt}/${this.maxManualAttempts})`
)
if (attempt === this.maxManualAttempts) {
throw new Error('TOTP input field not found')
}
this.bot.logger.info(
this.bot.isMobile,
'LOGIN-TOTP',
'Retrying manual TOTP input due to fill failure'
)
continue
}
await this.bot.utils.wait(500)
await this.bot.browser.utils.ghostClick(page, this.submitButtonSelector)
await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {})
this.bot.logger.info(this.bot.isMobile, 'LOGIN-TOTP', 'TOTP authentication completed successfully')
return
}
throw new Error(`Manual TOTP input failed after ${this.maxManualAttempts} attempts`)
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'LOGIN-TOTP',
`An error occurred: ${error instanceof Error ? error.message : String(error)}`
)
throw error
}
}
}

View File

@@ -1,71 +0,0 @@
{
"baseURL": "https://rewards.bing.com",
"sessionPath": "sessions",
"headless": false,
"runOnZeroPoints": false,
"clusters": 1,
"errorDiagnostics": true,
"saveFingerprint": {
"mobile": false,
"desktop": false
},
"workers": {
"doDailySet": true,
"doMorePromotions": true,
"doPunchCards": true,
"doAppPromotions": true,
"doDesktopSearch": true,
"doMobileSearch": true,
"doDailyCheckIn": true,
"doReadToEarn": true
},
"searchOnBingLocalQueries": false,
"globalTimeout": "30sec",
"searchSettings": {
"scrollRandomResults": false,
"clickRandomResults": false,
"parallelSearching": true,
"searchResultVisitTime": "10sec",
"searchDelay": {
"min": "30sec",
"max": "1min"
},
"readDelay": {
"min": "30sec",
"max": "1min"
}
},
"debugLogs": false,
"consoleLogFilter": {
"enabled": false,
"mode": "whitelist",
"levels": ["error", "warn"],
"keywords": ["starting account"],
"regexPatterns": []
},
"proxy": {
"queryEngine": true
},
"webhook": {
"discord": {
"enabled": false,
"url": ""
},
"ntfy": {
"enabled": false,
"url": "",
"topic": "",
"token": "",
"title": "Microsoft-Rewards-Script",
"tags": ["bot", "notify"],
"priority": 3
},
"webhookLogFilter": {
"enabled": false,
"mode": "whitelist",
"levels": ["error"],
"keywords": ["starting account", "select number", "collected"],
"regexPatterns": []
}
}
}

121
src/config.json Normal file
View File

@@ -0,0 +1,121 @@
{
"baseURL": "https://rewards.bing.com",
"sessionPath": "sessions",
"dryRun": false,
"browser": {
"headless": false,
"globalTimeout": "30s"
},
"fingerprinting": {
"saveFingerprint": {
"mobile": true,
"desktop": true
}
},
"execution": {
"parallel": false,
"runOnZeroPoints": false,
"clusters": 1
},
"jobState": {
"enabled": true,
"dir": ""
},
"workers": {
"doDailySet": true,
"doMorePromotions": true,
"doPunchCards": true,
"doDesktopSearch": true,
"doMobileSearch": true,
"doDailyCheckIn": true,
"doReadToEarn": true,
"bundleDailySetWithSearch": true
},
"search": {
"useLocalQueries": true,
"settings": {
"useGeoLocaleQueries": true,
"scrollRandomResults": true,
"clickRandomResults": true,
"retryMobileSearchAmount": 2,
"delay": {
"min": "2min",
"max": "5min"
}
}
},
"queryDiversity": {
"enabled": true,
"sources": [
"google-trends",
"reddit",
"local-fallback"
],
"maxQueriesPerSource": 10,
"cacheMinutes": 30
},
"humanization": {
"enabled": true,
"stopOnBan": true,
"immediateBanAlert": true,
"actionDelay": {
"min": 500,
"max": 2200
},
"gestureMoveProb": 0.65,
"gestureScrollProb": 0.4,
"allowedWindows": []
},
"vacation": {
"enabled": true,
"minDays": 2,
"maxDays": 4
},
"riskManagement": {
"enabled": true,
"autoAdjustDelays": true,
"stopOnCritical": false,
"banPrediction": true,
"riskThreshold": 75
},
"retryPolicy": {
"maxAttempts": 3,
"baseDelay": 1000,
"maxDelay": "30s",
"multiplier": 2,
"jitter": 0.2
},
"proxy": {
"proxyGoogleTrends": true,
"proxyBingTerms": true
},
"notifications": {
"webhook": {
"enabled": false,
"url": ""
},
"conclusionWebhook": {
"enabled": false,
"url": ""
},
"ntfy": {
"enabled": false,
"url": "",
"topic": "rewards",
"authToken": ""
}
},
"logging": {
"excludeFunc": [
"SEARCH-CLOSE-TABS",
"LOGIN-NO-PROMPT",
"FLOW"
],
"webhookExcludeFunc": [
"SEARCH-CLOSE-TABS",
"LOGIN-NO-PROMPT",
"FLOW"
],
"redactEmails": true
}
}

74
src/constants.ts Normal file
View File

@@ -0,0 +1,74 @@
/**
* Central constants file for the Microsoft Rewards Script
* Defines timeouts, retry limits, and other magic numbers used throughout the application
*/
export const TIMEOUTS = {
SHORT: 500,
MEDIUM: 1500,
MEDIUM_LONG: 2000,
LONG: 3000,
VERY_LONG: 5000,
EXTRA_LONG: 10000,
DASHBOARD_WAIT: 10000,
LOGIN_MAX: 180000, // 3 minutes
NETWORK_IDLE: 5000
} as const
export const RETRY_LIMITS = {
MAX_ITERATIONS: 5,
DASHBOARD_RELOAD: 2,
MOBILE_SEARCH: 3,
ABC_MAX: 15,
POLL_MAX: 15,
QUIZ_MAX: 15,
QUIZ_ANSWER_TIMEOUT: 10000,
GO_HOME_MAX: 5
} as const
export const DELAYS = {
ACTION_MIN: 1000,
ACTION_MAX: 3000,
SEARCH_DEFAULT_MIN: 2000,
SEARCH_DEFAULT_MAX: 5000,
BROWSER_CLOSE: 2000,
TYPING_DELAY: 20,
SEARCH_ON_BING_WAIT: 5000,
SEARCH_ON_BING_COMPLETE: 3000,
SEARCH_ON_BING_FOCUS: 200,
SEARCH_BAR_TIMEOUT: 15000,
QUIZ_ANSWER_WAIT: 2000,
THIS_OR_THAT_START: 2000
} as const
export const SELECTORS = {
MORE_ACTIVITIES: '#more-activities',
SUSPENDED_ACCOUNT: '#suspendedAccountHeader',
QUIZ_COMPLETE: '#quizCompleteContainer',
QUIZ_CREDITS: 'span.rqMCredits'
} as const
export const URLS = {
REWARDS_BASE: 'https://rewards.bing.com',
REWARDS_SIGNIN: 'https://rewards.bing.com/signin',
APP_USER_DATA: 'https://prod.rewardsplatform.microsoft.com/dapi/me?channel=SAAndroid&options=613'
} as const
export const DISCORD = {
MAX_EMBED_LENGTH: 1900,
RATE_LIMIT_DELAY: 500,
WEBHOOK_TIMEOUT: 10000,
DEBOUNCE_DELAY: 750,
COLOR_RED: 0xFF0000,
COLOR_CRIMSON: 0xDC143C,
COLOR_ORANGE: 0xFFA500,
COLOR_BLUE: 0x3498DB,
COLOR_GREEN: 0x00D26A,
AVATAR_URL: 'https://media.discordapp.net/attachments/1421163952972369931/1421929950377939125/Gc.png'
} as const
export const META = {
C: 'aHR0cHM6Ly9kaXNjb3JkLmdnL2tuMzY5NUt4MzI=',
R: 'aHR0cHM6Ly9naXRodWIuY29tL0xpZ2h0NjAtMS9NaWNyb3NvZnQtUmV3YXJkcy1SZXdp'
} as const

View File

@@ -1,7 +1,2 @@
# Set PATH so cron jobs can find node/npm
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# Set timezone for cron jobs
TZ=${TZ}
# Run automation according to CRON_SCHEDULE; redirect both stdout & stderr to Docker logs
${CRON_SCHEDULE} /bin/bash /usr/src/microsoft-rewards-script/scripts/docker/run_daily.sh >> /proc/1/fd/1 2>&1
${CRON_SCHEDULE} TZ=${TZ} /bin/bash /usr/src/microsoft-rewards-script/src/run_daily.sh >> /proc/1/fd/1 2>&1

View File

@@ -1,91 +1,164 @@
import type { MicrosoftRewardsBot } from '../index'
import type { Page } from 'patchright'
import { Page } from 'rebrowser-playwright'
// App
import { DailyCheckIn } from './activities/app/DailyCheckIn'
import { ReadToEarn } from './activities/app/ReadToEarn'
import { AppReward } from './activities/app/AppReward'
import { MicrosoftRewardsBot } from '../index'
// API
import { UrlReward } from './activities/api/UrlReward'
import { Quiz } from './activities/api/Quiz'
import { FindClippy } from './activities/api/FindClippy'
import { Search } from './activities/Search'
import { ABC } from './activities/ABC'
import { Poll } from './activities/Poll'
import { Quiz } from './activities/Quiz'
import { ThisOrThat } from './activities/ThisOrThat'
import { UrlReward } from './activities/UrlReward'
import { SearchOnBing } from './activities/SearchOnBing'
import { ReadToEarn } from './activities/ReadToEarn'
import { DailyCheckIn } from './activities/DailyCheckIn'
// Browser
import { SearchOnBing } from './activities/browser/SearchOnBing'
import { Search } from './activities/browser/Search'
import { DashboardData, MorePromotion, PromotionalItem } from '../interface/DashboardData'
import type { ActivityHandler } from '../interface/ActivityHandler'
type ActivityKind =
| { type: 'poll' }
| { type: 'abc' }
| { type: 'thisOrThat' }
| { type: 'quiz' }
| { type: 'urlReward' }
| { type: 'searchOnBing' }
| { type: 'unsupported' }
import type { BasePromotion, DashboardData, FindClippyPromotion } from '../interface/DashboardData'
import type { Promotion } from '../interface/AppDashBoardData'
export default class Activities {
private bot: MicrosoftRewardsBot
private handlers: ActivityHandler[] = []
constructor(bot: MicrosoftRewardsBot) {
this.bot = bot
}
// Browser Activities
doSearch = async (data: DashboardData, page: Page, isMobile: boolean): Promise<number> => {
// Register external/custom handlers (optional extension point)
registerHandler(handler: ActivityHandler) {
this.handlers.push(handler)
}
// Centralized dispatcher for activities from dashboard/punchcards
async run(page: Page, activity: MorePromotion | PromotionalItem): Promise<void> {
// First, try custom handlers (if any)
for (const h of this.handlers) {
try {
if (h.canHandle(activity)) {
await h.run(page, activity)
return
}
} catch (e) {
this.bot.log(this.bot.isMobile, 'ACTIVITY', `Custom handler ${(h.id || 'unknown')} failed: ${e instanceof Error ? e.message : e}`, 'error')
}
}
const kind = this.classifyActivity(activity)
try {
switch (kind.type) {
case 'poll':
await this.doPoll(page)
break
case 'abc':
await this.doABC(page)
break
case 'thisOrThat':
await this.doThisOrThat(page)
break
case 'quiz':
await this.doQuiz(page)
break
case 'searchOnBing':
await this.doSearchOnBing(page, activity)
break
case 'urlReward':
await this.doUrlReward(page)
break
default:
this.bot.log(this.bot.isMobile, 'ACTIVITY', `Skipped activity "${activity.title}" | Reason: Unsupported type: "${String((activity as { promotionType?: string }).promotionType)}"!`, 'warn')
break
}
} catch (e) {
this.bot.log(this.bot.isMobile, 'ACTIVITY', `Dispatcher error for "${activity.title}": ${e instanceof Error ? e.message : e}`, 'error')
}
}
public getTypeLabel(activity: MorePromotion | PromotionalItem): string {
const k = this.classifyActivity(activity)
switch (k.type) {
case 'poll': return 'Poll'
case 'abc': return 'ABC'
case 'thisOrThat': return 'ThisOrThat'
case 'quiz': return 'Quiz'
case 'searchOnBing': return 'SearchOnBing'
case 'urlReward': return 'UrlReward'
default: return 'Unsupported'
}
}
private classifyActivity(activity: MorePromotion | PromotionalItem): ActivityKind {
const type = (activity.promotionType || '').toLowerCase()
if (type === 'quiz') {
// Distinguish Poll/ABC/ThisOrThat vs general quiz using current heuristics
const max = activity.pointProgressMax
const url = (activity.destinationUrl || '').toLowerCase()
if (max === 10) {
if (url.includes('pollscenarioid')) return { type: 'poll' }
return { type: 'abc' }
}
if (max === 50) return { type: 'thisOrThat' }
return { type: 'quiz' }
}
if (type === 'urlreward') {
const name = (activity.name || '').toLowerCase()
if (name.includes('exploreonbing')) return { type: 'searchOnBing' }
return { type: 'urlReward' }
}
return { type: 'unsupported' }
}
doSearch = async (page: Page, data: DashboardData): Promise<void> => {
const search = new Search(this.bot)
return await search.doSearch(data, page, isMobile)
await search.doSearch(page, data)
}
doSearchOnBing = async (promotion: BasePromotion, page: Page): Promise<void> => {
const searchOnBing = new SearchOnBing(this.bot)
await searchOnBing.doSearchOnBing(promotion, page)
}
/*
doABC = async (page: Page): Promise<void> => {
const abc = new ABC(this.bot)
await abc.doABC(page)
}
*/
/*
doPoll = async (page: Page): Promise<void> => {
const poll = new Poll(this.bot)
await poll.doPoll(page)
}
*/
/*
doThisOrThat = async (page: Page): Promise<void> => {
const thisOrThat = new ThisOrThat(this.bot)
await thisOrThat.doThisOrThat(page)
}
*/
// API Activities
doUrlReward = async (promotion: BasePromotion): Promise<void> => {
const urlReward = new UrlReward(this.bot)
await urlReward.doUrlReward(promotion)
}
doQuiz = async (promotion: BasePromotion): Promise<void> => {
doQuiz = async (page: Page): Promise<void> => {
const quiz = new Quiz(this.bot)
await quiz.doQuiz(promotion)
await quiz.doQuiz(page)
}
doFindClippy = async (promotions: FindClippyPromotion): Promise<void> => {
const urlReward = new FindClippy(this.bot)
await urlReward.doFindClippy(promotions)
doUrlReward = async (page: Page): Promise<void> => {
const urlReward = new UrlReward(this.bot)
await urlReward.doUrlReward(page)
}
// App Activities
doAppReward = async (promotion: Promotion): Promise<void> => {
const urlReward = new AppReward(this.bot)
await urlReward.doAppReward(promotion)
doSearchOnBing = async (page: Page, activity: MorePromotion | PromotionalItem): Promise<void> => {
const searchOnBing = new SearchOnBing(this.bot)
await searchOnBing.doSearchOnBing(page, activity)
}
doReadToEarn = async (): Promise<void> => {
doReadToEarn = async (accessToken: string, data: DashboardData): Promise<void> => {
const readToEarn = new ReadToEarn(this.bot)
await readToEarn.doReadToEarn()
await readToEarn.doReadToEarn(accessToken, data)
}
doDailyCheckIn = async (): Promise<void> => {
doDailyCheckIn = async (accessToken: string, data: DashboardData): Promise<void> => {
const dailyCheckIn = new DailyCheckIn(this.bot)
await dailyCheckIn.doDailyCheckIn()
await dailyCheckIn.doDailyCheckIn(accessToken, data)
}
}
}

878
src/functions/Login.ts Normal file
View File

@@ -0,0 +1,878 @@
// Clean refactored Login implementation
// Public API preserved: login(), getMobileAccessToken()
import type { Page, Locator } from 'playwright'
import * as crypto from 'crypto'
import readline from 'readline'
import { AxiosRequestConfig } from 'axios'
import { generateTOTP } from '../util/Totp'
import { saveSessionData } from '../util/Load'
import { MicrosoftRewardsBot } from '../index'
import { OAuth } from '../interface/OAuth'
// -------------------------------
// Constants / Tunables
// -------------------------------
const SELECTORS = {
emailInput: 'input[type="email"]',
passwordInput: 'input[type="password"]',
submitBtn: 'button[type="submit"]',
passkeySecondary: 'button[data-testid="secondaryButton"]',
passkeyPrimary: 'button[data-testid="primaryButton"]',
passkeyTitle: '[data-testid="title"]',
kmsiVideo: '[data-testid="kmsiVideo"]',
biometricVideo: '[data-testid="biometricVideo"]'
} as const
const LOGIN_TARGET = { host: 'rewards.bing.com', path: '/' }
const DEFAULT_TIMEOUTS = {
loginMaxMs: (() => {
const val = Number(process.env.LOGIN_MAX_WAIT_MS || 180000)
if (isNaN(val) || val < 10000 || val > 600000) {
console.warn(`[Login] Invalid LOGIN_MAX_WAIT_MS: ${process.env.LOGIN_MAX_WAIT_MS}. Using default 180000ms`)
return 180000
}
return val
})(),
short: 500,
medium: 1500,
long: 3000
}
// Security pattern bundle
const SIGN_IN_BLOCK_PATTERNS: { re: RegExp; label: string }[] = [
{ re: /we can['`]?t sign you in/i, label: 'cant-sign-in' },
{ re: /incorrect account or password too many times/i, label: 'too-many-incorrect' },
{ re: /used an incorrect account or password too many times/i, label: 'too-many-incorrect-variant' },
{ re: /sign-in has been blocked/i, label: 'sign-in-blocked-phrase' },
{ re: /your account has been locked/i, label: 'account-locked' },
{ re: /your account or password is incorrect too many times/i, label: 'incorrect-too-many-times' }
]
interface SecurityIncident {
kind: string
account: string
details?: string[]
next?: string[]
docsUrl?: string
}
export class Login {
private bot: MicrosoftRewardsBot
private clientId = '0000000040170455'
private authBaseUrl = 'https://login.live.com/oauth20_authorize.srf'
private redirectUrl = 'https://login.live.com/oauth20_desktop.srf'
private tokenUrl = 'https://login.microsoftonline.com/consumers/oauth2/v2.0/token'
private scope = 'service::prod.rewardsplatform.microsoft.com::MBI_SSL'
private currentTotpSecret?: string
private compromisedInterval?: NodeJS.Timeout
private passkeyHandled = false
private noPromptIterations = 0
private lastNoPromptLog = 0
constructor(bot: MicrosoftRewardsBot) { this.bot = bot }
// --------------- Public API ---------------
async login(page: Page, email: string, password: string, totpSecret?: string) {
try {
// Clear any existing intervals from previous runs
if (this.compromisedInterval) {
clearInterval(this.compromisedInterval)
this.compromisedInterval = undefined
}
this.bot.log(this.bot.isMobile, 'LOGIN', 'Starting login process')
this.currentTotpSecret = (totpSecret && totpSecret.trim()) || undefined
await page.goto('https://www.bing.com/rewards/dashboard')
await this.disableFido(page)
await page.waitForLoadState('domcontentloaded').catch(() => { })
await this.bot.browser.utils.reloadBadPage(page)
await this.checkAccountLocked(page)
const already = await page.waitForSelector('html[data-role-name="RewardsPortal"]', { timeout: 8000 }).then(() => true).catch(() => false)
if (!already) {
await this.performLoginFlow(page, email, password)
} else {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Session already authenticated')
await this.checkAccountLocked(page)
}
await this.verifyBingContext(page)
await saveSessionData(this.bot.config.sessionPath, page.context(), email, this.bot.isMobile)
this.bot.log(this.bot.isMobile, 'LOGIN', 'Login complete (session saved)')
this.currentTotpSecret = undefined
} catch (e) {
throw this.bot.log(this.bot.isMobile, 'LOGIN', 'Failed login: ' + e, 'error')
}
}
async getMobileAccessToken(page: Page, email: string) {
// Reuse same FIDO disabling
await this.disableFido(page)
const url = new URL(this.authBaseUrl)
url.searchParams.set('response_type', 'code')
url.searchParams.set('client_id', this.clientId)
url.searchParams.set('redirect_uri', this.redirectUrl)
url.searchParams.set('scope', this.scope)
url.searchParams.set('state', crypto.randomBytes(16).toString('hex'))
url.searchParams.set('access_type', 'offline_access')
url.searchParams.set('login_hint', email)
await page.goto(url.href)
const start = Date.now()
this.bot.log(this.bot.isMobile, 'LOGIN-APP', 'Authorizing mobile scope...')
let code = ''
while (Date.now() - start < DEFAULT_TIMEOUTS.loginMaxMs) {
await this.handlePasskeyPrompts(page, 'oauth')
const u = new URL(page.url())
if (u.hostname === 'login.live.com' && u.pathname === '/oauth20_desktop.srf') {
code = u.searchParams.get('code') || ''
break
}
await this.bot.utils.wait(1000)
}
if (!code) throw this.bot.log(this.bot.isMobile, 'LOGIN-APP', 'OAuth code not received in time', 'error')
const form = new URLSearchParams()
form.append('grant_type', 'authorization_code')
form.append('client_id', this.clientId)
form.append('code', code)
form.append('redirect_uri', this.redirectUrl)
const req: AxiosRequestConfig = { url: this.tokenUrl, method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, data: form.toString() }
const resp = await this.bot.axios.request(req)
const data: OAuth = resp.data
this.bot.log(this.bot.isMobile, 'LOGIN-APP', `Authorized in ${Math.round((Date.now() - start) / 1000)}s`)
return data.access_token
}
// --------------- Main Flow ---------------
private async performLoginFlow(page: Page, email: string, password: string) {
await this.inputEmail(page, email)
await this.bot.utils.wait(1000)
await this.bot.browser.utils.reloadBadPage(page)
await this.bot.utils.wait(500)
await this.tryRecoveryMismatchCheck(page, email)
if (this.bot.compromisedModeActive && this.bot.compromisedReason === 'recovery-mismatch') {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Recovery mismatch detected stopping before password entry', 'warn')
return
}
// Try switching to password if a locale link is present (FR/EN)
await this.switchToPasswordLink(page)
await this.inputPasswordOr2FA(page, password)
if (this.bot.compromisedModeActive && this.bot.compromisedReason === 'sign-in-blocked') {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Blocked sign-in detected — halting.', 'warn')
return
}
await this.checkAccountLocked(page)
await this.awaitRewardsPortal(page)
}
// --------------- Input Steps ---------------
private async inputEmail(page: Page, email: string) {
const field = await page.waitForSelector(SELECTORS.emailInput, { timeout: 5000 }).catch(() => null)
if (!field) { this.bot.log(this.bot.isMobile, 'LOGIN', 'Email field not present', 'warn'); return }
const prefilled = await page.waitForSelector('#userDisplayName', { timeout: 1500 }).catch(() => null)
if (!prefilled) {
await page.fill(SELECTORS.emailInput, '')
await page.fill(SELECTORS.emailInput, email)
} else {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Email prefilled')
}
const next = await page.waitForSelector(SELECTORS.submitBtn, { timeout: 2000 }).catch(() => null)
if (next) { await next.click().catch(() => { }); this.bot.log(this.bot.isMobile, 'LOGIN', 'Submitted email') }
}
private async inputPasswordOr2FA(page: Page, password: string) {
// Some flows require switching to password first
const switchBtn = await page.waitForSelector('#idA_PWD_SwitchToPassword', { timeout: 1500 }).catch(() => null)
if (switchBtn) { await switchBtn.click().catch(() => { }); await this.bot.utils.wait(1000) }
// Rare flow: list of methods -> choose password
const passwordField = await page.waitForSelector(SELECTORS.passwordInput, { timeout: 4000 }).catch(() => null)
if (!passwordField) {
const blocked = await this.detectSignInBlocked(page)
if (blocked) return
// Log that we're handling the "Get a code to sign in" flow
this.bot.log(this.bot.isMobile, 'LOGIN', 'Attempting to handle "Get a code to sign in" flow')
// Try to handle "Other ways to sign in" flow first
const otherWaysHandled = await this.handleOtherWaysToSignIn(page)
if (otherWaysHandled) {
// Try to find password field again after clicking "Other ways"
const passwordFieldAfter = await page.waitForSelector(SELECTORS.passwordInput, { timeout: 3000 }).catch(() => null)
if (passwordFieldAfter) {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Password field found after "Other ways" flow')
await page.fill(SELECTORS.passwordInput, '')
await page.fill(SELECTORS.passwordInput, password)
const submit = await page.waitForSelector(SELECTORS.submitBtn, { timeout: 2000 }).catch(() => null)
if (submit) { await submit.click().catch(() => { }); this.bot.log(this.bot.isMobile, 'LOGIN', 'Password submitted') }
return
}
}
// If still no password field -> likely 2FA (approvals) first
this.bot.log(this.bot.isMobile, 'LOGIN', 'Password field absent — invoking 2FA handler', 'warn')
await this.handle2FA(page)
return
}
const blocked = await this.detectSignInBlocked(page)
if (blocked) return
await page.fill(SELECTORS.passwordInput, '')
await page.fill(SELECTORS.passwordInput, password)
const submit = await page.waitForSelector(SELECTORS.submitBtn, { timeout: 2000 }).catch(() => null)
if (submit) { await submit.click().catch(() => { }); this.bot.log(this.bot.isMobile, 'LOGIN', 'Password submitted') }
}
// --------------- Other Ways to Sign In Handling ---------------
private async handleOtherWaysToSignIn(page: Page): Promise<boolean> {
try {
// Look for "Other ways to sign in" - typically a span with role="button"
const otherWaysSelectors = [
'span[role="button"]:has-text("Other ways to sign in")',
'span:has-text("Other ways to sign in")',
'button:has-text("Other ways to sign in")',
'a:has-text("Other ways to sign in")',
'div[role="button"]:has-text("Other ways to sign in")'
]
let clicked = false
for (const selector of otherWaysSelectors) {
const element = await page.waitForSelector(selector, { timeout: 1000 }).catch(() => null)
if (element && await element.isVisible().catch(() => false)) {
await element.click().catch(() => { })
this.bot.log(this.bot.isMobile, 'LOGIN', 'Clicked "Other ways to sign in"')
await this.bot.utils.wait(2000) // Wait for options to appear
clicked = true
break
}
}
if (!clicked) {
return false
}
// Now look for "Use your password" option
const usePasswordSelectors = [
'span[role="button"]:has-text("Use your password")',
'span:has-text("Use your password")',
'button:has-text("Use your password")',
'button:has-text("Password")',
'a:has-text("Use your password")',
'div[role="button"]:has-text("Use your password")',
'div[role="button"]:has-text("Password")'
]
for (const selector of usePasswordSelectors) {
const element = await page.waitForSelector(selector, { timeout: 1500 }).catch(() => null)
if (element && await element.isVisible().catch(() => false)) {
await element.click().catch(() => { })
this.bot.log(this.bot.isMobile, 'LOGIN', 'Clicked "Use your password"')
await this.bot.utils.wait(2000) // Wait for password field to appear
return true
}
}
return false
} catch (error) {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Error in handleOtherWaysToSignIn: ' + error, 'warn')
return false
}
}
// --------------- 2FA Handling ---------------
private async handle2FA(page: Page) {
try {
// Dismiss any popups/dialogs before checking 2FA (Terms Update, etc.)
await this.bot.browser.utils.tryDismissAllMessages(page)
await this.bot.utils.wait(500)
if (this.currentTotpSecret) {
const totpSelector = await this.ensureTotpInput(page)
if (totpSelector) {
await this.submitTotpCode(page, totpSelector)
return
}
}
const number = await this.fetchAuthenticatorNumber(page)
if (number) { await this.approveAuthenticator(page, number); return }
await this.handleSMSOrTotp(page)
} catch (e) {
this.bot.log(this.bot.isMobile, 'LOGIN', '2FA error: ' + e, 'warn')
}
}
private async fetchAuthenticatorNumber(page: Page): Promise<string | null> {
try {
const el = await page.waitForSelector('#displaySign, div[data-testid="displaySign"]>span', { timeout: 2500 })
return (await el.textContent())?.trim() || null
} catch {
// Attempt resend loop in parallel mode
if (this.bot.config.parallel) {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Parallel mode: throttling authenticator push requests', 'log', 'yellow')
for (let attempts = 0; attempts < 6; attempts++) { // max 6 minutes retry window
const resend = await page.waitForSelector('button[aria-describedby="pushNotificationsTitle errorDescription"]', { timeout: 1500 }).catch(() => null)
if (!resend) break
await this.bot.utils.wait(60000)
await resend.click().catch(() => { })
}
}
await page.click('button[aria-describedby="confirmSendTitle"]').catch(() => { })
await this.bot.utils.wait(1500)
try {
const el = await page.waitForSelector('#displaySign, div[data-testid="displaySign"]>span', { timeout: 2000 })
return (await el.textContent())?.trim() || null
} catch { return null }
}
}
private async approveAuthenticator(page: Page, numberToPress: string) {
for (let cycle = 0; cycle < 6; cycle++) { // max ~6 refresh cycles
try {
this.bot.log(this.bot.isMobile, 'LOGIN', `Approve login in Authenticator (press ${numberToPress})`)
await page.waitForSelector('form[name="f1"]', { state: 'detached', timeout: 60000 })
this.bot.log(this.bot.isMobile, 'LOGIN', 'Authenticator approval successful')
return
} catch {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Authenticator code expired refreshing')
const retryBtn = await page.waitForSelector(SELECTORS.passkeyPrimary, { timeout: 3000 }).catch(() => null)
if (retryBtn) await retryBtn.click().catch(() => { })
const refreshed = await this.fetchAuthenticatorNumber(page)
if (!refreshed) { this.bot.log(this.bot.isMobile, 'LOGIN', 'Could not refresh authenticator code', 'warn'); return }
numberToPress = refreshed
}
}
this.bot.log(this.bot.isMobile, 'LOGIN', 'Authenticator approval loop exited (max cycles reached)', 'warn')
}
private async handleSMSOrTotp(page: Page) {
// TOTP auto entry (second chance if ensureTotpInput needed longer)
if (this.currentTotpSecret) {
try {
const totpSelector = await this.ensureTotpInput(page)
if (totpSelector) {
await this.submitTotpCode(page, totpSelector)
return
}
} catch {/* ignore */ }
}
// Manual prompt with periodic page check
this.bot.log(this.bot.isMobile, 'LOGIN', 'Waiting for user 2FA code (SMS / Email / App fallback)')
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
// Monitor page changes while waiting for user input
let userInput: string | null = null
let checkInterval: NodeJS.Timeout | null = null
try {
const inputPromise = new Promise<string>(res => {
rl.question('Enter 2FA code:\n', ans => {
if (checkInterval) clearInterval(checkInterval)
rl.close()
res(ans.trim())
})
})
// Check every 2 seconds if user manually progressed past the dialog
checkInterval = setInterval(async () => {
try {
await this.bot.browser.utils.tryDismissAllMessages(page)
// Check if we're no longer on 2FA page
const still2FA = await page.locator('input[name="otc"]').first().isVisible({ timeout: 500 }).catch(() => false)
if (!still2FA) {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Page changed during 2FA wait (user may have clicked Next)', 'warn')
if (checkInterval) clearInterval(checkInterval)
rl.close()
userInput = 'skip' // Signal to skip submission
}
} catch {/* ignore */ }
}, 2000)
const code = await inputPromise
if (code === 'skip' || userInput === 'skip') {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Skipping 2FA code submission (page progressed)')
return
}
await page.fill('input[name="otc"]', code)
await page.keyboard.press('Enter')
this.bot.log(this.bot.isMobile, 'LOGIN', '2FA code submitted')
} finally {
// Ensure cleanup happens even if errors occur
if (checkInterval) clearInterval(checkInterval)
try { rl.close() } catch {/* ignore */ }
}
}
private async ensureTotpInput(page: Page): Promise<string | null> {
const selector = await this.findFirstVisibleSelector(page, this.totpInputSelectors())
if (selector) return selector
const attempts = 4
for (let i = 0; i < attempts; i++) {
let acted = false
// Step 1: expose alternative verification options if hidden
if (!acted) {
acted = await this.clickFirstVisibleSelector(page, this.totpAltOptionSelectors())
if (acted) await this.bot.utils.wait(900)
}
// Step 2: choose authenticator code option if available
if (!acted) {
acted = await this.clickFirstVisibleSelector(page, this.totpChallengeSelectors())
if (acted) await this.bot.utils.wait(900)
}
const ready = await this.findFirstVisibleSelector(page, this.totpInputSelectors())
if (ready) return ready
if (!acted) break
}
return null
}
private async submitTotpCode(page: Page, selector: string) {
try {
const code = generateTOTP(this.currentTotpSecret!.trim())
const input = page.locator(selector).first()
if (!await input.isVisible().catch(() => false)) {
this.bot.log(this.bot.isMobile, 'LOGIN', 'TOTP input unexpectedly hidden', 'warn')
return
}
await input.fill('')
await input.fill(code)
// Use unified selector system
const submit = await this.findFirstVisibleLocator(page, Login.TOTP_SELECTORS.submit)
if (submit) {
await submit.click().catch(() => { })
} else {
await page.keyboard.press('Enter').catch(() => { })
}
this.bot.log(this.bot.isMobile, 'LOGIN', 'Submitted TOTP automatically')
} catch (error) {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Failed to submit TOTP automatically: ' + error, 'warn')
}
}
// Unified selector system - DRY principle
private static readonly TOTP_SELECTORS = {
input: [
'input[name="otc"]',
'#idTxtBx_SAOTCC_OTC',
'#idTxtBx_SAOTCS_OTC',
'input[data-testid="otcInput"]',
'input[autocomplete="one-time-code"]',
'input[type="tel"][name="otc"]'
],
altOptions: [
'#idA_SAOTCS_ProofPickerChange',
'#idA_SAOTCC_AlternateLogin',
'a:has-text("Use a different verification option")',
'a:has-text("Sign in another way")',
'a:has-text("I can\'t use my Microsoft Authenticator app right now")',
'button:has-text("Use a different verification option")',
'button:has-text("Sign in another way")'
],
challenge: [
'[data-value="PhoneAppOTP"]',
'[data-value="OneTimeCode"]',
'button:has-text("Use a verification code")',
'button:has-text("Enter code manually")',
'button:has-text("Enter a code from your authenticator app")',
'button:has-text("Use code from your authentication app")',
'button:has-text("Utiliser un code de vérification")',
'button:has-text("Utiliser un code de verification")',
'button:has-text("Entrer un code depuis votre application")',
'button:has-text("Entrez un code depuis votre application")',
'button:has-text("Entrez un code")',
'div[role="button"]:has-text("Use a verification code")',
'div[role="button"]:has-text("Enter a code")'
],
submit: [
'#idSubmit_SAOTCC_Continue',
'#idSubmit_SAOTCC_OTC',
'button[type="submit"]:has-text("Verify")',
'button[type="submit"]:has-text("Continuer")',
'button:has-text("Verify")',
'button:has-text("Continuer")',
'button:has-text("Submit")'
]
} as const
private totpInputSelectors(): readonly string[] { return Login.TOTP_SELECTORS.input }
private totpAltOptionSelectors(): readonly string[] { return Login.TOTP_SELECTORS.altOptions }
private totpChallengeSelectors(): readonly string[] { return Login.TOTP_SELECTORS.challenge }
// Generic selector finder - reduces duplication from 3 functions to 1
private async findFirstVisibleSelector(page: Page, selectors: readonly string[]): Promise<string | null> {
for (const sel of selectors) {
const loc = page.locator(sel).first()
if (await loc.isVisible().catch(() => false)) return sel
}
return null
}
private async clickFirstVisibleSelector(page: Page, selectors: readonly string[]): Promise<boolean> {
for (const sel of selectors) {
const loc = page.locator(sel).first()
if (await loc.isVisible().catch(() => false)) {
await loc.click().catch(() => { })
return true
}
}
return false
}
private async findFirstVisibleLocator(page: Page, selectors: readonly string[]): Promise<Locator | null> {
for (const sel of selectors) {
const loc = page.locator(sel).first()
if (await loc.isVisible().catch(() => false)) return loc
}
return null
}
private async waitForRewardsRoot(page: Page, timeoutMs: number): Promise<string | null> {
const selectors = [
'html[data-role-name="RewardsPortal"]',
'html[data-role-name*="RewardsPortal"]',
'body[data-role-name*="RewardsPortal"]',
'[data-role-name*="RewardsPortal"]',
'[data-bi-name="rewards-dashboard"]',
'main[data-bi-name="dashboard"]',
'#more-activities',
'#dashboard'
]
const start = Date.now()
while (Date.now() - start < timeoutMs) {
for (const sel of selectors) {
const loc = page.locator(sel).first()
if (await loc.isVisible().catch(() => false)) {
return sel
}
}
await this.bot.utils.wait(350)
}
return null
}
// --------------- Verification / State ---------------
private async awaitRewardsPortal(page: Page) {
const start = Date.now()
while (Date.now() - start < DEFAULT_TIMEOUTS.loginMaxMs) {
await this.handlePasskeyPrompts(page, 'main')
const u = new URL(page.url())
const isRewardsHost = u.hostname === LOGIN_TARGET.host
const isKnownPath = u.pathname === LOGIN_TARGET.path
|| u.pathname === '/dashboard'
|| u.pathname === '/rewardsapp/dashboard'
|| u.pathname.startsWith('/?')
if (isRewardsHost && isKnownPath) break
await this.bot.utils.wait(1000)
}
const portalSelector = await this.waitForRewardsRoot(page, 8000)
if (!portalSelector) {
try {
await this.bot.browser.func.goHome(page)
} catch {/* ignore fallback errors */ }
const fallbackSelector = await this.waitForRewardsRoot(page, 6000)
if (!fallbackSelector) {
throw this.bot.log(this.bot.isMobile, 'LOGIN', 'Portal root element missing after navigation', 'error')
}
this.bot.log(this.bot.isMobile, 'LOGIN', `Reached rewards portal via fallback (${fallbackSelector})`)
return
}
this.bot.log(this.bot.isMobile, 'LOGIN', `Reached rewards portal (${portalSelector})`)
}
private async verifyBingContext(page: Page) {
try {
this.bot.log(this.bot.isMobile, 'LOGIN-BING', 'Verifying Bing auth context')
await page.goto('https://www.bing.com/fd/auth/signin?action=interactive&provider=windows_live_id&return_url=https%3A%2F%2Fwww.bing.com%2F')
for (let i = 0; i < 5; i++) {
const u = new URL(page.url())
if (u.hostname === 'www.bing.com' && u.pathname === '/') {
await this.bot.browser.utils.tryDismissAllMessages(page)
const ok = await page.waitForSelector('#id_n', { timeout: 3000 }).then(() => true).catch(() => false)
if (ok || this.bot.isMobile) { this.bot.log(this.bot.isMobile, 'LOGIN-BING', 'Bing verification passed'); break }
}
await this.bot.utils.wait(1000)
}
} catch (e) {
this.bot.log(this.bot.isMobile, 'LOGIN-BING', 'Bing verification error: ' + e, 'warn')
}
}
private async checkAccountLocked(page: Page) {
const locked = await page.waitForSelector('#serviceAbuseLandingTitle', { timeout: 1200 }).then(() => true).catch(() => false)
if (locked) throw this.bot.log(this.bot.isMobile, 'CHECK-LOCKED', 'Account locked by Microsoft (serviceAbuseLandingTitle)', 'error')
}
// --------------- Passkey / Dialog Handling ---------------
private async handlePasskeyPrompts(page: Page, context: 'main' | 'oauth') {
let did = false
// Video heuristic
const biometric = await page.waitForSelector(SELECTORS.biometricVideo, { timeout: 500 }).catch(() => null)
if (biometric) {
const btn = await page.$(SELECTORS.passkeySecondary)
if (btn) { await btn.click().catch(() => { }); did = true; this.logPasskeyOnce('video heuristic') }
}
if (!did) {
const titleEl = await page.waitForSelector(SELECTORS.passkeyTitle, { timeout: 500 }).catch(() => null)
const secBtn = await page.waitForSelector(SELECTORS.passkeySecondary, { timeout: 500 }).catch(() => null)
const primBtn = await page.waitForSelector(SELECTORS.passkeyPrimary, { timeout: 500 }).catch(() => null)
const title = (titleEl ? (await titleEl.textContent()) : '')?.trim() || ''
const looksLike = /sign in faster|passkey|fingerprint|face|pin/i.test(title)
if (looksLike && secBtn) { await secBtn.click().catch(() => { }); did = true; this.logPasskeyOnce('title heuristic ' + title) }
else if (!did && secBtn && primBtn) {
const text = (await secBtn.textContent() || '').trim()
if (/skip for now/i.test(text)) { await secBtn.click().catch(() => { }); did = true; this.logPasskeyOnce('secondary button text') }
}
if (!did) {
const textBtn = await page.locator('xpath=//button[contains(normalize-space(.),"Skip for now")]').first()
if (await textBtn.isVisible().catch(() => false)) { await textBtn.click().catch(() => { }); did = true; this.logPasskeyOnce('text fallback') }
}
if (!did) {
const close = await page.$('#close-button')
if (close) { await close.click().catch(() => { }); did = true; this.logPasskeyOnce('close button') }
}
}
// KMSI prompt
const kmsi = await page.waitForSelector(SELECTORS.kmsiVideo, { timeout: 400 }).catch(() => null)
if (kmsi) {
const yes = await page.$(SELECTORS.passkeyPrimary)
if (yes) { await yes.click().catch(() => { }); did = true; this.bot.log(this.bot.isMobile, 'LOGIN-KMSI', 'Accepted KMSI prompt') }
}
if (!did && context === 'main') {
this.noPromptIterations++
const now = Date.now()
if (this.noPromptIterations === 1 || now - this.lastNoPromptLog > 10000) {
this.lastNoPromptLog = now
this.bot.log(this.bot.isMobile, 'LOGIN-NO-PROMPT', `No dialogs (x${this.noPromptIterations})`)
if (this.noPromptIterations > 50) this.noPromptIterations = 0
}
} else if (did) {
this.noPromptIterations = 0
}
}
private logPasskeyOnce(reason: string) {
if (this.passkeyHandled) return
this.passkeyHandled = true
this.bot.log(this.bot.isMobile, 'LOGIN-PASSKEY', `Dismissed passkey prompt (${reason})`)
}
// --------------- Security Detection ---------------
private async detectSignInBlocked(page: Page): Promise<boolean> {
if (this.bot.compromisedModeActive && this.bot.compromisedReason === 'sign-in-blocked') return true
try {
let text = ''
for (const sel of ['[data-testid="title"]', 'h1', 'div[role="heading"]', 'div.text-title']) {
const el = await page.waitForSelector(sel, { timeout: 600 }).catch(() => null)
if (el) {
const t = (await el.textContent() || '').trim()
if (t && t.length < 300) text += ' ' + t
}
}
const lower = text.toLowerCase()
let matched: string | null = null
for (const p of SIGN_IN_BLOCK_PATTERNS) { if (p.re.test(lower)) { matched = p.label; break } }
if (!matched) return false
const email = this.bot.currentAccountEmail || 'unknown'
const incident: SecurityIncident = {
kind: 'We can\'t sign you in (blocked)',
account: email,
details: [matched ? `Pattern: ${matched}` : 'Pattern: unknown'],
next: ['Manual recovery required before continuing']
}
await this.sendIncidentAlert(incident, 'warn')
this.bot.compromisedModeActive = true
this.bot.compromisedReason = 'sign-in-blocked'
this.startCompromisedInterval()
await this.bot.engageGlobalStandby('sign-in-blocked', email).catch(() => { })
return true
} catch { return false }
}
private async tryRecoveryMismatchCheck(page: Page, email: string) { try { await this.detectAndHandleRecoveryMismatch(page, email) } catch {/* ignore */ } }
private async detectAndHandleRecoveryMismatch(page: Page, email: string) {
try {
const recoveryEmail: string | undefined = this.bot.currentAccountRecoveryEmail
if (!recoveryEmail || !/@/.test(recoveryEmail)) return
const accountEmail = email
const parseRef = (val: string) => { const [l, d] = val.split('@'); return { local: l || '', domain: (d || '').toLowerCase(), prefix2: (l || '').slice(0, 2).toLowerCase() } }
const refs = [parseRef(recoveryEmail), parseRef(accountEmail)].filter(r => r.domain && r.prefix2)
if (refs.length === 0) return
const candidates: string[] = []
// Direct selectors (Microsoft variants + French spans)
const sel = '[data-testid="recoveryEmailHint"], #recoveryEmail, [id*="ProofEmail"], [id*="EmailProof"], [data-testid*="Email"], span:has(span.fui-Text)'
const el = await page.waitForSelector(sel, { timeout: 1500 }).catch(() => null)
if (el) { const t = (await el.textContent() || '').trim(); if (t) candidates.push(t) }
// List items
const li = page.locator('[role="listitem"], li')
const liCount = await li.count().catch(() => 0)
for (let i = 0; i < liCount && i < 12; i++) { const t = (await li.nth(i).textContent().catch(() => ''))?.trim() || ''; if (t && /@/.test(t)) candidates.push(t) }
// XPath generic masked patterns
const xp = page.locator('xpath=//*[contains(normalize-space(.), "@") and (contains(normalize-space(.), "*") or contains(normalize-space(.), "•"))]')
const xpCount = await xp.count().catch(() => 0)
for (let i = 0; i < xpCount && i < 12; i++) { const t = (await xp.nth(i).textContent().catch(() => ''))?.trim() || ''; if (t && t.length < 300) candidates.push(t) }
// Normalize
const seen = new Set<string>()
const norm = (s: string) => s.replace(/\s+/g, ' ').trim()
const uniq = candidates.map(norm).filter(t => t && !seen.has(t) && seen.add(t))
// Masked filter
let masked = uniq.filter(t => /@/.test(t) && /[*•]/.test(t))
if (masked.length === 0) {
// Fallback full HTML scan
try {
const html = await page.content()
const generic = /[A-Za-z0-9]{1,4}[*•]{2,}[A-Za-z0-9*•._-]*@[A-Za-z0-9.-]+/g
const frPhrase = /Nous\s+enverrons\s+un\s+code\s+à\s+([^<@]*[A-Za-z0-9]{1,4}[*•]{2,}[A-Za-z0-9*•._-]*@[A-Za-z0-9.-]+)[^.]{0,120}?Pour\s+vérifier/gi
const found = new Set<string>()
let m: RegExpExecArray | null
while ((m = generic.exec(html)) !== null) found.add(m[0])
while ((m = frPhrase.exec(html)) !== null) { const raw = m[1]?.replace(/<[^>]+>/g, '').trim(); if (raw) found.add(raw) }
if (found.size > 0) masked = Array.from(found)
} catch {/* ignore */ }
}
if (masked.length === 0) return
// Prefer one mentioning email/adresse
const preferred = masked.find(t => /email|courriel|adresse|mail/i.test(t)) || masked[0]!
// Extract the masked email: Microsoft sometimes shows only first 1 char (k*****@domain) or 2 chars (ko*****@domain).
// We ONLY compare (1 or 2) leading visible alphanumeric chars + full domain (case-insensitive).
// This avoids false positives when the displayed mask hides the 2nd char.
const maskRegex = /([a-zA-Z0-9]{1,2})[a-zA-Z0-9*•._-]*@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/
const m = maskRegex.exec(preferred)
// Fallback: try to salvage with looser pattern if first regex fails
const loose = !m ? /([a-zA-Z0-9])[*•][a-zA-Z0-9*•._-]*@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/.exec(preferred) : null
const use = m || loose
const extracted = use ? use[0] : preferred
const extractedLower = extracted.toLowerCase()
let observedPrefix = ((use && use[1]) ? use[1] : '').toLowerCase()
let observedDomain = ((use && use[2]) ? use[2] : '').toLowerCase()
if (!observedDomain && extractedLower.includes('@')) {
const parts = extractedLower.split('@')
observedDomain = parts[1] || ''
}
if (!observedPrefix && extractedLower.includes('@')) {
const parts = extractedLower.split('@')
observedPrefix = (parts[0] || '').replace(/[^a-z0-9]/gi, '').slice(0, 2)
}
// Determine if any reference (recoveryEmail or accountEmail) matches observed mask logic
const matchRef = refs.find(r => {
if (r.domain !== observedDomain) return false
// If only one char visible, only enforce first char; if two, enforce both.
if (observedPrefix.length === 1) {
return r.prefix2.startsWith(observedPrefix)
}
return r.prefix2 === observedPrefix
})
if (!matchRef) {
const incident: SecurityIncident = {
kind: 'Recovery email mismatch',
account: email,
details: [
`MaskedShown: ${preferred}`,
`Extracted: ${extracted}`,
`Observed => ${observedPrefix || '??'}**@${observedDomain || '??'}`,
`Expected => ${refs.map(r => `${r.prefix2}**@${r.domain}`).join(' OR ')}`
],
next: [
'Automation halted globally (standby engaged).',
'Verify account security & recovery email in Microsoft settings.',
'Update accounts.json if the change was legitimate before restart.'
]
}
await this.sendIncidentAlert(incident, 'critical')
this.bot.compromisedModeActive = true
this.bot.compromisedReason = 'recovery-mismatch'
this.startCompromisedInterval()
await this.bot.engageGlobalStandby('recovery-mismatch', email).catch(() => { })
} else {
const mode = observedPrefix.length === 1 ? 'lenient' : 'strict'
this.bot.log(this.bot.isMobile, 'LOGIN-RECOVERY', `Recovery OK (${mode}): ${extracted} matches ${matchRef.prefix2}**@${matchRef.domain}`)
}
} catch {/* non-fatal */ }
}
private async switchToPasswordLink(page: Page) {
try {
const link = await page.locator('xpath=//span[@role="button" and (contains(translate(normalize-space(.),"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz"),"use your password") or contains(translate(normalize-space(.),"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz"),"utilisez votre mot de passe"))]').first()
if (await link.isVisible().catch(() => false)) {
await link.click().catch(() => { })
await this.bot.utils.wait(800)
this.bot.log(this.bot.isMobile, 'LOGIN', 'Clicked "Use your password" link')
}
} catch {/* ignore */ }
}
// --------------- Incident Helpers ---------------
private async sendIncidentAlert(incident: SecurityIncident, severity: 'warn' | 'critical' = 'warn') {
const lines = [`[Incident] ${incident.kind}`, `Account: ${incident.account}`]
if (incident.details?.length) lines.push(`Details: ${incident.details.join(' | ')}`)
if (incident.next?.length) lines.push(`Next: ${incident.next.join(' -> ')}`)
if (incident.docsUrl) lines.push(`Docs: ${incident.docsUrl}`)
const level: 'warn' | 'error' = severity === 'critical' ? 'error' : 'warn'
this.bot.log(this.bot.isMobile, 'SECURITY', lines.join(' | '), level)
try {
const { ConclusionWebhook } = await import('../util/ConclusionWebhook')
const fields = [
{ name: 'Account', value: incident.account },
...(incident.details?.length ? [{ name: 'Details', value: incident.details.join('\n') }] : []),
...(incident.next?.length ? [{ name: 'Next steps', value: incident.next.join('\n') }] : []),
...(incident.docsUrl ? [{ name: 'Docs', value: incident.docsUrl }] : [])
]
await ConclusionWebhook(
this.bot.config,
`🔐 ${incident.kind}`,
'_Security check',
fields,
severity === 'critical' ? 0xFF0000 : 0xFFAA00
)
} catch {/* ignore */ }
}
private startCompromisedInterval() {
if (this.compromisedInterval) clearInterval(this.compromisedInterval)
this.compromisedInterval = setInterval(() => {
try { this.bot.log(this.bot.isMobile, 'SECURITY', 'Account in security standby. Review before proceeding.', 'warn') } catch {/* ignore */ }
}, 5 * 60 * 1000)
}
// --------------- Infrastructure ---------------
private async disableFido(page: Page) {
await page.route('**/GetCredentialType.srf*', route => {
try {
const body = JSON.parse(route.request().postData() || '{}')
body.isFidoSupported = false
route.continue({ postData: JSON.stringify(body) })
} catch { route.continue() }
}).catch(() => { })
}
}

View File

@@ -1,191 +0,0 @@
import type { AxiosRequestConfig } from 'axios'
import type {
BingSuggestionResponse,
BingTrendingTopicsResponse,
GoogleSearch,
GoogleTrendsResponse
} from '../interface/Search'
import type { MicrosoftRewardsBot } from '../index'
export class QueryCore {
constructor(private bot: MicrosoftRewardsBot) {}
async getGoogleTrends(geoLocale: string): Promise<string[]> {
const queryTerms: GoogleSearch[] = []
this.bot.logger.info(
this.bot.isMobile,
'SEARCH-GOOGLE-TRENDS',
`Generating search queries, can take a while! | GeoLocale: ${geoLocale}`
)
try {
const request: AxiosRequestConfig = {
url: 'https://trends.google.com/_/TrendsUi/data/batchexecute',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
data: `f.req=[[[i0OFE,"[null, null, \\"${geoLocale.toUpperCase()}\\", 0, null, 48]"]]]`
}
const response = await this.bot.axios.request(request, this.bot.config.proxy.queryEngine)
const rawData = response.data
const trendsData = this.extractJsonFromResponse(rawData)
if (!trendsData) {
throw this.bot.logger.error(
this.bot.isMobile,
'SEARCH-GOOGLE-TRENDS',
'Failed to parse Google Trends response'
)
}
const mappedTrendsData = trendsData.map(query => [query[0], query[9]!.slice(1)])
if (mappedTrendsData.length < 90) {
this.bot.logger.warn(
this.bot.isMobile,
'SEARCH-GOOGLE-TRENDS',
'Insufficient search queries, falling back to US'
)
return this.getGoogleTrends('US')
}
for (const [topic, relatedQueries] of mappedTrendsData) {
queryTerms.push({
topic: topic as string,
related: relatedQueries as string[]
})
}
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'SEARCH-GOOGLE-TRENDS',
`An error occurred: ${error instanceof Error ? error.message : String(error)}`
)
}
const queries = queryTerms.flatMap(x => [x.topic, ...x.related])
return queries
}
private extractJsonFromResponse(text: string): GoogleTrendsResponse[1] | null {
const lines = text.split('\n')
for (const line of lines) {
const trimmed = line.trim()
if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
try {
return JSON.parse(JSON.parse(trimmed)[0][2])[1]
} catch {
continue
}
}
}
return null
}
async getBingSuggestions(query: string = '', langCode: string = 'en'): Promise<string[]> {
this.bot.logger.info(
this.bot.isMobile,
'SEARCH-BING-SUGGESTIONS',
`Generating bing suggestions! | LangCode: ${langCode}`
)
try {
const request: AxiosRequestConfig = {
url: `https://www.bingapis.com/api/v7/suggestions?q=${encodeURIComponent(query)}&appid=6D0A9B8C5100E9ECC7E11A104ADD76C10219804B&cc=xl&setlang=${langCode}`,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
}
const response = await this.bot.axios.request(request, this.bot.config.proxy.queryEngine)
const rawData: BingSuggestionResponse = response.data
const searchSuggestions = rawData.suggestionGroups[0]?.searchSuggestions
if (!searchSuggestions?.length) {
this.bot.logger.warn(this.bot.isMobile, 'SEARCH-BING-SUGGESTIONS', 'API returned no results')
return []
}
return searchSuggestions.map(x => x.query)
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'SEARCH-GOOGLE-TRENDS',
`An error occurred: ${error instanceof Error ? error.message : String(error)}`
)
}
return []
}
async getBingRelatedTerms(term: string): Promise<string[]> {
try {
const request = {
url: `https://api.bing.com/osjson.aspx?query=${term}`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
const response = await this.bot.axios.request(request, this.bot.config.proxy.queryEngine)
const rawData = response.data
const relatedTerms = rawData[1]
if (!relatedTerms?.length) {
this.bot.logger.warn(this.bot.isMobile, 'SEARCH-BING-RELATED', 'API returned no results')
return []
}
return relatedTerms
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'SEARCH-BING-RELATED',
`An error occurred: ${error instanceof Error ? error.message : String(error)}`
)
}
return []
}
async getBingTendingTopics(langCode: string = 'en'): Promise<string[]> {
try {
const request = {
url: `https://www.bing.com/api/v7/news/trendingtopics?appid=91B36E34F9D1B900E54E85A77CF11FB3BE5279E6&cc=xl&setlang=${langCode}`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
const response = await this.bot.axios.request(request, this.bot.config.proxy.queryEngine)
const rawData: BingTrendingTopicsResponse = response.data
const trendingTopics = rawData.value
if (!trendingTopics?.length) {
this.bot.logger.warn(this.bot.isMobile, 'SEARCH-BING-TRENDING', 'API returned no results')
return []
}
const queries = trendingTopics.map(x => x.query?.text?.trim() || x.name.trim())
return queries
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'SEARCH-BING-TRENDING',
`An error occurred: ${error instanceof Error ? error.message : String(error)}`
)
}
return []
}
}

View File

@@ -1,618 +0,0 @@
import type { BrowserContext } from 'patchright'
import type { BrowserFingerprintWithHeaders } from 'fingerprint-generator'
import { MicrosoftRewardsBot, executionContext } from '../index'
import type { DashboardData } from '../interface/DashboardData'
import type { Account } from '../interface/Account'
interface BrowserSession {
context: BrowserContext
fingerprint: BrowserFingerprintWithHeaders
}
interface MissingSearchPoints {
mobilePoints: number
desktopPoints: number
}
interface SearchResults {
mobilePoints: number
desktopPoints: number
}
export class SearchManager {
constructor(private bot: MicrosoftRewardsBot) {}
async doSearches(
data: DashboardData,
missingSearchPoints: MissingSearchPoints,
mobileSession: BrowserSession,
account: Account,
accountEmail: string
): Promise<SearchResults> {
this.bot.logger.debug(
'main',
'SEARCH-MANAGER',
`Start | account=${accountEmail} | mobileMissing=${missingSearchPoints.mobilePoints} | desktopMissing=${missingSearchPoints.desktopPoints}`
)
const doMobile = this.bot.config.workers.doMobileSearch && missingSearchPoints.mobilePoints > 0
const doDesktop = this.bot.config.workers.doDesktopSearch && missingSearchPoints.desktopPoints > 0
const mobileStatus = this.bot.config.workers.doMobileSearch
? missingSearchPoints.mobilePoints > 0
? 'run'
: 'skip-no-points'
: 'skip-disabled'
const desktopStatus = this.bot.config.workers.doDesktopSearch
? missingSearchPoints.desktopPoints > 0
? 'run'
: 'skip-no-points'
: 'skip-disabled'
this.bot.logger.info(
'main',
'SEARCH-MANAGER',
`Mobile: ${mobileStatus} (enabled=${this.bot.config.workers.doMobileSearch}, missing=${missingSearchPoints.mobilePoints})`
)
this.bot.logger.info(
'main',
'SEARCH-MANAGER',
`Desktop: ${desktopStatus} (enabled=${this.bot.config.workers.doDesktopSearch}, missing=${missingSearchPoints.desktopPoints})`
)
if (!doMobile && !doDesktop) {
const bothWorkersEnabled = this.bot.config.workers.doMobileSearch && this.bot.config.workers.doDesktopSearch
const bothNoPoints = missingSearchPoints.mobilePoints <= 0 && missingSearchPoints.desktopPoints <= 0
if (bothWorkersEnabled && bothNoPoints) {
this.bot.logger.info(
'main',
'SEARCH-MANAGER',
'All searches skipped: no mobile or desktop points left.'
)
} else {
this.bot.logger.info('main', 'SEARCH-MANAGER', 'No searches scheduled (disabled or no points).')
}
this.bot.logger.info('main', 'SEARCH-MANAGER', 'Closing mobile session')
try {
await executionContext.run({ isMobile: true, accountEmail }, async () => {
await this.bot.browser.func.closeBrowser(mobileSession.context, accountEmail)
})
this.bot.logger.info('main', 'SEARCH-MANAGER', 'Mobile session closed')
} catch (error) {
this.bot.logger.warn(
'main',
'SEARCH-MANAGER',
`Failed to close mobile session: ${error instanceof Error ? error.message : String(error)}`
)
if (error instanceof Error && error.stack) {
this.bot.logger.debug('main', 'SEARCH-MANAGER', `Mobile close stack: ${error.stack}`)
}
}
return { mobilePoints: 0, desktopPoints: 0 }
}
const useParallel = this.bot.config.searchSettings.parallelSearching
this.bot.logger.info('main', 'SEARCH-MANAGER', `Mode: ${useParallel ? 'parallel' : 'sequential'}`)
this.bot.logger.debug('main', 'SEARCH-MANAGER', `parallelSearching=${useParallel} | account=${accountEmail}`)
if (useParallel) {
return await this.doParallelSearches(
data,
missingSearchPoints,
mobileSession,
account,
accountEmail,
executionContext
)
} else {
return await this.doSequentialSearches(
data,
missingSearchPoints,
mobileSession,
account,
accountEmail,
executionContext
)
}
}
private async doParallelSearches(
data: DashboardData,
missingSearchPoints: MissingSearchPoints,
mobileSession: BrowserSession,
account: Account,
accountEmail: string,
executionContext: any
): Promise<SearchResults> {
this.bot.logger.info('main', 'SEARCH-MANAGER', 'Parallel start')
this.bot.logger.debug(
'main',
'SEARCH-MANAGER',
`Parallel config | account=${accountEmail} | mobileMissing=${missingSearchPoints.mobilePoints} | desktopMissing=${missingSearchPoints.desktopPoints}`
)
const shouldDoMobile = this.bot.config.workers.doMobileSearch && missingSearchPoints.mobilePoints > 0
const shouldDoDesktop = this.bot.config.workers.doDesktopSearch && missingSearchPoints.desktopPoints > 0
this.bot.logger.debug(
'main',
'SEARCH-MANAGER',
`Parallel flags | mobile=${shouldDoMobile} | desktop=${shouldDoDesktop}`
)
let desktopSession: BrowserSession | null = null
let mobileContextClosed = false
try {
const promises: Promise<number>[] = []
const searchTypes: string[] = []
if (shouldDoMobile) {
this.bot.logger.debug(
'main',
'SEARCH-MANAGER',
`Schedule mobile | target=${missingSearchPoints.mobilePoints}`
)
searchTypes.push('Mobile')
promises.push(
this.doMobileSearch(data, missingSearchPoints, mobileSession, accountEmail, executionContext).then(
points => {
mobileContextClosed = true
this.bot.logger.info('main', 'SEARCH-MANAGER', `Mobile done | earned=${points}`)
return points
}
)
)
} else {
const reason = !this.bot.config.workers.doMobileSearch ? 'disabled' : 'no-points'
this.bot.logger.info('main', 'SEARCH-MANAGER', `Skip mobile (${reason}); closing mobile session`)
await this.bot.browser.func.closeBrowser(mobileSession.context, accountEmail)
mobileContextClosed = true
this.bot.logger.info('main', 'SEARCH-MANAGER', 'Mobile session closed (no mobile search)')
}
if (shouldDoDesktop) {
this.bot.logger.info('main', 'SEARCH-MANAGER', 'Desktop login start')
this.bot.logger.debug(
'main',
'SEARCH-MANAGER',
`Desktop login | account=${accountEmail} | proxy=${account.proxy ?? 'none'}`
)
desktopSession = await executionContext.run({ isMobile: false, accountEmail }, async () =>
this.createDesktopSession(account, accountEmail)
)
this.bot.logger.info('main', 'SEARCH-MANAGER', 'Desktop login done')
} else {
const reason = !this.bot.config.workers.doDesktopSearch ? 'disabled' : 'no-points'
this.bot.logger.info('main', 'SEARCH-MANAGER', `Skip desktop login (${reason})`)
}
if (shouldDoDesktop && desktopSession) {
this.bot.logger.debug(
'main',
'SEARCH-MANAGER',
`Schedule desktop | target=${missingSearchPoints.desktopPoints}`
)
searchTypes.push('Desktop')
promises.push(
this.doDesktopSearch(
data,
missingSearchPoints,
desktopSession,
accountEmail,
executionContext
).then(points => {
this.bot.logger.info('main', 'SEARCH-MANAGER', `Desktop done | earned=${points}`)
return points
})
)
}
this.bot.logger.info('main', 'SEARCH-MANAGER', `Running parallel: ${searchTypes.join(' + ') || 'none'}`)
const results = await Promise.all(promises)
this.bot.logger.debug(
'main',
'SEARCH-MANAGER',
`Parallel results | account=${accountEmail} | results=${JSON.stringify(results)}`
)
const mobilePoints = shouldDoMobile ? (results[0] ?? 0) : 0
const desktopPoints = shouldDoDesktop ? (results[shouldDoMobile ? 1 : 0] ?? 0) : 0
this.bot.logger.info(
'main',
'SEARCH-MANAGER',
`Parallel summary | mobile=${mobilePoints} | desktop=${desktopPoints} | total=${
mobilePoints + desktopPoints
}`
)
return { mobilePoints, desktopPoints }
} catch (error) {
this.bot.logger.error(
'main',
'SEARCH-MANAGER',
`Parallel failed: ${error instanceof Error ? error.message : String(error)}`
)
if (error instanceof Error && error.stack) {
this.bot.logger.debug('main', 'SEARCH-MANAGER', `Parallel stack: ${error.stack}`)
}
throw error
} finally {
if (!mobileContextClosed && mobileSession) {
this.bot.logger.info('main', 'SEARCH-MANAGER', 'Cleanup: closing mobile session')
this.bot.logger.debug('main', 'SEARCH-MANAGER', `Cleanup mobile | account=${accountEmail}`)
try {
await executionContext.run({ isMobile: true, accountEmail }, async () => {
await this.bot.browser.func.closeBrowser(mobileSession.context, accountEmail)
})
this.bot.logger.info('main', 'SEARCH-MANAGER', 'Cleanup: mobile session closed')
} catch (error) {
this.bot.logger.warn(
'main',
'SEARCH-MANAGER',
`Cleanup: mobile close failed: ${error instanceof Error ? error.message : String(error)}`
)
if (error instanceof Error && error.stack) {
this.bot.logger.debug('main', 'SEARCH-MANAGER', `Cleanup mobile stack: ${error.stack}`)
}
}
}
}
}
private async doSequentialSearches(
data: DashboardData,
missingSearchPoints: MissingSearchPoints,
mobileSession: BrowserSession,
account: Account,
accountEmail: string,
executionContext: any
): Promise<SearchResults> {
this.bot.logger.info('main', 'SEARCH-MANAGER', 'Sequential start')
this.bot.logger.debug(
'main',
'SEARCH-MANAGER',
`Sequential config | account=${accountEmail} | mobileMissing=${missingSearchPoints.mobilePoints} | desktopMissing=${missingSearchPoints.desktopPoints}`
)
const shouldDoMobile = this.bot.config.workers.doMobileSearch && missingSearchPoints.mobilePoints > 0
const shouldDoDesktop = this.bot.config.workers.doDesktopSearch && missingSearchPoints.desktopPoints > 0
this.bot.logger.debug(
'main',
'SEARCH-MANAGER',
`Sequential flags | mobile=${shouldDoMobile} | desktop=${shouldDoDesktop}`
)
let mobilePoints = 0
let desktopPoints = 0
if (shouldDoMobile) {
this.bot.logger.info('main', 'SEARCH-MANAGER', 'Step 1: mobile')
this.bot.logger.debug(
'main',
'SEARCH-MANAGER',
`Sequential mobile | target=${missingSearchPoints.mobilePoints}`
)
mobilePoints = await this.doMobileSearch(
data,
missingSearchPoints,
mobileSession,
accountEmail,
executionContext
)
this.bot.logger.info('main', 'SEARCH-MANAGER', `Step 1: mobile done | earned=${mobilePoints}`)
} else {
const reason = !this.bot.config.workers.doMobileSearch ? 'disabled' : 'no-points'
this.bot.logger.info('main', 'SEARCH-MANAGER', `Step 1: skip mobile (${reason}); closing mobile session`)
this.bot.logger.debug('main', 'SEARCH-MANAGER', 'Closing unused mobile context')
try {
await executionContext.run({ isMobile: true, accountEmail }, async () => {
await this.bot.browser.func.closeBrowser(mobileSession.context, accountEmail)
})
this.bot.logger.info('main', 'SEARCH-MANAGER', 'Unused mobile session closed')
} catch (error) {
this.bot.logger.warn(
'main',
'SEARCH-MANAGER',
`Unused mobile close failed: ${error instanceof Error ? error.message : String(error)}`
)
if (error instanceof Error && error.stack) {
this.bot.logger.debug('main', 'SEARCH-MANAGER', `Unused mobile stack: ${error.stack}`)
}
}
}
if (shouldDoDesktop) {
this.bot.logger.info('main', 'SEARCH-MANAGER', 'Step 2: desktop')
this.bot.logger.debug(
'main',
'SEARCH-MANAGER',
`Sequential desktop | target=${missingSearchPoints.desktopPoints}`
)
desktopPoints = await this.doDesktopSearchSequential(
data,
missingSearchPoints,
account,
accountEmail,
executionContext
)
this.bot.logger.info('main', 'SEARCH-MANAGER', `Step 2: desktop done | earned=${desktopPoints}`)
} else {
const reason = !this.bot.config.workers.doDesktopSearch ? 'disabled' : 'no-points'
this.bot.logger.info('main', 'SEARCH-MANAGER', `Step 2: skip desktop (${reason})`)
}
this.bot.logger.info(
'main',
'SEARCH-MANAGER',
`Sequential summary | mobile=${mobilePoints} | desktop=${desktopPoints} | total=${
mobilePoints + desktopPoints
}`
)
this.bot.logger.debug('main', 'SEARCH-MANAGER', `Sequential done | account=${accountEmail}`)
return { mobilePoints, desktopPoints }
}
private async createDesktopSession(account: Account, accountEmail: string): Promise<BrowserSession> {
this.bot.logger.info('main', 'SEARCH-DESKTOP-LOGIN', 'Init desktop session')
this.bot.logger.debug(
'main',
'SEARCH-DESKTOP-LOGIN',
`Init | account=${accountEmail} | proxy=${account.proxy ?? 'none'}`
)
const session = await this.bot['browserFactory'].createBrowser(account.proxy, accountEmail)
this.bot.logger.debug('main', 'SEARCH-DESKTOP-LOGIN', 'Browser created, new page')
this.bot.mainDesktopPage = await session.context.newPage()
this.bot.logger.info('main', 'SEARCH-DESKTOP-LOGIN', `Browser ready | account=${accountEmail}`)
this.bot.logger.info('main', 'SEARCH-DESKTOP-LOGIN', 'Login start')
this.bot.logger.debug('main', 'SEARCH-DESKTOP-LOGIN', 'Calling login handler')
await this.bot['login'].login(this.bot.mainDesktopPage, accountEmail, account.password, account.totp)
this.bot.logger.info('main', 'SEARCH-DESKTOP-LOGIN', 'Login passed, verifying')
this.bot.logger.debug('main', 'SEARCH-DESKTOP-LOGIN', 'verifyBingSession')
await this.bot['login'].verifyBingSession(this.bot.mainDesktopPage)
this.bot.cookies.desktop = await session.context.cookies()
this.bot.logger.debug('main', 'SEARCH-DESKTOP-LOGIN', 'Cookies stored')
this.bot.logger.info('main', 'SEARCH-DESKTOP-LOGIN', 'Desktop session ready')
return session
}
private async doMobileSearch(
data: DashboardData,
missingSearchPoints: MissingSearchPoints,
mobileSession: BrowserSession,
accountEmail: string,
executionContext: any
): Promise<number> {
this.bot.logger.debug(
'main',
'SEARCH-MOBILE-SEARCH',
`Start | account=${accountEmail} | target=${missingSearchPoints.mobilePoints}`
)
return await executionContext.run({ isMobile: true, accountEmail }, async () => {
try {
if (!this.bot.config.workers.doMobileSearch) {
this.bot.logger.info('main', 'SEARCH-MOBILE-SEARCH', 'Skip: worker disabled in config')
return 0
}
if (missingSearchPoints.mobilePoints === 0) {
this.bot.logger.info('main', 'SEARCH-MOBILE-SEARCH', 'Skip: no points left')
return 0
}
this.bot.logger.info(
'main',
'SEARCH-MOBILE-SEARCH',
`Search start | target=${missingSearchPoints.mobilePoints}`
)
this.bot.logger.debug('main', 'SEARCH-MOBILE-SEARCH', 'activities.doSearch (mobile)')
const pointsEarned = await this.bot.activities.doSearch(data, this.bot.mainMobilePage, true)
this.bot.logger.info(
'main',
'SEARCH-MOBILE-SEARCH',
`Search done | earned=${pointsEarned}/${missingSearchPoints.mobilePoints}`
)
this.bot.logger.debug(
'main',
'SEARCH-MOBILE-SEARCH',
`Result | account=${accountEmail} | earned=${pointsEarned}`
)
return pointsEarned
} catch (error) {
this.bot.logger.error(
'main',
'SEARCH-MOBILE-SEARCH',
`Failed: ${error instanceof Error ? error.message : String(error)}`
)
if (error instanceof Error && error.stack) {
this.bot.logger.debug('main', 'SEARCH-MOBILE-SEARCH', `Stack: ${error.stack}`)
}
return 0
} finally {
this.bot.logger.info('main', 'SEARCH-MOBILE-SEARCH', 'Closing mobile session')
this.bot.logger.debug('main', 'SEARCH-MOBILE-SEARCH', `Closing context | account=${accountEmail}`)
try {
await this.bot.browser.func.closeBrowser(mobileSession.context, accountEmail)
this.bot.logger.info('main', 'SEARCH-MOBILE-SEARCH', 'Mobile browser closed')
} catch (error) {
this.bot.logger.warn(
'main',
'SEARCH-MOBILE-SEARCH',
`Close failed: ${error instanceof Error ? error.message : String(error)}`
)
if (error instanceof Error && error.stack) {
this.bot.logger.debug('main', 'SEARCH-MOBILE-SEARCH', `Close stack: ${error.stack}`)
}
}
}
})
}
private async doDesktopSearch(
data: DashboardData,
missingSearchPoints: MissingSearchPoints,
desktopSession: BrowserSession,
accountEmail: string,
executionContext: any
): Promise<number> {
this.bot.logger.debug(
'main',
'SEARCH-DESKTOP-PARALLEL',
`Start | account=${accountEmail} | target=${missingSearchPoints.desktopPoints}`
)
return await executionContext.run({ isMobile: false, accountEmail }, async () => {
try {
this.bot.logger.info(
'main',
'SEARCH-DESKTOP-PARALLEL',
`Search start | target=${missingSearchPoints.desktopPoints}`
)
const pointsEarned = await this.bot.activities.doSearch(data, this.bot.mainDesktopPage, false)
this.bot.logger.info(
'main',
'SEARCH-DESKTOP-PARALLEL',
`Search done | earned=${pointsEarned}/${missingSearchPoints.desktopPoints}`
)
this.bot.logger.debug(
'main',
'SEARCH-DESKTOP-PARALLEL',
`Result | account=${accountEmail} | earned=${pointsEarned}`
)
return pointsEarned
} catch (error) {
this.bot.logger.error(
'main',
'SEARCH-DESKTOP-PARALLEL',
`Failed: ${error instanceof Error ? error.message : String(error)}`
)
if (error instanceof Error && error.stack) {
this.bot.logger.debug('main', 'SEARCH-DESKTOP-PARALLEL', `Stack: ${error.stack}`)
}
return 0
} finally {
this.bot.logger.info('main', 'SEARCH-DESKTOP-PARALLEL', 'Closing desktop session')
this.bot.logger.debug('main', 'SEARCH-DESKTOP-PARALLEL', `Closing context | account=${accountEmail}`)
try {
await this.bot.browser.func.closeBrowser(desktopSession.context, accountEmail)
this.bot.logger.info('main', 'SEARCH-DESKTOP-PARALLEL', 'Desktop browser closed')
} catch (error) {
this.bot.logger.warn(
'main',
'SEARCH-DESKTOP-PARALLEL',
`Close failed: ${error instanceof Error ? error.message : String(error)}`
)
if (error instanceof Error && error.stack) {
this.bot.logger.debug('main', 'SEARCH-DESKTOP-PARALLEL', `Close stack: ${error.stack}`)
}
}
}
})
}
private async doDesktopSearchSequential(
data: DashboardData,
missingSearchPoints: MissingSearchPoints,
account: Account,
accountEmail: string,
executionContext: any
): Promise<number> {
this.bot.logger.debug(
'main',
'SEARCH-DESKTOP-SEQUENTIAL',
`Start | account=${accountEmail} | target=${missingSearchPoints.desktopPoints}`
)
return await executionContext.run({ isMobile: false, accountEmail }, async () => {
if (!this.bot.config.workers.doDesktopSearch) {
this.bot.logger.info('main', 'SEARCH-DESKTOP-SEQUENTIAL', 'Skip: worker disabled in config')
return 0
}
if (missingSearchPoints.desktopPoints === 0) {
this.bot.logger.info('main', 'SEARCH-DESKTOP-SEQUENTIAL', 'Skip: no points left')
return 0
}
let desktopSession: BrowserSession | null = null
try {
this.bot.logger.info('main', 'SEARCH-DESKTOP-SEQUENTIAL', 'Init desktop session')
desktopSession = await this.createDesktopSession(account, accountEmail)
this.bot.logger.info(
'main',
'SEARCH-DESKTOP-SEQUENTIAL',
`Search start | target=${missingSearchPoints.desktopPoints}`
)
const pointsEarned = await this.bot.activities.doSearch(data, this.bot.mainDesktopPage, false)
this.bot.logger.info(
'main',
'SEARCH-DESKTOP-SEQUENTIAL',
`Search done | earned=${pointsEarned}/${missingSearchPoints.desktopPoints}`
)
this.bot.logger.debug(
'main',
'SEARCH-DESKTOP-SEQUENTIAL',
`Result | account=${accountEmail} | earned=${pointsEarned}`
)
return pointsEarned
} catch (error) {
this.bot.logger.error(
'main',
'SEARCH-DESKTOP-SEQUENTIAL',
`Failed: ${error instanceof Error ? error.message : String(error)}`
)
if (error instanceof Error && error.stack) {
this.bot.logger.debug('main', 'SEARCH-DESKTOP-SEQUENTIAL', `Stack: ${error.stack}`)
}
return 0
} finally {
if (desktopSession) {
this.bot.logger.info('main', 'SEARCH-DESKTOP-SEQUENTIAL', 'Closing desktop session')
this.bot.logger.debug(
'main',
'SEARCH-DESKTOP-SEQUENTIAL',
`Closing context | account=${accountEmail}`
)
try {
await this.bot.browser.func.closeBrowser(desktopSession.context, accountEmail)
this.bot.logger.info('main', 'SEARCH-DESKTOP-SEQUENTIAL', 'Desktop browser closed')
} catch (error) {
this.bot.logger.warn(
'main',
'SEARCH-DESKTOP-SEQUENTIAL',
`Close failed: ${error instanceof Error ? error.message : String(error)}`
)
if (error instanceof Error && error.stack) {
this.bot.logger.debug('main', 'SEARCH-DESKTOP-SEQUENTIAL', `Close stack: ${error.stack}`)
}
}
}
}
})
}
}

View File

@@ -1,199 +1,242 @@
import type { Page } from 'patchright'
import type { MicrosoftRewardsBot } from '../index'
import type { DashboardData, PunchCard, BasePromotion, FindClippyPromotion } from '../interface/DashboardData'
import type { AppDashboardData } from '../interface/AppDashBoardData'
import { Page } from 'rebrowser-playwright'
import { DashboardData, MorePromotion, PromotionalItem, PunchCard } from '../interface/DashboardData'
import { MicrosoftRewardsBot } from '../index'
import JobState from '../util/JobState'
import Retry from '../util/Retry'
import { AdaptiveThrottler } from '../util/AdaptiveThrottler'
export class Workers {
public bot: MicrosoftRewardsBot
private jobState: JobState
constructor(bot: MicrosoftRewardsBot) {
this.bot = bot
this.jobState = new JobState(this.bot.config)
}
public async doDailySet(data: DashboardData, page: Page) {
const todayKey = this.bot.utils.getFormattedDate()
const todayData = data.dailySetPromotions[todayKey]
// Daily Set
async doDailySet(page: Page, data: DashboardData) {
const todayData = data.dailySetPromotions[this.bot.utils.getFormattedDate()]
const activitiesUncompleted = todayData?.filter(x => !x.complete && x.pointProgressMax > 0) ?? []
const today = this.bot.utils.getFormattedDate()
const activitiesUncompleted = (todayData?.filter(x => !x.complete && x.pointProgressMax > 0) ?? [])
.filter(x => {
if (this.bot.config.jobState?.enabled === false) return true
const email = this.bot.currentAccountEmail || 'unknown'
return !this.jobState.isDone(email, today, x.offerId)
})
if (!activitiesUncompleted.length) {
this.bot.logger.info(this.bot.isMobile, 'DAILY-SET', 'All "Daily Set" items have already been completed')
this.bot.log(this.bot.isMobile, 'DAILY-SET', 'All Daily Set" items have already been completed')
return
}
this.bot.logger.info(this.bot.isMobile, 'DAILY-SET', 'Started solving "Daily Set" items')
// Solve Activities
this.bot.log(this.bot.isMobile, 'DAILY-SET', 'Started solving "Daily Set" items')
await this.solveActivities(activitiesUncompleted, page)
await this.solveActivities(page, activitiesUncompleted)
this.bot.logger.info(this.bot.isMobile, 'DAILY-SET', 'All "Daily Set" items have been completed')
}
public async doMorePromotions(data: DashboardData, page: Page) {
const morePromotions: BasePromotion[] = [
...new Map(
[...(data.morePromotions ?? []), ...(data.morePromotionsWithoutPromotionalItems ?? [])]
.filter(Boolean)
.map(p => [p.offerId, p as BasePromotion] as const)
).values()
]
const activitiesUncompleted: BasePromotion[] =
morePromotions?.filter(
x =>
!x.complete &&
x.pointProgressMax > 0 &&
x.exclusiveLockedFeatureStatus !== 'locked' &&
x.promotionType
) ?? []
if (!activitiesUncompleted.length) {
this.bot.logger.info(
this.bot.isMobile,
'MORE-PROMOTIONS',
'All "More Promotion" items have already been completed'
)
return
// Mark as done to prevent duplicate work if checkpoints enabled
if (this.bot.config.jobState?.enabled !== false) {
const email = this.bot.currentAccountEmail || 'unknown'
for (const a of activitiesUncompleted) {
this.jobState.markDone(email, today, a.offerId)
}
}
this.bot.logger.info(
this.bot.isMobile,
'MORE-PROMOTIONS',
`Started solving ${activitiesUncompleted.length} "More Promotions" items`
)
page = await this.bot.browser.utils.getLatestTab(page)
await this.solveActivities(activitiesUncompleted, page)
// Always return to the homepage if not already
await this.bot.browser.func.goHome(page)
this.bot.logger.info(this.bot.isMobile, 'MORE-PROMOTIONS', 'All "More Promotion" items have been completed')
}
this.bot.log(this.bot.isMobile, 'DAILY-SET', 'All "Daily Set" items have been completed')
public async doAppPromotions(data: AppDashboardData) {
const appRewards = data.response.promotions.filter(
x =>
x.attributes['complete']?.toLowerCase() === 'false' &&
x.attributes['offerid'] &&
x.attributes['type'] &&
x.attributes['type'] === 'sapphire'
)
if (!appRewards.length) {
this.bot.logger.info(
this.bot.isMobile,
'APP-PROMOTIONS',
'All "App Promotions" items have already been completed'
)
return
}
for (const reward of appRewards) {
await this.bot.activities.doAppReward(reward)
// A delay between completing each activity
await this.bot.utils.wait(this.bot.utils.randomDelay(5000, 15000))
}
this.bot.logger.info(this.bot.isMobile, 'APP-PROMOTIONS', 'All "App Promotions" items have been completed')
}
private async solveActivities(activities: BasePromotion[], page: Page, punchCard?: PunchCard) {
for (const activity of activities) {
// Optional: immediately run desktop search bundle
if (!this.bot.isMobile && this.bot.config.workers.bundleDailySetWithSearch && this.bot.config.workers.doDesktopSearch) {
try {
const type = activity.promotionType?.toLowerCase() ?? ''
const name = activity.name?.toLowerCase() ?? ''
const offerId = (activity as BasePromotion).offerId
const destinationUrl = activity.destinationUrl?.toLowerCase() ?? ''
this.bot.logger.debug(
this.bot.isMobile,
'ACTIVITY',
`Processing activity | title="${activity.title}" | offerId=${offerId} | type=${type} | punchCard="${punchCard?.parentPromotion?.title ?? 'none'}"`
)
switch (type) {
// Quiz-like activities (Poll / regular quiz variants)
case 'quiz': {
const basePromotion = activity as BasePromotion
// Poll (usually 10 points, pollscenarioid in URL)
if (activity.pointProgressMax === 10 && destinationUrl.includes('pollscenarioid')) {
this.bot.logger.info(
this.bot.isMobile,
'ACTIVITY',
`Found activity type "Poll" | title="${activity.title}" | offerId=${offerId}`
)
//await this.bot.activities.doPoll(basePromotion)
break
}
// All other quizzes handled via Quiz API
this.bot.logger.info(
this.bot.isMobile,
'ACTIVITY',
`Found activity type "Quiz" | title="${activity.title}" | offerId=${offerId}`
)
await this.bot.activities.doQuiz(basePromotion)
break
}
// UrlReward
case 'urlreward': {
const basePromotion = activity as BasePromotion
// Search on Bing are subtypes of "urlreward"
if (name.includes('exploreonbing')) {
this.bot.logger.info(
this.bot.isMobile,
'ACTIVITY',
`Found activity type "SearchOnBing" | title="${activity.title}" | offerId=${offerId}`
)
await this.bot.activities.doSearchOnBing(basePromotion, page)
} else {
this.bot.logger.info(
this.bot.isMobile,
'ACTIVITY',
`Found activity type "UrlReward" | title="${activity.title}" | offerId=${offerId}`
)
await this.bot.activities.doUrlReward(basePromotion)
}
break
}
// Find Clippy specific promotion type
case 'findclippy': {
const clippyPromotion = activity as unknown as FindClippyPromotion
this.bot.logger.info(
this.bot.isMobile,
'ACTIVITY',
`Found activity type "FindClippy" | title="${activity.title}" | offerId=${offerId}`
)
await this.bot.activities.doFindClippy(clippyPromotion)
break
}
// Unsupported types
default: {
this.bot.logger.warn(
this.bot.isMobile,
'ACTIVITY',
`Skipped activity "${activity.title}" | offerId=${offerId} | Reason: Unsupported type "${activity.promotionType}"`
)
break
}
}
// Cooldown
await this.bot.utils.wait(this.bot.utils.randomDelay(5000, 15000))
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'ACTIVITY',
`Error while solving activity "${activity.title}" | message=${error instanceof Error ? error.message : String(error)}`
)
await this.bot.utils.waitRandom(1200, 2600)
await this.bot.activities.doSearch(page, data)
} catch (e) {
this.bot.log(this.bot.isMobile, 'DAILY-SET', `Post-DailySet search failed: ${e instanceof Error ? e.message : e}`, 'warn')
}
}
}
}
// Punch Card
async doPunchCard(page: Page, data: DashboardData) {
const punchCardsUncompleted = data.punchCards?.filter(x => x.parentPromotion && !x.parentPromotion.complete) ?? [] // Only return uncompleted punch cards
if (!punchCardsUncompleted.length) {
this.bot.log(this.bot.isMobile, 'PUNCH-CARD', 'All "Punch Cards" have already been completed')
return
}
for (const punchCard of punchCardsUncompleted) {
// Ensure parentPromotion exists before proceeding
if (!punchCard.parentPromotion?.title) {
this.bot.log(this.bot.isMobile, 'PUNCH-CARD', `Skipped punchcard "${punchCard.name}" | Reason: Parent promotion is missing!`, 'warn')
continue
}
// Get latest page for each card
page = await this.bot.browser.utils.getLatestTab(page)
const activitiesUncompleted = punchCard.childPromotions.filter(x => !x.complete) // Only return uncompleted activities
// Solve Activities
this.bot.log(this.bot.isMobile, 'PUNCH-CARD', `Started solving "Punch Card" items for punchcard: "${punchCard.parentPromotion.title}"`)
// Got to punch card index page in a new tab
await page.goto(punchCard.parentPromotion.destinationUrl, { referer: this.bot.config.baseURL })
// Wait for new page to load, max 10 seconds, however try regardless in case of error
await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => { })
await this.solveActivities(page, activitiesUncompleted, punchCard)
page = await this.bot.browser.utils.getLatestTab(page)
const pages = page.context().pages()
if (pages.length > 3) {
await page.close()
} else {
await this.bot.browser.func.goHome(page)
}
this.bot.log(this.bot.isMobile, 'PUNCH-CARD', `All items for punchcard: "${punchCard.parentPromotion.title}" have been completed`)
}
this.bot.log(this.bot.isMobile, 'PUNCH-CARD', 'All "Punch Card" items have been completed')
}
// More Promotions
async doMorePromotions(page: Page, data: DashboardData) {
const morePromotions = data.morePromotions
// Check if there is a promotional item
if (data.promotionalItem) { // Convert and add the promotional item to the array
morePromotions.push(data.promotionalItem as unknown as MorePromotion)
}
const activitiesUncompleted = morePromotions?.filter(x => !x.complete && x.pointProgressMax > 0 && x.exclusiveLockedFeatureStatus !== 'locked') ?? []
if (!activitiesUncompleted.length) {
this.bot.log(this.bot.isMobile, 'MORE-PROMOTIONS', 'All "More Promotion" items have already been completed')
return
}
// Solve Activities
this.bot.log(this.bot.isMobile, 'MORE-PROMOTIONS', 'Started solving "More Promotions" items')
page = await this.bot.browser.utils.getLatestTab(page)
await this.solveActivities(page, activitiesUncompleted)
page = await this.bot.browser.utils.getLatestTab(page)
// Always return to the homepage if not already
await this.bot.browser.func.goHome(page)
this.bot.log(this.bot.isMobile, 'MORE-PROMOTIONS', 'All "More Promotion" items have been completed')
}
// Solve all the different types of activities
private async solveActivities(activityPage: Page, activities: PromotionalItem[] | MorePromotion[], punchCard?: PunchCard) {
const activityInitial = activityPage.url()
const retry = new Retry(this.bot.config.retryPolicy)
const throttle = new AdaptiveThrottler()
for (const activity of activities) {
try {
activityPage = await this.manageTabLifecycle(activityPage, activityInitial)
await this.applyThrottle(throttle, 800, 1400)
const selector = await this.buildActivitySelector(activityPage, activity, punchCard)
await this.prepareActivityPage(activityPage, selector, throttle)
const typeLabel = this.bot.activities.getTypeLabel(activity)
if (typeLabel !== 'Unsupported') {
await this.executeActivity(activityPage, activity, selector, throttle, retry)
} else {
this.bot.log(this.bot.isMobile, 'ACTIVITY', `Skipped activity "${activity.title}" | Reason: Unsupported type: "${activity.promotionType}"!`, 'warn')
}
await this.applyThrottle(throttle, 1200, 2600)
} catch (error) {
this.bot.log(this.bot.isMobile, 'ACTIVITY', 'An error occurred:' + error, 'error')
throttle.record(false)
}
}
}
private async manageTabLifecycle(page: Page, initialUrl: string): Promise<Page> {
page = await this.bot.browser.utils.getLatestTab(page)
const pages = page.context().pages()
if (pages.length > 3) {
await page.close()
page = await this.bot.browser.utils.getLatestTab(page)
}
if (page.url() !== initialUrl) {
await page.goto(initialUrl)
}
return page
}
private async buildActivitySelector(page: Page, activity: PromotionalItem | MorePromotion, punchCard?: PunchCard): Promise<string> {
if (punchCard) {
return await this.bot.browser.func.getPunchCardActivity(page, activity)
}
const name = activity.name.toLowerCase()
if (name.includes('membercenter') || name.includes('exploreonbing')) {
return `[data-bi-id^="${activity.name}"] .pointLink:not(.contentContainer .pointLink)`
}
return `[data-bi-id^="${activity.offerId}"] .pointLink:not(.contentContainer .pointLink)`
}
private async prepareActivityPage(page: Page, selector: string, throttle: AdaptiveThrottler): Promise<void> {
await page.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => {})
await this.bot.browser.utils.humanizePage(page)
await this.applyThrottle(throttle, 1200, 2600)
}
private async executeActivity(page: Page, activity: PromotionalItem | MorePromotion, selector: string, throttle: AdaptiveThrottler, retry: Retry): Promise<void> {
this.bot.log(this.bot.isMobile, 'ACTIVITY', `Found activity type: "${this.bot.activities.getTypeLabel(activity)}" title: "${activity.title}"`)
await page.click(selector)
page = await this.bot.browser.utils.getLatestTab(page)
const timeoutMs = this.bot.utils.stringToMs(this.bot.config?.globalTimeout ?? '30s') * 2
const runWithTimeout = (p: Promise<void>) => Promise.race([
p,
new Promise<void>((_, rej) => setTimeout(() => rej(new Error('activity-timeout')), timeoutMs))
])
await retry.run(async () => {
try {
await runWithTimeout(this.bot.activities.run(page, activity))
throttle.record(true)
} catch (e) {
throttle.record(false)
throw e
}
}, () => true)
await this.bot.browser.utils.humanizePage(page)
}
private async applyThrottle(throttle: AdaptiveThrottler, min: number, max: number): Promise<void> {
const multiplier = throttle.getDelayMultiplier()
await this.bot.utils.waitRandom(Math.floor(min * multiplier), Math.floor(max * multiplier))
}
}

View File

@@ -0,0 +1,51 @@
import { Page } from 'rebrowser-playwright'
import { Workers } from '../Workers'
import { RETRY_LIMITS, TIMEOUTS } from '../../constants'
export class ABC extends Workers {
async doABC(page: Page) {
this.bot.log(this.bot.isMobile, 'ABC', 'Trying to complete poll')
try {
let $ = await this.bot.browser.func.loadInCheerio(page)
let i
for (i = 0; i < RETRY_LIMITS.ABC_MAX && !$('span.rw_icon').length; i++) {
await page.waitForSelector('.wk_OptionClickClass', { state: 'visible', timeout: TIMEOUTS.DASHBOARD_WAIT })
const answers = $('.wk_OptionClickClass')
const answer = answers[this.bot.utils.randomNumber(0, 2)]?.attribs['id']
await page.waitForSelector(`#${answer}`, { state: 'visible', timeout: TIMEOUTS.DASHBOARD_WAIT })
await this.bot.utils.wait(TIMEOUTS.MEDIUM_LONG)
await page.click(`#${answer}`) // Click answer
await this.bot.utils.wait(TIMEOUTS.LONG + 1000)
await page.waitForSelector('div.wk_button', { state: 'visible', timeout: TIMEOUTS.DASHBOARD_WAIT })
await page.click('div.wk_button') // Click next question button
page = await this.bot.browser.utils.getLatestTab(page)
$ = await this.bot.browser.func.loadInCheerio(page)
await this.bot.utils.wait(TIMEOUTS.MEDIUM)
}
await this.bot.utils.wait(TIMEOUTS.LONG + 1000)
await page.close()
if (i === RETRY_LIMITS.ABC_MAX) {
this.bot.log(this.bot.isMobile, 'ABC', `Failed to solve quiz, exceeded max iterations of ${RETRY_LIMITS.ABC_MAX}`, 'warn')
} else {
this.bot.log(this.bot.isMobile, 'ABC', 'Completed the ABC successfully')
}
} catch (error) {
await page.close()
this.bot.log(this.bot.isMobile, 'ABC', 'An error occurred:' + error, 'error')
}
}
}

View File

@@ -0,0 +1,49 @@
import { randomBytes } from 'crypto'
import { AxiosRequestConfig } from 'axios'
import { Workers } from '../Workers'
import { DashboardData } from '../../interface/DashboardData'
export class DailyCheckIn extends Workers {
public async doDailyCheckIn(accessToken: string, data: DashboardData) {
this.bot.log(this.bot.isMobile, 'DAILY-CHECK-IN', 'Starting Daily Check In')
try {
let geoLocale = data.userProfile.attributes.country
geoLocale = (this.bot.config.searchSettings.useGeoLocaleQueries && geoLocale.length === 2) ? geoLocale.toLowerCase() : 'us'
const jsonData = {
amount: 1,
country: geoLocale,
id: randomBytes(64).toString('hex'),
type: 101,
attributes: {
offerid: 'Gamification_Sapphire_DailyCheckIn'
}
}
const claimRequest: AxiosRequestConfig = {
url: 'https://prod.rewardsplatform.microsoft.com/dapi/me/activities',
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'X-Rewards-Country': geoLocale,
'X-Rewards-Language': 'en',
'X-Rewards-ismobile': 'true'
},
data: JSON.stringify(jsonData)
}
const claimResponse = await this.bot.axios.request(claimRequest)
const claimedPoint = parseInt((await claimResponse.data).response?.activity?.p) ?? 0
this.bot.log(this.bot.isMobile, 'DAILY-CHECK-IN', claimedPoint > 0 ? `Claimed ${claimedPoint} points` : 'Already claimed today')
} catch (error) {
this.bot.log(this.bot.isMobile, 'DAILY-CHECK-IN', 'An error occurred:' + error, 'error')
}
}
}

View File

@@ -0,0 +1,32 @@
import { Page } from 'rebrowser-playwright'
import { Workers } from '../Workers'
import { TIMEOUTS } from '../../constants'
export class Poll extends Workers {
async doPoll(page: Page) {
this.bot.log(this.bot.isMobile, 'POLL', 'Trying to complete poll')
try {
const buttonId = `#btoption${Math.floor(this.bot.utils.randomNumber(0, 1))}`
await page.waitForSelector(buttonId, { state: 'visible', timeout: TIMEOUTS.DASHBOARD_WAIT }).catch((e) => {
this.bot.log(this.bot.isMobile, 'POLL', `Could not find poll button: ${e}`, 'warn')
})
await this.bot.utils.wait(TIMEOUTS.MEDIUM_LONG)
await page.click(buttonId)
await this.bot.utils.wait(TIMEOUTS.LONG + 1000)
await page.close()
this.bot.log(this.bot.isMobile, 'POLL', 'Completed the poll successfully')
} catch (error) {
await page.close()
this.bot.log(this.bot.isMobile, 'POLL', 'An error occurred:' + error, 'error')
}
}
}

View File

@@ -0,0 +1,131 @@
import { Page } from 'rebrowser-playwright'
import { Workers } from '../Workers'
import { RETRY_LIMITS, TIMEOUTS, DELAYS } from '../../constants'
export class Quiz extends Workers {
async doQuiz(page: Page) {
this.bot.log(this.bot.isMobile, 'QUIZ', 'Trying to complete quiz')
try {
// Check if the quiz has been started or not
const quizNotStarted = await page.waitForSelector('#rqStartQuiz', { state: 'visible', timeout: TIMEOUTS.MEDIUM_LONG }).then(() => true).catch(() => false)
if (quizNotStarted) {
await page.click('#rqStartQuiz')
} else {
this.bot.log(this.bot.isMobile, 'QUIZ', 'Quiz has already been started, trying to finish it')
}
await this.bot.utils.wait(TIMEOUTS.MEDIUM_LONG)
let quizData = await this.bot.browser.func.getQuizData(page)
// Verify quiz is actually loaded before proceeding
const firstOptionExists = await page.waitForSelector('#rqAnswerOption0', { state: 'attached', timeout: TIMEOUTS.VERY_LONG }).then(() => true).catch(() => false)
if (!firstOptionExists) {
this.bot.log(this.bot.isMobile, 'QUIZ', 'Quiz options not found - page may not have loaded correctly. Skipping.', 'warn')
await page.close()
return
}
const questionsRemaining = quizData.maxQuestions - quizData.CorrectlyAnsweredQuestionCount // Amount of questions remaining
// All questions
for (let question = 0; question < questionsRemaining; question++) {
if (quizData.numberOfOptions === 8) {
const answers: string[] = []
for (let i = 0; i < quizData.numberOfOptions; i++) {
const answerSelector = await page.waitForSelector(`#rqAnswerOption${i}`, { state: 'visible', timeout: TIMEOUTS.DASHBOARD_WAIT }).catch(() => null)
if (!answerSelector) {
this.bot.log(this.bot.isMobile, 'QUIZ', `Option ${i} not found - quiz structure may have changed. Skipping remaining options.`, 'warn')
break
}
const answerAttribute = await answerSelector?.evaluate((el: Element) => el.getAttribute('iscorrectoption'))
if (answerAttribute && answerAttribute.toLowerCase() === 'true') {
answers.push(`#rqAnswerOption${i}`)
}
}
// If no correct answers found, skip this question
if (answers.length === 0) {
this.bot.log(this.bot.isMobile, 'QUIZ', 'No correct answers found for 8-option quiz. Skipping.', 'warn')
await page.close()
return
}
// Click the answers
for (const answer of answers) {
await page.waitForSelector(answer, { state: 'visible', timeout: DELAYS.QUIZ_ANSWER_WAIT })
// Click the answer on page
await page.click(answer)
const refreshSuccess = await this.bot.browser.func.waitForQuizRefresh(page)
if (!refreshSuccess) {
await page.close()
this.bot.log(this.bot.isMobile, 'QUIZ', 'An error occurred, refresh was unsuccessful', 'error')
return
}
}
// Other type quiz, lightspeed
} else if ([2, 3, 4].includes(quizData.numberOfOptions)) {
quizData = await this.bot.browser.func.getQuizData(page) // Refresh Quiz Data
const correctOption = quizData.correctAnswer
let answerClicked = false
for (let i = 0; i < quizData.numberOfOptions; i++) {
const answerSelector = await page.waitForSelector(`#rqAnswerOption${i}`, { state: 'visible', timeout: RETRY_LIMITS.QUIZ_ANSWER_TIMEOUT }).catch(() => null)
if (!answerSelector) {
this.bot.log(this.bot.isMobile, 'QUIZ', `Option ${i} not found for ${quizData.numberOfOptions}-option quiz. Skipping.`, 'warn')
continue
}
const dataOption = await answerSelector?.evaluate((el: Element) => el.getAttribute('data-option'))
if (dataOption === correctOption) {
// Click the answer on page
await page.click(`#rqAnswerOption${i}`)
answerClicked = true
const refreshSuccess = await this.bot.browser.func.waitForQuizRefresh(page)
if (!refreshSuccess) {
await page.close()
this.bot.log(this.bot.isMobile, 'QUIZ', 'An error occurred, refresh was unsuccessful', 'error')
return
}
break
}
}
if (!answerClicked) {
this.bot.log(this.bot.isMobile, 'QUIZ', `Could not find correct answer for ${quizData.numberOfOptions}-option quiz. Skipping.`, 'warn')
await page.close()
return
}
await this.bot.utils.wait(DELAYS.QUIZ_ANSWER_WAIT)
}
}
// Done with
await this.bot.utils.wait(DELAYS.QUIZ_ANSWER_WAIT)
await page.close()
this.bot.log(this.bot.isMobile, 'QUIZ', 'Completed the quiz successfully')
} catch (error) {
await page.close()
this.bot.log(this.bot.isMobile, 'QUIZ', 'An error occurred:' + error, 'error')
}
}
}

View File

@@ -0,0 +1,74 @@
import { randomBytes } from 'crypto'
import { AxiosRequestConfig } from 'axios'
import { Workers } from '../Workers'
import { DashboardData } from '../../interface/DashboardData'
export class ReadToEarn extends Workers {
public async doReadToEarn(accessToken: string, data: DashboardData) {
this.bot.log(this.bot.isMobile, 'READ-TO-EARN', 'Starting Read to Earn')
try {
let geoLocale = data.userProfile.attributes.country
geoLocale = (this.bot.config.searchSettings.useGeoLocaleQueries && geoLocale.length === 2) ? geoLocale.toLowerCase() : 'us'
const userDataRequest: AxiosRequestConfig = {
url: 'https://prod.rewardsplatform.microsoft.com/dapi/me',
method: 'GET',
headers: {
'Authorization': `Bearer ${accessToken}`,
'X-Rewards-Country': geoLocale,
'X-Rewards-Language': 'en'
}
}
const userDataResponse = await this.bot.axios.request(userDataRequest)
const userData = (await userDataResponse.data).response
let userBalance = userData.balance
const jsonData = {
amount: 1,
country: geoLocale,
id: '1',
type: 101,
attributes: {
offerid: 'ENUS_readarticle3_30points'
}
}
const articleCount = 10
for (let i = 0; i < articleCount; ++i) {
jsonData.id = randomBytes(64).toString('hex')
const claimRequest = {
url: 'https://prod.rewardsplatform.microsoft.com/dapi/me/activities',
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'X-Rewards-Country': geoLocale,
'X-Rewards-Language': 'en',
'X-Rewards-ismobile': 'true'
},
data: JSON.stringify(jsonData)
}
const claimResponse = await this.bot.axios.request(claimRequest)
const newBalance = (await claimResponse.data).response.balance
if (newBalance == userBalance) {
this.bot.log(this.bot.isMobile, 'READ-TO-EARN', 'Read all available articles')
break
} else {
this.bot.log(this.bot.isMobile, 'READ-TO-EARN', `Read article ${i + 1} of ${articleCount} max | Gained ${newBalance - userBalance} Points`)
userBalance = newBalance
await this.bot.utils.wait(Math.floor(this.bot.utils.randomNumber(this.bot.utils.stringToMs(this.bot.config.searchSettings.searchDelay.min), this.bot.utils.stringToMs(this.bot.config.searchSettings.searchDelay.max))))
}
}
this.bot.log(this.bot.isMobile, 'READ-TO-EARN', 'Completed Read to Earn')
} catch (error) {
this.bot.log(this.bot.isMobile, 'READ-TO-EARN', 'An error occurred:' + error, 'error')
}
}
}

View File

@@ -0,0 +1,445 @@
import { Page } from 'rebrowser-playwright'
import { platform } from 'os'
import { Workers } from '../Workers'
import { Counters, DashboardData } from '../../interface/DashboardData'
import { GoogleSearch } from '../../interface/Search'
import { AxiosRequestConfig } from 'axios'
type GoogleTrendsResponse = [
string,
[
string,
...null[],
[string, ...string[]]
][]
];
export class Search extends Workers {
private bingHome = 'https://bing.com'
private searchPageURL = ''
public async doSearch(page: Page, data: DashboardData) {
this.bot.log(this.bot.isMobile, 'SEARCH-BING', 'Starting Bing searches')
page = await this.bot.browser.utils.getLatestTab(page)
let searchCounters: Counters = await this.bot.browser.func.getSearchPoints()
let missingPoints = this.calculatePoints(searchCounters)
if (missingPoints === 0) {
this.bot.log(this.bot.isMobile, 'SEARCH-BING', 'Bing searches have already been completed')
return
}
// Generate search queries (primary: Google Trends)
const geo = this.bot.config.searchSettings.useGeoLocaleQueries ? data.userProfile.attributes.country : 'US'
let googleSearchQueries = await this.getGoogleTrends(geo)
// Fallback: if trends failed or insufficient, sample from local queries file
if (!googleSearchQueries.length || googleSearchQueries.length < 10) {
this.bot.log(this.bot.isMobile, 'SEARCH-BING', 'Primary trends source insufficient, falling back to local queries.json', 'warn')
try {
const local = await import('../queries.json')
// Flatten & sample
const sampleSize = Math.max(5, Math.min(this.bot.config.searchSettings.localFallbackCount || 25, local.default.length))
const sampled = this.bot.utils.shuffleArray(local.default).slice(0, sampleSize)
googleSearchQueries = sampled.map((x: { title: string; queries: string[] }) => ({ topic: x.queries[0] || x.title, related: x.queries.slice(1) }))
} catch (e) {
this.bot.log(this.bot.isMobile, 'SEARCH-BING', 'Failed loading local queries fallback: ' + (e instanceof Error ? e.message : e), 'error')
}
}
googleSearchQueries = this.bot.utils.shuffleArray(googleSearchQueries)
// Deduplicate topics
const seen = new Set<string>()
googleSearchQueries = googleSearchQueries.filter(q => {
if (seen.has(q.topic.toLowerCase())) return false
seen.add(q.topic.toLowerCase())
return true
})
// Go to bing
await page.goto(this.searchPageURL ? this.searchPageURL : this.bingHome)
await this.bot.utils.wait(2000)
await this.bot.browser.utils.tryDismissAllMessages(page)
let stagnation = 0 // consecutive searches without point progress
const queries: string[] = []
// Mobile search doesn't seem to like related queries?
googleSearchQueries.forEach(x => { this.bot.isMobile ? queries.push(x.topic) : queries.push(x.topic, ...x.related) })
// Loop over Google search queries
for (let i = 0; i < queries.length; i++) {
const query = queries[i] as string
this.bot.log(this.bot.isMobile, 'SEARCH-BING', `${missingPoints} Points Remaining | Query: ${query}`)
searchCounters = await this.bingSearch(page, query)
const newMissingPoints = this.calculatePoints(searchCounters)
// If the new point amount is the same as before
if (newMissingPoints === missingPoints) {
stagnation++
} else {
stagnation = 0
}
missingPoints = newMissingPoints
if (missingPoints === 0) break
// Only for mobile searches
if (stagnation > 5 && this.bot.isMobile) {
this.bot.log(this.bot.isMobile, 'SEARCH-BING', 'Search didn\'t gain point for 5 iterations, likely bad User-Agent', 'warn')
break
}
// If we didn't gain points for 10 iterations, assume it's stuck
if (stagnation > 10) {
this.bot.log(this.bot.isMobile, 'SEARCH-BING', 'Search didn\'t gain point for 10 iterations aborting searches', 'warn')
stagnation = 0 // allow fallback loop below
break
}
}
// Only for mobile searches
if (missingPoints > 0 && this.bot.isMobile) {
return
}
// If we still got remaining search queries, generate extra ones
if (missingPoints > 0) {
this.bot.log(this.bot.isMobile, 'SEARCH-BING', `Search completed but we're missing ${missingPoints} points, generating extra searches`)
let i = 0
let fallbackRounds = 0
const extraRetries = this.bot.config.searchSettings.extraFallbackRetries || 1
while (missingPoints > 0 && fallbackRounds <= extraRetries) {
const query = googleSearchQueries[i++] as GoogleSearch
if (!query) break
// Get related search terms to the Google search queries
const relatedTerms = await this.getRelatedTerms(query?.topic)
if (relatedTerms.length > 3) {
// Search for the first 2 related terms
for (const term of relatedTerms.slice(1, 3)) {
this.bot.log(this.bot.isMobile, 'SEARCH-BING-EXTRA', `${missingPoints} Points Remaining | Query: ${term}`)
searchCounters = await this.bingSearch(page, term)
const newMissingPoints = this.calculatePoints(searchCounters)
// If the new point amount is the same as before
if (newMissingPoints === missingPoints) {
stagnation++
} else {
stagnation = 0
}
missingPoints = newMissingPoints
// If we satisfied the searches
if (missingPoints === 0) {
break
}
// Try 5 more times, then we tried a total of 15 times, fair to say it's stuck
if (stagnation > 5) {
this.bot.log(this.bot.isMobile, 'SEARCH-BING-EXTRA', 'Search didn\'t gain point for 5 iterations aborting searches', 'warn')
return
}
}
fallbackRounds++
}
}
}
this.bot.log(this.bot.isMobile, 'SEARCH-BING', 'Completed searches')
}
private async bingSearch(searchPage: Page, query: string) {
const platformControlKey = platform() === 'darwin' ? 'Meta' : 'Control'
// Try a max of 5 times
for (let i = 0; i < 5; i++) {
try {
// This page had already been set to the Bing.com page or the previous search listing, we just need to select it
searchPage = await this.bot.browser.utils.getLatestTab(searchPage)
// Go to top of the page
await searchPage.evaluate(() => {
window.scrollTo(0, 0)
})
await this.bot.utils.wait(500)
const searchBar = '#sb_form_q'
// Prefer attached over visible to avoid strict visibility waits when overlays exist
const box = searchPage.locator(searchBar)
await box.waitFor({ state: 'attached', timeout: 15000 })
// Try dismissing overlays before interacting
await this.bot.browser.utils.tryDismissAllMessages(searchPage)
await this.bot.utils.wait(200)
let navigatedDirectly = false
try {
// Try focusing and filling instead of clicking (more reliable on mobile)
await box.focus({ timeout: 2000 }).catch(() => { /* ignore focus errors */ })
await box.fill('')
await this.bot.utils.wait(200)
await searchPage.keyboard.down(platformControlKey)
await searchPage.keyboard.press('A')
await searchPage.keyboard.press('Backspace')
await searchPage.keyboard.up(platformControlKey)
await box.type(query, { delay: 20 })
await searchPage.keyboard.press('Enter')
} catch (typeErr) {
// As a robust fallback, navigate directly to the search results URL
const q = encodeURIComponent(query)
const url = `https://www.bing.com/search?q=${q}`
await searchPage.goto(url)
navigatedDirectly = true
}
await this.bot.utils.wait(3000)
// Bing.com in Chrome opens a new tab when searching via Enter; if we navigated directly, stay on current tab
const resultPage = navigatedDirectly ? searchPage : await this.bot.browser.utils.getLatestTab(searchPage)
this.searchPageURL = new URL(resultPage.url()).href // Set the results page
await this.bot.browser.utils.reloadBadPage(resultPage)
if (this.bot.config.searchSettings.scrollRandomResults) {
await this.bot.utils.wait(2000)
await this.randomScroll(resultPage)
}
if (this.bot.config.searchSettings.clickRandomResults) {
await this.bot.utils.wait(2000)
await this.clickRandomLink(resultPage)
}
// Delay between searches
const minDelay = this.bot.utils.stringToMs(this.bot.config.searchSettings.searchDelay.min)
const maxDelay = this.bot.utils.stringToMs(this.bot.config.searchSettings.searchDelay.max)
const adaptivePad = Math.min(4000, Math.max(0, Math.floor(Math.random() * 800)))
await this.bot.utils.wait(Math.floor(this.bot.utils.randomNumber(minDelay, maxDelay)) + adaptivePad)
return await this.bot.browser.func.getSearchPoints()
} catch (error) {
if (i === 5) {
this.bot.log(this.bot.isMobile, 'SEARCH-BING', 'Failed after 5 retries... An error occurred:' + error, 'error')
break
}
this.bot.log(this.bot.isMobile, 'SEARCH-BING', 'Search failed, An error occurred:' + error, 'error')
this.bot.log(this.bot.isMobile, 'SEARCH-BING', `Retrying search, attempt ${i}/5`, 'warn')
// Reset the tabs
const lastTab = await this.bot.browser.utils.getLatestTab(searchPage)
await this.closeTabs(lastTab)
await this.bot.utils.wait(4000)
}
}
this.bot.log(this.bot.isMobile, 'SEARCH-BING', 'Search failed after 5 retries, ending', 'error')
return await this.bot.browser.func.getSearchPoints()
}
private async getGoogleTrends(geoLocale: string = 'US'): Promise<GoogleSearch[]> {
const queryTerms: GoogleSearch[] = []
this.bot.log(this.bot.isMobile, 'SEARCH-GOOGLE-TRENDS', `Generating search queries, can take a while! | GeoLocale: ${geoLocale}`)
try {
const request: AxiosRequestConfig = {
url: 'https://trends.google.com/_/TrendsUi/data/batchexecute',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
data: `f.req=[[[i0OFE,"[null, null, \\"${geoLocale.toUpperCase()}\\", 0, null, 48]"]]]`
}
const response = await this.bot.axios.request(request, this.bot.config.proxy.proxyGoogleTrends)
const rawText = response.data
const trendsData = this.extractJsonFromResponse(rawText)
if (!trendsData) {
throw this.bot.log(this.bot.isMobile, 'SEARCH-GOOGLE-TRENDS', 'Failed to parse Google Trends response', 'error')
}
const mappedTrendsData = trendsData.map(query => [query[0], query[9]!.slice(1)])
this.bot.log(this.bot.isMobile, 'SEARCH-GOOGLE-TRENDS', `Found ${mappedTrendsData.length} search queries for ${geoLocale}`)
if (mappedTrendsData.length < 30 && geoLocale.toUpperCase() !== 'US') {
this.bot.log(this.bot.isMobile, 'SEARCH-GOOGLE-TRENDS', `Insufficient search queries (${mappedTrendsData.length} < 30), falling back to US`, 'warn')
return this.getGoogleTrends()
}
for (const [topic, relatedQueries] of mappedTrendsData) {
queryTerms.push({
topic: topic as string,
related: relatedQueries as string[]
})
}
} catch (error) {
this.bot.log(this.bot.isMobile, 'SEARCH-GOOGLE-TRENDS', 'An error occurred:' + error, 'error')
}
return queryTerms
}
private extractJsonFromResponse(text: string): GoogleTrendsResponse[1] | null {
const lines = text.split('\n')
for (const line of lines) {
const trimmed = line.trim()
if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
try {
return JSON.parse(JSON.parse(trimmed)[0][2])[1]
} catch {
continue
}
}
}
return null
}
private async getRelatedTerms(term: string): Promise<string[]> {
try {
const request = {
url: `https://api.bing.com/osjson.aspx?query=${term}`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
const response = await this.bot.axios.request(request, this.bot.config.proxy.proxyBingTerms)
return response.data[1] as string[]
} catch (error) {
this.bot.log(this.bot.isMobile, 'SEARCH-BING-RELATED', 'An error occurred:' + error, 'error')
}
return []
}
private async randomScroll(page: Page) {
try {
const viewportHeight = await page.evaluate(() => window.innerHeight)
const totalHeight = await page.evaluate(() => document.body.scrollHeight)
const randomScrollPosition = Math.floor(Math.random() * (totalHeight - viewportHeight))
await page.evaluate((scrollPos: number) => {
window.scrollTo(0, scrollPos)
}, randomScrollPosition)
} catch (error) {
this.bot.log(this.bot.isMobile, 'SEARCH-RANDOM-SCROLL', 'An error occurred:' + error, 'error')
}
}
private async clickRandomLink(page: Page) {
try {
await page.click('#b_results .b_algo h2', { timeout: 2000 }).catch(() => { }) // Since we don't really care if it did it or not
// Only used if the browser is not the edge browser (continue on Edge popup)
await this.closeContinuePopup(page)
// Stay for 10 seconds for page to load and "visit"
await this.bot.utils.wait(10000)
// Will get current tab if no new one is created, this will always be the visited site or the result page if it failed to click
let lastTab = await this.bot.browser.utils.getLatestTab(page)
let lastTabURL = new URL(lastTab.url()) // Get new tab info, this is the website we're visiting
// Check if the URL is different from the original one, don't loop more than 5 times.
let i = 0
while (lastTabURL.href !== this.searchPageURL && i < 5) {
await this.closeTabs(lastTab)
// End of loop, refresh lastPage
lastTab = await this.bot.browser.utils.getLatestTab(page) // Finally update the lastTab var again
lastTabURL = new URL(lastTab.url()) // Get new tab info
i++
}
} catch (error) {
this.bot.log(this.bot.isMobile, 'SEARCH-RANDOM-CLICK', 'An error occurred:' + error, 'error')
}
}
private async closeTabs(lastTab: Page) {
const browser = lastTab.context()
const tabs = browser.pages()
try {
if (tabs.length > 2) {
// If more than 2 tabs are open, close the last tab
await lastTab.close()
this.bot.log(this.bot.isMobile, 'SEARCH-CLOSE-TABS', `More than 2 were open, closed the last tab: "${new URL(lastTab.url()).host}"`)
} else if (tabs.length === 1) {
// If only 1 tab is open, open a new one to search in
const newPage = await browser.newPage()
await this.bot.utils.wait(1000)
await newPage.goto(this.bingHome)
await this.bot.utils.wait(3000)
this.searchPageURL = newPage.url()
this.bot.log(this.bot.isMobile, 'SEARCH-CLOSE-TABS', 'There was only 1 tab open, crated a new one')
} else {
// Else reset the last tab back to the search listing or Bing.com
lastTab = await this.bot.browser.utils.getLatestTab(lastTab)
await lastTab.goto(this.searchPageURL ? this.searchPageURL : this.bingHome)
}
} catch (error) {
this.bot.log(this.bot.isMobile, 'SEARCH-CLOSE-TABS', 'An error occurred:' + error, 'error')
}
}
private calculatePoints(counters: Counters) {
const mobileData = counters.mobileSearch?.[0] // Mobile searches
const genericData = counters.pcSearch?.[0] // Normal searches
const edgeData = counters.pcSearch?.[1] // Edge searches
const missingPoints = (this.bot.isMobile && mobileData)
? mobileData.pointProgressMax - mobileData.pointProgress
: (edgeData ? edgeData.pointProgressMax - edgeData.pointProgress : 0)
+ (genericData ? genericData.pointProgressMax - genericData.pointProgress : 0)
return missingPoints
}
private async closeContinuePopup(page: Page) {
try {
await page.waitForSelector('#sacs_close', { timeout: 1000 })
const continueButton = await page.$('#sacs_close')
if (continueButton) {
await continueButton.click()
}
} catch (error) {
// Continue if element is not found or other error occurs
}
}
}

View File

@@ -0,0 +1,85 @@
import type { Page } from 'playwright'
import * as fs from 'fs'
import path from 'path'
import { Workers } from '../Workers'
import { DELAYS } from '../../constants'
import { MorePromotion, PromotionalItem } from '../../interface/DashboardData'
export class SearchOnBing extends Workers {
async doSearchOnBing(page: Page, activity: MorePromotion | PromotionalItem) {
this.bot.log(this.bot.isMobile, 'SEARCH-ON-BING', 'Trying to complete SearchOnBing')
try {
await this.bot.utils.wait(DELAYS.SEARCH_ON_BING_WAIT)
await this.bot.browser.utils.tryDismissAllMessages(page)
const query = await this.getSearchQuery(activity.title)
const searchBar = '#sb_form_q'
const box = page.locator(searchBar)
await box.waitFor({ state: 'attached', timeout: DELAYS.SEARCH_BAR_TIMEOUT })
await this.bot.browser.utils.tryDismissAllMessages(page)
await this.bot.utils.wait(DELAYS.SEARCH_ON_BING_FOCUS)
try {
await box.focus({ timeout: DELAYS.THIS_OR_THAT_START }).catch(() => { /* ignore */ })
await box.fill('')
await this.bot.utils.wait(DELAYS.SEARCH_ON_BING_FOCUS)
await page.keyboard.type(query, { delay: DELAYS.TYPING_DELAY })
await page.keyboard.press('Enter')
} catch {
const url = `https://www.bing.com/search?q=${encodeURIComponent(query)}`
await page.goto(url)
}
await this.bot.utils.wait(DELAYS.SEARCH_ON_BING_COMPLETE)
await page.close()
this.bot.log(this.bot.isMobile, 'SEARCH-ON-BING', 'Completed the SearchOnBing successfully')
} catch (error) {
await page.close()
this.bot.log(this.bot.isMobile, 'SEARCH-ON-BING', 'An error occurred:' + error, 'error')
}
}
private async getSearchQuery(title: string): Promise<string> {
interface Queries {
title: string;
queries: string[]
}
let queries: Queries[] = []
try {
if (this.bot.config.searchOnBingLocalQueries) {
const data = fs.readFileSync(path.join(__dirname, '../queries.json'), 'utf8')
queries = JSON.parse(data)
} else {
// Fetch from the repo directly so the user doesn't need to redownload the script for the new activities
const response = await this.bot.axios.request({
method: 'GET',
url: 'https://raw.githubusercontent.com/TheNetsky/Microsoft-Rewards-Script/refs/heads/v2/src/functions/queries.json'
})
queries = response.data
}
const answers = queries.find(x => this.normalizeString(x.title) === this.normalizeString(title))
const answer = answers ? this.bot.utils.shuffleArray(answers?.queries)[0] as string : title
this.bot.log(this.bot.isMobile, 'SEARCH-ON-BING-QUERY', `Fetched answer: ${answer} | question: ${title}`)
return answer
} catch (error) {
this.bot.log(this.bot.isMobile, 'SEARCH-ON-BING-QUERY', 'An error occurred:' + error, 'error')
return title
}
}
private normalizeString(string: string): string {
return string.normalize('NFD').trim().toLowerCase().replace(/[^\x20-\x7E]/g, '').replace(/[?!]/g, '')
}
}

View File

@@ -0,0 +1,48 @@
import { Page } from 'rebrowser-playwright'
import { Workers } from '../Workers'
import { DELAYS } from '../../constants'
export class ThisOrThat extends Workers {
async doThisOrThat(page: Page) {
this.bot.log(this.bot.isMobile, 'THIS-OR-THAT', 'Trying to complete ThisOrThat')
try {
// Check if the quiz has been started or not
const quizNotStarted = await page.waitForSelector('#rqStartQuiz', { state: 'visible', timeout: DELAYS.THIS_OR_THAT_START }).then(() => true).catch(() => false)
if (quizNotStarted) {
await page.click('#rqStartQuiz')
} else {
this.bot.log(this.bot.isMobile, 'THIS-OR-THAT', 'ThisOrThat has already been started, trying to finish it')
}
await this.bot.utils.wait(DELAYS.THIS_OR_THAT_START)
// Solving
const quizData = await this.bot.browser.func.getQuizData(page)
const questionsRemaining = quizData.maxQuestions - (quizData.currentQuestionNumber - 1) // Amount of questions remaining
for (let question = 0; question < questionsRemaining; question++) {
// Since there's no solving logic yet, randomly guess to complete
const buttonId = `#rqAnswerOption${Math.floor(this.bot.utils.randomNumber(0, 1))}`
await page.click(buttonId)
const refreshSuccess = await this.bot.browser.func.waitForQuizRefresh(page)
if (!refreshSuccess) {
await page.close()
this.bot.log(this.bot.isMobile, 'QUIZ', 'An error occurred, refresh was unsuccessful', 'error')
return
}
}
this.bot.log(this.bot.isMobile, 'THIS-OR-THAT', 'Completed the ThisOrThat successfully')
} catch (error) {
await page.close()
this.bot.log(this.bot.isMobile, 'THIS-OR-THAT', 'An error occurred:' + error, 'error')
}
}
}

View File

@@ -0,0 +1,23 @@
import { Page } from 'rebrowser-playwright'
import { Workers } from '../Workers'
export class UrlReward extends Workers {
async doUrlReward(page: Page) {
this.bot.log(this.bot.isMobile, 'URL-REWARD', 'Trying to complete UrlReward')
try {
await this.bot.utils.wait(2000)
await page.close()
this.bot.log(this.bot.isMobile, 'URL-REWARD', 'Completed the UrlReward successfully')
} catch (error) {
await page.close()
this.bot.log(this.bot.isMobile, 'URL-REWARD', 'An error occurred:' + error, 'error')
}
}
}

View File

@@ -1,130 +0,0 @@
import type { AxiosRequestConfig } from 'axios'
import type { FindClippyPromotion } from '../../../interface/DashboardData'
import { Workers } from '../../Workers'
export class FindClippy extends Workers {
private cookieHeader: string = ''
private fingerprintHeader: { [x: string]: string } = {}
private gainedPoints: number = 0
private oldBalance: number = this.bot.userData.currentPoints
public async doFindClippy(promotion: FindClippyPromotion) {
const offerId = promotion.offerId
const activityType = promotion.activityType
try {
if (!this.bot.requestToken) {
this.bot.logger.warn(
this.bot.isMobile,
'FIND-CLIPPY',
'Skipping: Request token not available, this activity requires it!'
)
return
}
this.cookieHeader = (this.bot.isMobile ? this.bot.cookies.mobile : this.bot.cookies.desktop)
.map((c: { name: string; value: string }) => `${c.name}=${c.value}`)
.join('; ')
const fingerprintHeaders = { ...this.bot.fingerprint.headers }
delete fingerprintHeaders['Cookie']
delete fingerprintHeaders['cookie']
this.fingerprintHeader = fingerprintHeaders
this.bot.logger.info(
this.bot.isMobile,
'FIND-CLIPPY',
`Starting Find Clippy | offerId=${offerId} | activityType=${activityType} | oldBalance=${this.oldBalance}`
)
this.bot.logger.debug(
this.bot.isMobile,
'FIND-CLIPPY',
`Prepared headers | cookieLength=${this.cookieHeader.length} | fingerprintHeaderKeys=${Object.keys(this.fingerprintHeader).length}`
)
const formData = new URLSearchParams({
id: offerId,
hash: promotion.hash,
timeZone: '60',
activityAmount: '1',
dbs: '0',
form: '',
type: activityType,
__RequestVerificationToken: this.bot.requestToken
})
this.bot.logger.debug(
this.bot.isMobile,
'FIND-CLIPPY',
`Prepared Find Clippy form data | offerId=${offerId} | hash=${promotion.hash} | timeZone=60 | activityAmount=1 | type=${activityType}`
)
const request: AxiosRequestConfig = {
url: 'https://rewards.bing.com/api/reportactivity?X-Requested-With=XMLHttpRequest',
method: 'POST',
headers: {
...(this.bot.fingerprint?.headers ?? {}),
Cookie: this.cookieHeader,
Referer: 'https://rewards.bing.com/',
Origin: 'https://rewards.bing.com'
},
data: formData
}
this.bot.logger.debug(
this.bot.isMobile,
'FIND-CLIPPY',
`Sending Find Clippy request | offerId=${offerId} | url=${request.url}`
)
const response = await this.bot.axios.request(request)
this.bot.logger.debug(
this.bot.isMobile,
'FIND-CLIPPY',
`Received Find Clippy response | offerId=${offerId} | status=${response.status}`
)
const newBalance = await this.bot.browser.func.getCurrentPoints()
this.gainedPoints = newBalance - this.oldBalance
this.bot.logger.debug(
this.bot.isMobile,
'FIND-CLIPPY',
`Balance delta after Find Clippy | offerId=${offerId} | oldBalance=${this.oldBalance} | newBalance=${newBalance} | gainedPoints=${this.gainedPoints}`
)
if (this.gainedPoints > 0) {
this.bot.userData.currentPoints = newBalance
this.bot.userData.gainedPoints = (this.bot.userData.gainedPoints ?? 0) + this.gainedPoints
this.bot.logger.info(
this.bot.isMobile,
'FIND-CLIPPY',
`Found Clippy | offerId=${offerId} | status=${response.status} | gainedPoints=${this.gainedPoints} | newBalance=${newBalance}`,
'green'
)
} else {
this.bot.logger.warn(
this.bot.isMobile,
'FIND-CLIPPY',
`Found Clippy but no points were gained | offerId=${offerId} | status=${response.status} | oldBalance=${this.oldBalance} | newBalance=${newBalance}`
)
}
this.bot.logger.debug(this.bot.isMobile, 'FIND-CLIPPY', `Waiting after Find Clippy | offerId=${offerId}`)
await this.bot.utils.wait(this.bot.utils.randomDelay(5000, 10000))
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'FIND-CLIPPY',
`Error in doFindClippy | offerId=${offerId} | message=${error instanceof Error ? error.message : String(error)}`
)
}
}
}

View File

@@ -1,173 +0,0 @@
import type { AxiosRequestConfig } from 'axios'
import type { BasePromotion } from '../../../interface/DashboardData'
import { Workers } from '../../Workers'
export class Quiz extends Workers {
private cookieHeader: string = ''
private fingerprintHeader: { [x: string]: string } = {}
private gainedPoints: number = 0
private oldBalance: number = this.bot.userData.currentPoints
async doQuiz(promotion: BasePromotion) {
const offerId = promotion.offerId
this.oldBalance = Number(this.bot.userData.currentPoints ?? 0)
const startBalance = this.oldBalance
this.bot.logger.info(
this.bot.isMobile,
'QUIZ',
`Starting quiz | offerId=${offerId} | pointProgressMax=${promotion.pointProgressMax} | activityProgressMax=${promotion.activityProgressMax} | currentPoints=${startBalance}`
)
try {
this.cookieHeader = (this.bot.isMobile ? this.bot.cookies.mobile : this.bot.cookies.desktop)
.map((c: { name: string; value: string }) => `${c.name}=${c.value}`)
.join('; ')
const fingerprintHeaders = { ...this.bot.fingerprint.headers }
delete fingerprintHeaders['Cookie']
delete fingerprintHeaders['cookie']
this.fingerprintHeader = fingerprintHeaders
this.bot.logger.debug(
this.bot.isMobile,
'QUIZ',
`Prepared quiz headers | offerId=${offerId} | cookieLength=${this.cookieHeader.length} | fingerprintHeaderKeys=${Object.keys(this.fingerprintHeader).length}`
)
// 8-question quiz
if (promotion.activityProgressMax === 80) {
this.bot.logger.warn(
this.bot.isMobile,
'QUIZ',
`Detected 8-question quiz (activityProgressMax=80), marking as completed | offerId=${offerId}`
)
// Not implemented
return
}
//Standard points quizzes (20/30/40/50 max)
if ([20, 30, 40, 50].includes(promotion.pointProgressMax)) {
let oldBalance = startBalance
let gainedPoints = 0
const maxAttempts = 20
let totalGained = 0
let attempts = 0
this.bot.logger.debug(
this.bot.isMobile,
'QUIZ',
`Starting ReportActivity loop | offerId=${offerId} | maxAttempts=${maxAttempts} | startingBalance=${oldBalance}`
)
for (let i = 0; i < maxAttempts; i++) {
try {
const jsonData = {
UserId: null,
TimeZoneOffset: -60,
OfferId: offerId,
ActivityCount: 1,
QuestionIndex: '-1'
}
const request: AxiosRequestConfig = {
url: 'https://www.bing.com/bingqa/ReportActivity?ajaxreq=1',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
cookie: this.cookieHeader,
...this.fingerprintHeader
},
data: JSON.stringify(jsonData)
}
this.bot.logger.debug(
this.bot.isMobile,
'QUIZ',
`Sending ReportActivity request | attempt=${i + 1}/${maxAttempts} | offerId=${offerId} | url=${request.url}`
)
const response = await this.bot.axios.request(request)
this.bot.logger.debug(
this.bot.isMobile,
'QUIZ',
`Received ReportActivity response | attempt=${i + 1}/${maxAttempts} | offerId=${offerId} | status=${response.status}`
)
const newBalance = await this.bot.browser.func.getCurrentPoints()
gainedPoints = newBalance - oldBalance
this.bot.logger.debug(
this.bot.isMobile,
'QUIZ',
`Balance delta after ReportActivity | attempt=${i + 1}/${maxAttempts} | offerId=${offerId} | oldBalance=${oldBalance} | newBalance=${newBalance} | gainedPoints=${gainedPoints}`
)
attempts = i + 1
if (gainedPoints > 0) {
this.bot.userData.currentPoints = newBalance
this.bot.userData.gainedPoints = (this.bot.userData.gainedPoints ?? 0) + gainedPoints
oldBalance = newBalance
totalGained += gainedPoints
this.gainedPoints += gainedPoints
this.bot.logger.info(
this.bot.isMobile,
'QUIZ',
`ReportActivity ${i + 1}${response.status} | offerId=${offerId} | gainedPoints=${gainedPoints} | newBalance=${newBalance}`,
'green'
)
} else {
this.bot.logger.warn(
this.bot.isMobile,
'QUIZ',
`ReportActivity ${i + 1} | offerId=${offerId} | no more points gained, ending quiz | lastBalance=${newBalance}`
)
break
}
this.bot.logger.debug(
this.bot.isMobile,
'QUIZ',
`Waiting between ReportActivity attempts | attempt=${i + 1}/${maxAttempts} | offerId=${offerId}`
)
await this.bot.utils.wait(this.bot.utils.randomDelay(5000, 7000))
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'QUIZ',
`Error during ReportActivity | attempt=${i + 1}/${maxAttempts} | offerId=${offerId} | message=${error instanceof Error ? error.message : String(error)}`
)
break
}
}
this.bot.logger.info(
this.bot.isMobile,
'QUIZ',
`Completed the quiz successfully | offerId=${offerId} | attempts=${attempts} | totalGained=${totalGained} | startBalance=${startBalance} | finalBalance=${this.bot.userData.currentPoints}`
)
} else {
this.bot.logger.warn(
this.bot.isMobile,
'QUIZ',
`Unsupported quiz configuration | offerId=${offerId} | pointProgressMax=${promotion.pointProgressMax} | activityProgressMax=${promotion.activityProgressMax}`
)
}
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'QUIZ',
`Error in doQuiz | offerId=${promotion.offerId} | message=${error instanceof Error ? error.message : String(error)}`
)
}
}
}

View File

@@ -1,129 +0,0 @@
import type { AxiosRequestConfig } from 'axios'
import type { BasePromotion } from '../../../interface/DashboardData'
import { Workers } from '../../Workers'
export class UrlReward extends Workers {
private cookieHeader: string = ''
private fingerprintHeader: { [x: string]: string } = {}
private gainedPoints: number = 0
private oldBalance: number = this.bot.userData.currentPoints
public async doUrlReward(promotion: BasePromotion) {
if (!this.bot.requestToken) {
this.bot.logger.warn(
this.bot.isMobile,
'URL-REWARD',
'Skipping: Request token not available, this activity requires it!'
)
return
}
const offerId = promotion.offerId
this.bot.logger.info(
this.bot.isMobile,
'URL-REWARD',
`Starting UrlReward | offerId=${offerId} | geo=${this.bot.userData.geoLocale} | oldBalance=${this.oldBalance}`
)
try {
this.cookieHeader = (this.bot.isMobile ? this.bot.cookies.mobile : this.bot.cookies.desktop)
.map((c: { name: string; value: string }) => `${c.name}=${c.value}`)
.join('; ')
const fingerprintHeaders = { ...this.bot.fingerprint.headers }
delete fingerprintHeaders['Cookie']
delete fingerprintHeaders['cookie']
this.fingerprintHeader = fingerprintHeaders
this.bot.logger.debug(
this.bot.isMobile,
'URL-REWARD',
`Prepared UrlReward headers | offerId=${offerId} | cookieLength=${this.cookieHeader.length} | fingerprintHeaderKeys=${Object.keys(this.fingerprintHeader).length}`
)
const formData = new URLSearchParams({
id: offerId,
hash: promotion.hash,
timeZone: '60',
activityAmount: '1',
dbs: '0',
form: '',
type: '',
__RequestVerificationToken: this.bot.requestToken
})
this.bot.logger.debug(
this.bot.isMobile,
'URL-REWARD',
`Prepared UrlReward form data | offerId=${offerId} | hash=${promotion.hash} | timeZone=60 | activityAmount=1`
)
const request: AxiosRequestConfig = {
url: 'https://rewards.bing.com/api/reportactivity?X-Requested-With=XMLHttpRequest',
method: 'POST',
headers: {
...(this.bot.fingerprint?.headers ?? {}),
Cookie: this.cookieHeader,
Referer: 'https://rewards.bing.com/',
Origin: 'https://rewards.bing.com'
},
data: formData
}
this.bot.logger.debug(
this.bot.isMobile,
'URL-REWARD',
`Sending UrlReward request | offerId=${offerId} | url=${request.url}`
)
const response = await this.bot.axios.request(request)
this.bot.logger.debug(
this.bot.isMobile,
'URL-REWARD',
`Received UrlReward response | offerId=${offerId} | status=${response.status}`
)
const newBalance = await this.bot.browser.func.getCurrentPoints()
this.gainedPoints = newBalance - this.oldBalance
this.bot.logger.debug(
this.bot.isMobile,
'URL-REWARD',
`Balance delta after UrlReward | offerId=${offerId} | oldBalance=${this.oldBalance} | newBalance=${newBalance} | gainedPoints=${this.gainedPoints}`
)
if (this.gainedPoints > 0) {
this.bot.userData.currentPoints = newBalance
this.bot.userData.gainedPoints = (this.bot.userData.gainedPoints ?? 0) + this.gainedPoints
this.bot.logger.info(
this.bot.isMobile,
'URL-REWARD',
`Completed UrlReward | offerId=${offerId} | status=${response.status} | gainedPoints=${this.gainedPoints} | newBalance=${newBalance}`,
'green'
)
} else {
this.bot.logger.warn(
this.bot.isMobile,
'URL-REWARD',
`Failed UrlReward with no points | offerId=${offerId} | status=${response.status} | oldBalance=${this.oldBalance} | newBalance=${newBalance}`
)
}
this.bot.logger.debug(this.bot.isMobile, 'URL-REWARD', `Waiting after UrlReward | offerId=${offerId}`)
await this.bot.utils.wait(this.bot.utils.randomDelay(5000, 10000))
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'URL-REWARD',
`Error in doUrlReward | offerId=${promotion.offerId} | message=${error instanceof Error ? error.message : String(error)}`
)
}
}
}

View File

@@ -1,119 +0,0 @@
import type { AxiosRequestConfig } from 'axios'
import { randomUUID } from 'crypto'
import type { Promotion } from '../../../interface/AppDashBoardData'
import { Workers } from '../../Workers'
export class AppReward extends Workers {
private gainedPoints: number = 0
private oldBalance: number = this.bot.userData.currentPoints
public async doAppReward(promotion: Promotion) {
if (!this.bot.accessToken) {
this.bot.logger.warn(
this.bot.isMobile,
'APP-REWARD',
'Skipping: App access token not available, this activity requires it!'
)
return
}
const offerId = promotion.attributes['offerid']
this.bot.logger.info(
this.bot.isMobile,
'APP-REWARD',
`Starting AppReward | offerId=${offerId} | country=${this.bot.userData.geoLocale} | oldBalance=${this.oldBalance}`
)
try {
const jsonData = {
id: randomUUID(),
amount: 1,
type: 101,
attributes: {
offerid: offerId
},
country: this.bot.userData.geoLocale
}
this.bot.logger.debug(
this.bot.isMobile,
'APP-REWARD',
`Prepared activity payload | offerId=${offerId} | id=${jsonData.id} | amount=${jsonData.amount} | type=${jsonData.type} | country=${jsonData.country}`
)
const request: AxiosRequestConfig = {
url: 'https://prod.rewardsplatform.microsoft.com/dapi/me/activities',
method: 'POST',
headers: {
Authorization: `Bearer ${this.bot.accessToken}`,
'User-Agent':
'Bing/32.5.431027001 (com.microsoft.bing; build:431027001; iOS 17.6.1) Alamofire/5.10.2',
'Content-Type': 'application/json',
'X-Rewards-Country': this.bot.userData.geoLocale,
'X-Rewards-Language': 'en',
'X-Rewards-ismobile': 'true'
},
data: JSON.stringify(jsonData)
}
this.bot.logger.debug(
this.bot.isMobile,
'APP-REWARD',
`Sending activity request | offerId=${offerId} | url=${request.url}`
)
const response = await this.bot.axios.request(request)
this.bot.logger.debug(
this.bot.isMobile,
'APP-REWARD',
`Received activity response | offerId=${offerId} | status=${response.status}`
)
const newBalance = Number(response?.data?.response?.balance ?? this.oldBalance)
this.gainedPoints = newBalance - this.oldBalance
this.bot.logger.debug(
this.bot.isMobile,
'APP-REWARD',
`Balance delta after AppReward | offerId=${offerId} | oldBalance=${this.oldBalance} | newBalance=${newBalance} | gainedPoints=${this.gainedPoints}`
)
if (this.gainedPoints > 0) {
this.bot.userData.currentPoints = newBalance
this.bot.userData.gainedPoints = (this.bot.userData.gainedPoints ?? 0) + this.gainedPoints
this.bot.logger.info(
this.bot.isMobile,
'APP-REWARD',
`Completed AppReward | offerId=${offerId} | gainedPoints=${this.gainedPoints} | oldBalance=${this.oldBalance} | newBalance=${newBalance}`,
'green'
)
} else {
this.bot.logger.warn(
this.bot.isMobile,
'APP-REWARD',
`Completed AppReward with no points | offerId=${offerId} | oldBalance=${this.oldBalance} | newBalance=${newBalance}`
)
}
this.bot.logger.debug(this.bot.isMobile, 'APP-REWARD', `Waiting after AppReward | offerId=${offerId}`)
await this.bot.utils.wait(this.bot.utils.randomDelay(5000, 10000))
this.bot.logger.info(
this.bot.isMobile,
'APP-REWARD',
`Finished AppReward | offerId=${offerId} | finalBalance=${this.bot.userData.currentPoints}`
)
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'APP-REWARD',
`Error in doAppReward | offerId=${offerId} | message=${error instanceof Error ? error.message : String(error)}`
)
}
}
}

View File

@@ -1,161 +0,0 @@
import type { AxiosRequestConfig } from 'axios'
import { randomUUID } from 'crypto'
import { Workers } from '../../Workers'
export class DailyCheckIn extends Workers {
private gainedPoints: number = 0
private oldBalance: number = this.bot.userData.currentPoints
public async doDailyCheckIn() {
if (!this.bot.accessToken) {
this.bot.logger.warn(
this.bot.isMobile,
'DAILY-CHECK-IN',
'Skipping: App access token not available, this activity requires it!'
)
return
}
this.oldBalance = Number(this.bot.userData.currentPoints ?? 0)
this.bot.logger.info(
this.bot.isMobile,
'DAILY-CHECK-IN',
`Starting Daily Check-In | geo=${this.bot.userData.geoLocale} | currentPoints=${this.oldBalance}`
)
try {
// Try type 101 first
this.bot.logger.debug(this.bot.isMobile, 'DAILY-CHECK-IN', 'Attempting Daily Check-In | type=101')
let response = await this.submitDaily(101) // Try using 101 (EU Variant?)
this.bot.logger.debug(
this.bot.isMobile,
'DAILY-CHECK-IN',
`Received Daily Check-In response | type=101 | status=${response?.status ?? 'unknown'}`
)
let newBalance = Number(response?.data?.response?.balance ?? this.oldBalance)
this.gainedPoints = newBalance - this.oldBalance
this.bot.logger.debug(
this.bot.isMobile,
'DAILY-CHECK-IN',
`Balance delta after Daily Check-In | type=101 | oldBalance=${this.oldBalance} | newBalance=${newBalance} | gainedPoints=${this.gainedPoints}`
)
if (this.gainedPoints > 0) {
this.bot.userData.currentPoints = newBalance
this.bot.userData.gainedPoints = (this.bot.userData.gainedPoints ?? 0) + this.gainedPoints
this.bot.logger.info(
this.bot.isMobile,
'DAILY-CHECK-IN',
`Completed Daily Check-In | type=101 | gainedPoints=${this.gainedPoints} | oldBalance=${this.oldBalance} | newBalance=${newBalance}`,
'green'
)
return
}
this.bot.logger.debug(
this.bot.isMobile,
'DAILY-CHECK-IN',
`No points gained with type=101 | oldBalance=${this.oldBalance} | newBalance=${newBalance} | retryingWithType=103`
)
// Fallback to type 103
this.bot.logger.debug(this.bot.isMobile, 'DAILY-CHECK-IN', 'Attempting Daily Check-In | type=103')
response = await this.submitDaily(103) // Try using 103 (USA Variant?)
this.bot.logger.debug(
this.bot.isMobile,
'DAILY-CHECK-IN',
`Received Daily Check-In response | type=103 | status=${response?.status ?? 'unknown'}`
)
newBalance = Number(response?.data?.response?.balance ?? this.oldBalance)
this.gainedPoints = newBalance - this.oldBalance
this.bot.logger.debug(
this.bot.isMobile,
'DAILY-CHECK-IN',
`Balance delta after Daily Check-In | type=103 | oldBalance=${this.oldBalance} | newBalance=${newBalance} | gainedPoints=${this.gainedPoints}`
)
if (this.gainedPoints > 0) {
this.bot.userData.currentPoints = newBalance
this.bot.userData.gainedPoints = (this.bot.userData.gainedPoints ?? 0) + this.gainedPoints
this.bot.logger.info(
this.bot.isMobile,
'DAILY-CHECK-IN',
`Completed Daily Check-In | type=103 | gainedPoints=${this.gainedPoints} | oldBalance=${this.oldBalance} | newBalance=${newBalance}`,
'green'
)
} else {
this.bot.logger.warn(
this.bot.isMobile,
'DAILY-CHECK-IN',
`Daily Check-In completed but no points gained | typesTried=101,103 | oldBalance=${this.oldBalance} | finalBalance=${newBalance}`
)
}
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'DAILY-CHECK-IN',
`Error during Daily Check-In | message=${error instanceof Error ? error.message : String(error)}`
)
}
}
private async submitDaily(type: number) {
try {
const jsonData = {
id: randomUUID(),
amount: 1,
type: type,
attributes: {
offerid: 'Gamification_Sapphire_DailyCheckIn'
},
country: this.bot.userData.geoLocale
}
this.bot.logger.debug(
this.bot.isMobile,
'DAILY-CHECK-IN',
`Preparing Daily Check-In payload | type=${type} | id=${jsonData.id} | amount=${jsonData.amount} | country=${jsonData.country}`
)
const request: AxiosRequestConfig = {
url: 'https://prod.rewardsplatform.microsoft.com/dapi/me/activities',
method: 'POST',
headers: {
Authorization: `Bearer ${this.bot.accessToken}`,
'User-Agent':
'Bing/32.5.431027001 (com.microsoft.bing; build:431027001; iOS 17.6.1) Alamofire/5.10.2',
'Content-Type': 'application/json',
'X-Rewards-Country': this.bot.userData.geoLocale,
'X-Rewards-Language': 'en',
'X-Rewards-ismobile': 'true'
},
data: JSON.stringify(jsonData)
}
this.bot.logger.debug(
this.bot.isMobile,
'DAILY-CHECK-IN',
`Sending Daily Check-In request | type=${type} | url=${request.url}`
)
return this.bot.axios.request(request)
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'DAILY-CHECK-IN',
`Error in submitDaily | type=${type} | message=${error instanceof Error ? error.message : String(error)}`
)
throw error
}
}
}

View File

@@ -1,131 +0,0 @@
import type { AxiosRequestConfig } from 'axios'
import { randomBytes } from 'crypto'
import { Workers } from '../../Workers'
export class ReadToEarn extends Workers {
public async doReadToEarn() {
if (!this.bot.accessToken) {
this.bot.logger.warn(
this.bot.isMobile,
'READ-TO-EARN',
'Skipping: App access token not available, this activity requires it!'
)
return
}
const delayMin = this.bot.config.searchSettings.readDelay.min
const delayMax = this.bot.config.searchSettings.readDelay.max
const startBalance = Number(this.bot.userData.currentPoints ?? 0)
this.bot.logger.info(
this.bot.isMobile,
'READ-TO-EARN',
`Starting Read to Earn | geo=${this.bot.userData.geoLocale} | delayRange=${delayMin}-${delayMax} | currentPoints=${startBalance}`
)
try {
const jsonData = {
amount: 1,
id: '1',
type: 101,
attributes: {
offerid: 'ENUS_readarticle3_30points'
},
country: this.bot.userData.geoLocale
}
const articleCount = 10
let totalGained = 0
let articlesRead = 0
let oldBalance = startBalance
for (let i = 0; i < articleCount; ++i) {
jsonData.id = randomBytes(64).toString('hex')
this.bot.logger.debug(
this.bot.isMobile,
'READ-TO-EARN',
`Submitting Read to Earn activity | article=${i + 1}/${articleCount} | id=${jsonData.id} | country=${jsonData.country}`
)
const request: AxiosRequestConfig = {
url: 'https://prod.rewardsplatform.microsoft.com/dapi/me/activities',
method: 'POST',
headers: {
Authorization: `Bearer ${this.bot.accessToken}`,
'User-Agent':
'Bing/32.5.431027001 (com.microsoft.bing; build:431027001; iOS 17.6.1) Alamofire/5.10.2',
'Content-Type': 'application/json',
'X-Rewards-Country': this.bot.userData.geoLocale,
'X-Rewards-Language': 'en',
'X-Rewards-ismobile': 'true'
},
data: JSON.stringify(jsonData)
}
const response = await this.bot.axios.request(request)
this.bot.logger.debug(
this.bot.isMobile,
'READ-TO-EARN',
`Received Read to Earn response | article=${i + 1}/${articleCount} | status=${response?.status ?? 'unknown'}`
)
const newBalance = Number(response?.data?.response?.balance ?? oldBalance)
const gainedPoints = newBalance - oldBalance
this.bot.logger.debug(
this.bot.isMobile,
'READ-TO-EARN',
`Balance delta after article | article=${i + 1}/${articleCount} | oldBalance=${oldBalance} | newBalance=${newBalance} | gainedPoints=${gainedPoints}`
)
if (gainedPoints <= 0) {
this.bot.logger.info(
this.bot.isMobile,
'READ-TO-EARN',
`No points gained, stopping Read to Earn | article=${i + 1}/${articleCount} | status=${response.status} | oldBalance=${oldBalance} | newBalance=${newBalance}`
)
break
}
// Update point tracking
this.bot.userData.currentPoints = newBalance
this.bot.userData.gainedPoints = (this.bot.userData.gainedPoints ?? 0) + gainedPoints
totalGained += gainedPoints
articlesRead = i + 1
oldBalance = newBalance
this.bot.logger.info(
this.bot.isMobile,
'READ-TO-EARN',
`Read article ${i + 1}/${articleCount} | status=${response.status} | gainedPoints=${gainedPoints} | newBalance=${newBalance}`,
'green'
)
// Wait random delay between articles
this.bot.logger.debug(
this.bot.isMobile,
'READ-TO-EARN',
`Waiting between articles | article=${i + 1}/${articleCount} | delayRange=${delayMin}-${delayMax}`
)
await this.bot.utils.wait(this.bot.utils.randomDelay(delayMin, delayMax))
}
const finalBalance = Number(this.bot.userData.currentPoints ?? startBalance)
this.bot.logger.info(
this.bot.isMobile,
'READ-TO-EARN',
`Completed Read to Earn | articlesRead=${articlesRead} | totalGained=${totalGained} | startBalance=${startBalance} | finalBalance=${finalBalance}`
)
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'READ-TO-EARN',
`Error during Read to Earn | message=${error instanceof Error ? error.message : String(error)}`
)
}
}
}

View File

@@ -1,426 +0,0 @@
import type { Page } from 'patchright'
import type { Counters, DashboardData } from '../../../interface/DashboardData'
import { QueryCore } from '../../QueryEngine'
import { Workers } from '../../Workers'
export class Search extends Workers {
private bingHome = 'https://bing.com'
private searchPageURL = ''
private searchCount = 0
public async doSearch(data: DashboardData, page: Page, isMobile: boolean): Promise<number> {
const startBalance = Number(this.bot.userData.currentPoints ?? 0)
this.bot.logger.info(isMobile, 'SEARCH-BING', `Starting Bing searches | currentPoints=${startBalance}`)
let totalGainedPoints = 0
try {
let searchCounters: Counters = await this.bot.browser.func.getSearchPoints()
const missingPoints = this.bot.browser.func.missingSearchPoints(searchCounters, isMobile)
let missingPointsTotal = missingPoints.totalPoints
this.bot.logger.debug(
isMobile,
'SEARCH-BING',
`Initial search counters | mobile=${missingPoints.mobilePoints} | desktop=${missingPoints.desktopPoints} | edge=${missingPoints.edgePoints}`
)
this.bot.logger.info(
isMobile,
'SEARCH-BING',
`Search points remaining | Edge=${missingPoints.edgePoints} | Desktop=${missingPoints.desktopPoints} | Mobile=${missingPoints.mobilePoints}`
)
let queries: string[] = []
const queryCore = new QueryCore(this.bot)
const locale = this.bot.userData.geoLocale.toUpperCase()
this.bot.logger.debug(isMobile, 'SEARCH-BING', `Resolving search queries | locale=${locale}`)
// Set Google search queries
queries = await queryCore.getGoogleTrends(locale)
this.bot.logger.debug(isMobile, 'SEARCH-BING', `Fetched base queries | count=${queries.length}`)
// Deduplicate queries
queries = [...new Set(queries)]
this.bot.logger.debug(isMobile, 'SEARCH-BING', `Deduplicated queries | count=${queries.length}`)
// Shuffle
queries = this.bot.utils.shuffleArray(queries)
this.bot.logger.debug(isMobile, 'SEARCH-BING', `Shuffled queries | count=${queries.length}`)
// Go to bing
const targetUrl = this.searchPageURL ? this.searchPageURL : this.bingHome
this.bot.logger.debug(isMobile, 'SEARCH-BING', `Navigating to search page | url=${targetUrl}`)
await page.goto(targetUrl)
// Wait until page loaded
await page.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => {})
await this.bot.browser.utils.tryDismissAllMessages(page)
let stagnantLoop = 0
const stagnantLoopMax = 10
for (let i = 0; i < queries.length; i++) {
const query = queries[i] as string
searchCounters = await this.bingSearch(page, query, isMobile)
const newMissingPoints = this.bot.browser.func.missingSearchPoints(searchCounters, isMobile)
const newMissingPointsTotal = newMissingPoints.totalPoints
// Points gained for THIS query only
const rawGained = missingPointsTotal - newMissingPointsTotal
const gainedPoints = Math.max(0, rawGained)
if (gainedPoints === 0) {
stagnantLoop++
this.bot.logger.info(
isMobile,
'SEARCH-BING',
`No points gained ${stagnantLoop}/${stagnantLoopMax} | query="${query}" | remaining=${newMissingPointsTotal}`
)
} else {
stagnantLoop = 0
// Update global user data
const newBalance = Number(this.bot.userData.currentPoints ?? 0) + gainedPoints
this.bot.userData.currentPoints = newBalance
this.bot.userData.gainedPoints = (this.bot.userData.gainedPoints ?? 0) + gainedPoints
// Track for return value
totalGainedPoints += gainedPoints
this.bot.logger.info(
isMobile,
'SEARCH-BING',
`gainedPoints=${gainedPoints} points | query="${query}" | remaining=${newMissingPointsTotal}`,
'green'
)
}
// Update loop state
missingPointsTotal = newMissingPointsTotal
// Completed
if (missingPointsTotal === 0) {
this.bot.logger.info(
isMobile,
'SEARCH-BING',
'All required search points earned, stopping main search loop'
)
break
}
// Stuck
if (stagnantLoop > stagnantLoopMax) {
this.bot.logger.warn(
isMobile,
'SEARCH-BING',
`Search did not gain points for ${stagnantLoopMax} iterations, aborting main search loop`
)
stagnantLoop = 0
break
}
}
if (missingPointsTotal > 0) {
this.bot.logger.info(
isMobile,
'SEARCH-BING',
`Search completed but still missing points, generating extra searches | remaining=${missingPointsTotal}`
)
let i = 0
let stagnantLoop = 0
const stagnantLoopMax = 5
while (missingPointsTotal > 0) {
const query = queries[i++] as string
this.bot.logger.debug(
isMobile,
'SEARCH-BING-EXTRA',
`Fetching related terms for extra searches | baseQuery="${query}"`
)
const relatedTerms = await queryCore.getBingRelatedTerms(query)
this.bot.logger.debug(
isMobile,
'SEARCH-BING-EXTRA',
`Related terms resolved | baseQuery="${query}" | count=${relatedTerms.length}`
)
if (relatedTerms.length > 3) {
for (const term of relatedTerms.slice(1, 3)) {
this.bot.logger.info(
isMobile,
'SEARCH-BING-EXTRA',
`Extra search | remaining=${missingPointsTotal} | query="${term}"`
)
searchCounters = await this.bingSearch(page, term, isMobile)
const newMissingPoints = this.bot.browser.func.missingSearchPoints(searchCounters, isMobile)
const newMissingPointsTotal = newMissingPoints.totalPoints
// Points gained for THIS extra query only
const rawGained = missingPointsTotal - newMissingPointsTotal
const gainedPoints = Math.max(0, rawGained)
if (gainedPoints === 0) {
stagnantLoop++
this.bot.logger.info(
isMobile,
'SEARCH-BING-EXTRA',
`No points gained for extra query ${stagnantLoop}/${stagnantLoopMax} | query="${term}" | remaining=${newMissingPointsTotal}`
)
} else {
stagnantLoop = 0
// Update global user data
const newBalance = Number(this.bot.userData.currentPoints ?? 0) + gainedPoints
this.bot.userData.currentPoints = newBalance
this.bot.userData.gainedPoints = (this.bot.userData.gainedPoints ?? 0) + gainedPoints
// Track for return value
totalGainedPoints += gainedPoints
this.bot.logger.info(
isMobile,
'SEARCH-BING-EXTRA',
`gainedPoints=${gainedPoints} points | query="${term}" | remaining=${newMissingPointsTotal}`,
'green'
)
}
// Update loop state
missingPointsTotal = newMissingPointsTotal
// Completed
if (missingPointsTotal === 0) {
this.bot.logger.info(
isMobile,
'SEARCH-BING-EXTRA',
'All required search points earned during extra searches'
)
break
}
// Stuck again
if (stagnantLoop > stagnantLoopMax) {
this.bot.logger.warn(
isMobile,
'SEARCH-BING-EXTRA',
`Search did not gain points for ${stagnantLoopMax} extra iterations, aborting extra searches`
)
const finalBalance = Number(this.bot.userData.currentPoints ?? startBalance)
this.bot.logger.info(
isMobile,
'SEARCH-BING',
`Aborted extra searches | startBalance=${startBalance} | finalBalance=${finalBalance}`
)
return totalGainedPoints
}
}
}
}
}
const finalBalance = Number(this.bot.userData.currentPoints ?? startBalance)
this.bot.logger.info(
isMobile,
'SEARCH-BING',
`Completed Bing searches | startBalance=${startBalance} | newBalance=${finalBalance}`
)
return totalGainedPoints
} catch (error) {
this.bot.logger.error(
isMobile,
'SEARCH-BING',
`Error in doSearch | message=${error instanceof Error ? error.message : String(error)}`
)
return totalGainedPoints
}
}
private async bingSearch(searchPage: Page, query: string, isMobile: boolean) {
const maxAttempts = 5
const refreshThreshold = 10 // Page gets sluggish after x searches?
this.searchCount++
// Page fill seems to get more sluggish over time
if (this.searchCount % refreshThreshold === 0) {
this.bot.logger.info(
isMobile,
'SEARCH-BING',
`Returning to home page to clear accumulated page context | count=${this.searchCount} | threshold=${refreshThreshold}`
)
this.bot.logger.debug(isMobile, 'SEARCH-BING', `Returning home to refresh state | url=${this.bingHome}`)
await searchPage.goto(this.bingHome)
await searchPage.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => {})
await this.bot.browser.utils.tryDismissAllMessages(searchPage) // Not always the case but possible for new cookie headers
}
this.bot.logger.debug(
isMobile,
'SEARCH-BING',
`Starting bingSearch | query="${query}" | maxAttempts=${maxAttempts} | searchCount=${this.searchCount} | refreshEvery=${refreshThreshold} | scrollRandomResults=${this.bot.config.searchSettings.scrollRandomResults} | clickRandomResults=${this.bot.config.searchSettings.clickRandomResults}`
)
for (let i = 0; i < maxAttempts; i++) {
try {
const searchBar = '#sb_form_q'
const searchBox = searchPage.locator(searchBar)
await searchPage.evaluate(() => {
window.scrollTo({ left: 0, top: 0, behavior: 'auto' })
})
await searchPage.keyboard.press('Home')
await searchBox.waitFor({ state: 'visible', timeout: 15000 })
await this.bot.utils.wait(1000)
await this.bot.browser.utils.ghostClick(searchPage, searchBar, { clickCount: 3 })
await searchBox.fill('')
await searchPage.keyboard.type(query, { delay: 50 })
await searchPage.keyboard.press('Enter')
this.bot.logger.debug(
isMobile,
'SEARCH-BING',
`Submitted query to Bing | attempt=${i + 1}/${maxAttempts} | query="${query}"`
)
await this.bot.utils.wait(3000)
if (this.bot.config.searchSettings.scrollRandomResults) {
await this.bot.utils.wait(2000)
await this.randomScroll(searchPage, isMobile)
}
if (this.bot.config.searchSettings.clickRandomResults) {
await this.bot.utils.wait(2000)
await this.clickRandomLink(searchPage, isMobile)
}
await this.bot.utils.wait(
this.bot.utils.randomDelay(
this.bot.config.searchSettings.searchDelay.min,
this.bot.config.searchSettings.searchDelay.max
)
)
const counters = await this.bot.browser.func.getSearchPoints()
this.bot.logger.debug(
isMobile,
'SEARCH-BING',
`Search counters after query | attempt=${i + 1}/${maxAttempts} | query="${query}"`
)
return counters
} catch (error) {
if (i >= 5) {
this.bot.logger.error(
isMobile,
'SEARCH-BING',
`Failed after 5 retries | query="${query}" | message=${error instanceof Error ? error.message : String(error)}`
)
break
}
this.bot.logger.error(
isMobile,
'SEARCH-BING',
`Search attempt failed | attempt=${i + 1}/${maxAttempts} | query="${query}" | message=${error instanceof Error ? error.message : String(error)}`
)
this.bot.logger.warn(
isMobile,
'SEARCH-BING',
`Retrying search | attempt=${i + 1}/${maxAttempts} | query="${query}"`
)
await this.bot.utils.wait(2000)
}
}
this.bot.logger.debug(
isMobile,
'SEARCH-BING',
`Returning current search counters after failed retries | query="${query}"`
)
return await this.bot.browser.func.getSearchPoints()
}
private async randomScroll(page: Page, isMobile: boolean) {
try {
const viewportHeight = await page.evaluate(() => window.innerHeight)
const totalHeight = await page.evaluate(() => document.body.scrollHeight)
const randomScrollPosition = Math.floor(Math.random() * (totalHeight - viewportHeight))
this.bot.logger.debug(
isMobile,
'SEARCH-RANDOM-SCROLL',
`Random scroll | viewportHeight=${viewportHeight} | totalHeight=${totalHeight} | scrollPos=${randomScrollPosition}`
)
await page.evaluate((scrollPos: number) => {
window.scrollTo({ left: 0, top: scrollPos, behavior: 'auto' })
}, randomScrollPosition)
} catch (error) {
this.bot.logger.error(
isMobile,
'SEARCH-RANDOM-SCROLL',
`An error occurred during random scroll | message=${error instanceof Error ? error.message : String(error)}`
)
}
}
private async clickRandomLink(page: Page, isMobile: boolean) {
try {
this.bot.logger.debug(isMobile, 'SEARCH-RANDOM-CLICK', 'Attempting to click a random search result link')
const searchPageUrl = page.url()
await this.bot.browser.utils.ghostClick(page, '#b_results .b_algo h2')
await this.bot.utils.wait(this.bot.config.searchSettings.searchResultVisitTime)
if (isMobile) {
// Mobile
await page.goto(searchPageUrl)
this.bot.logger.debug(isMobile, 'SEARCH-RANDOM-CLICK', 'Navigated back to search page')
} else {
// Desktop
const newTab = await this.bot.browser.utils.getLatestTab(page)
const newTabUrl = newTab.url()
this.bot.logger.debug(isMobile, 'SEARCH-RANDOM-CLICK', `Visited result tab | url=${newTabUrl}`)
await this.bot.browser.utils.closeTabs(newTab)
this.bot.logger.debug(isMobile, 'SEARCH-RANDOM-CLICK', 'Closed result tab')
}
} catch (error) {
this.bot.logger.error(
isMobile,
'SEARCH-RANDOM-CLICK',
`An error occurred during random click | message=${error instanceof Error ? error.message : String(error)}`
)
}
}
}

View File

@@ -1,330 +0,0 @@
import type { AxiosRequestConfig } from 'axios'
import type { Page } from 'patchright'
import * as fs from 'fs'
import path from 'path'
import { Workers } from '../../Workers'
import { QueryCore } from '../../QueryEngine'
import type { BasePromotion } from '../../../interface/DashboardData'
export class SearchOnBing extends Workers {
private bingHome = 'https://bing.com'
private cookieHeader: string = ''
private fingerprintHeader: { [x: string]: string } = {}
private gainedPoints: number = 0
private success: boolean = false
private oldBalance: number = this.bot.userData.currentPoints
public async doSearchOnBing(promotion: BasePromotion, page: Page) {
const offerId = promotion.offerId
this.oldBalance = Number(this.bot.userData.currentPoints ?? 0)
this.bot.logger.info(
this.bot.isMobile,
'SEARCH-ON-BING',
`Starting SearchOnBing | offerId=${offerId} | title="${promotion.title}" | currentPoints=${this.oldBalance}`
)
try {
this.cookieHeader = (this.bot.isMobile ? this.bot.cookies.mobile : this.bot.cookies.desktop)
.map((c: { name: string; value: string }) => `${c.name}=${c.value}`)
.join('; ')
const fingerprintHeaders = { ...this.bot.fingerprint.headers }
delete fingerprintHeaders['Cookie']
delete fingerprintHeaders['cookie']
this.fingerprintHeader = fingerprintHeaders
this.bot.logger.debug(
this.bot.isMobile,
'SEARCH-ON-BING',
`Prepared headers for SearchOnBing | offerId=${offerId} | cookieLength=${this.cookieHeader.length} | fingerprintHeaderKeys=${Object.keys(this.fingerprintHeader).length}`
)
this.bot.logger.debug(this.bot.isMobile, 'SEARCH-ON-BING', `Activating search task | offerId=${offerId}`)
const activated = await this.activateSearchTask(promotion)
if (!activated) {
this.bot.logger.warn(
this.bot.isMobile,
'SEARCH-ON-BING',
`Search activity couldn't be activated, aborting | offerId=${offerId}`
)
return
}
// Do the bing search here
const queries = await this.getSearchQueries(promotion)
// Run through the queries
await this.searchBing(page, queries)
if (this.success) {
this.bot.logger.info(
this.bot.isMobile,
'SEARCH-ON-BING',
`Completed SearchOnBing | offerId=${offerId} | startBalance=${this.oldBalance} | finalBalance=${this.bot.userData.currentPoints}`
)
} else {
this.bot.logger.warn(
this.bot.isMobile,
'SEARCH-ON-BING',
`Failed SearchOnBing | offerId=${offerId} | startBalance=${this.oldBalance} | finalBalance=${this.bot.userData.currentPoints}`
)
}
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'SEARCH-ON-BING',
`Error in doSearchOnBing | offerId=${promotion.offerId} | message=${error instanceof Error ? error.message : String(error)}`
)
}
}
private async searchBing(page: Page, queries: string[]) {
queries = [...new Set(queries)]
this.bot.logger.debug(
this.bot.isMobile,
'SEARCH-ON-BING-SEARCH',
`Starting search loop | queriesCount=${queries.length} | oldBalance=${this.oldBalance}`
)
let i = 0
for (const query of queries) {
try {
this.bot.logger.debug(this.bot.isMobile, 'SEARCH-ON-BING-SEARCH', `Processing query | query="${query}"`)
await this.bot.mainMobilePage.goto(this.bingHome)
// Wait until page loaded
await page.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => {})
await this.bot.browser.utils.tryDismissAllMessages(page)
const searchBar = '#sb_form_q'
const searchBox = page.locator(searchBar)
await searchBox.waitFor({ state: 'attached', timeout: 15000 })
await this.bot.utils.wait(500)
await this.bot.browser.utils.ghostClick(page, searchBar, { clickCount: 3 })
await searchBox.fill('')
await page.keyboard.type(query, { delay: 50 })
await page.keyboard.press('Enter')
await this.bot.utils.wait(this.bot.utils.randomDelay(5000, 7000))
// Check for point updates
const newBalance = await this.bot.browser.func.getCurrentPoints()
this.gainedPoints = newBalance - this.oldBalance
this.bot.logger.debug(
this.bot.isMobile,
'SEARCH-ON-BING-SEARCH',
`Balance check after query | query="${query}" | oldBalance=${this.oldBalance} | newBalance=${newBalance} | gainedPoints=${this.gainedPoints}`
)
if (this.gainedPoints > 0) {
this.bot.userData.currentPoints = newBalance
this.bot.userData.gainedPoints = (this.bot.userData.gainedPoints ?? 0) + this.gainedPoints
this.bot.logger.info(
this.bot.isMobile,
'SEARCH-ON-BING-SEARCH',
`SearchOnBing query completed | query="${query}" | gainedPoints=${this.gainedPoints} | oldBalance=${this.oldBalance} | newBalance=${newBalance}`,
'green'
)
this.success = true
return
} else {
this.bot.logger.warn(
this.bot.isMobile,
'SEARCH-ON-BING-SEARCH',
`${++i}/${queries.length} | noPoints=1 | query="${query}"`
)
}
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'SEARCH-ON-BING-SEARCH',
`Error during search loop | query="${query}" | message=${error instanceof Error ? error.message : String(error)}`
)
} finally {
await this.bot.utils.wait(this.bot.utils.randomDelay(5000, 15000))
await page.goto(this.bot.config.baseURL, { timeout: 5000 }).catch(() => {})
}
}
this.bot.logger.warn(
this.bot.isMobile,
'SEARCH-ON-BING-SEARCH',
`Finished all queries with no points gained | queriesTried=${queries.length} | oldBalance=${this.oldBalance} | finalBalance=${this.bot.userData.currentPoints}`
)
}
// The task needs to be activated before being able to complete it
private async activateSearchTask(promotion: BasePromotion): Promise<boolean> {
try {
this.bot.logger.debug(
this.bot.isMobile,
'SEARCH-ON-BING-ACTIVATE',
`Preparing activation request | offerId=${promotion.offerId} | hash=${promotion.hash}`
)
const formData = new URLSearchParams({
id: promotion.offerId,
hash: promotion.hash,
timeZone: '60',
activityAmount: '1',
dbs: '0',
form: '',
type: '',
__RequestVerificationToken: this.bot.requestToken
})
const request: AxiosRequestConfig = {
url: 'https://rewards.bing.com/api/reportactivity?X-Requested-With=XMLHttpRequest',
method: 'POST',
headers: {
...(this.bot.fingerprint?.headers ?? {}),
Cookie: this.cookieHeader,
Referer: 'https://rewards.bing.com/',
Origin: 'https://rewards.bing.com'
},
data: formData
}
const response = await this.bot.axios.request(request)
this.bot.logger.info(
this.bot.isMobile,
'SEARCH-ON-BING-ACTIVATE',
`Successfully activated activity | status=${response.status} | offerId=${promotion.offerId}`
)
return true
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'SEARCH-ON-BING-ACTIVATE',
`Activation failed | offerId=${promotion.offerId} | message=${error instanceof Error ? error.message : String(error)}`
)
return false
}
}
private async getSearchQueries(promotion: BasePromotion): Promise<string[]> {
interface Queries {
title: string
queries: string[]
}
let queries: Queries[] = []
try {
if (this.bot.config.searchOnBingLocalQueries) {
this.bot.logger.debug(this.bot.isMobile, 'SEARCH-ON-BING-QUERY', 'Using local queries config file')
const data = fs.readFileSync(path.join(__dirname, '../queries.json'), 'utf8')
queries = JSON.parse(data)
this.bot.logger.debug(
this.bot.isMobile,
'SEARCH-ON-BING-QUERY',
`Loaded queries config | source=local | entries=${queries.length}`
)
} else {
this.bot.logger.debug(
this.bot.isMobile,
'SEARCH-ON-BING-QUERY',
'Fetching queries config from remote repository'
)
// Fetch from the repo directly so the user doesn't need to redownload the script for the new activities
const response = await this.bot.axios.request({
method: 'GET',
url: 'https://raw.githubusercontent.com/TheNetsky/Microsoft-Rewards-Script/refs/heads/v3/src/functions/queries.json'
})
queries = response.data
this.bot.logger.debug(
this.bot.isMobile,
'SEARCH-ON-BING-QUERY',
`Loaded queries config | source=remote | entries=${queries.length}`
)
}
const answers = queries.find(
x => this.bot.utils.normalizeString(x.title) === this.bot.utils.normalizeString(promotion.title)
)
if (answers && answers.queries.length > 0) {
const answer = this.bot.utils.shuffleArray(answers.queries)
this.bot.logger.info(
this.bot.isMobile,
'SEARCH-ON-BING-QUERY',
`Found answers for activity title | source=${this.bot.config.searchOnBingLocalQueries ? 'local' : 'remote'} | title="${promotion.title}" | answersCount=${answer.length} | firstQuery="${answer[0]}"`
)
return answer
} else {
this.bot.logger.info(
this.bot.isMobile,
'SEARCH-ON-BING-QUERY',
`No matching title in queries config | source=${this.bot.config.searchOnBingLocalQueries ? 'local' : 'remote'} | title="${promotion.title}"`
)
const queryCore = new QueryCore(this.bot)
const promotionDescription = promotion.description.toLowerCase().trim()
const queryDescription = promotionDescription.replace('search on bing', '').trim()
this.bot.logger.debug(
this.bot.isMobile,
'SEARCH-ON-BING-QUERY',
`Requesting Bing suggestions | queryDescription="${queryDescription}"`
)
const bingSuggestions = await queryCore.getBingSuggestions(queryDescription)
this.bot.logger.debug(
this.bot.isMobile,
'SEARCH-ON-BING-QUERY',
`Bing suggestions result | count=${bingSuggestions.length} | title="${promotion.title}"`
)
// If no suggestions found
if (!bingSuggestions.length) {
this.bot.logger.info(
this.bot.isMobile,
'SEARCH-ON-BING-QUERY',
`No suggestions found, falling back to activity title | title="${promotion.title}"`
)
return [promotion.title]
} else {
this.bot.logger.info(
this.bot.isMobile,
'SEARCH-ON-BING-QUERY',
`Using Bing suggestions as search queries | count=${bingSuggestions.length} | title="${promotion.title}"`
)
return bingSuggestions
}
}
} catch (error) {
this.bot.logger.error(
this.bot.isMobile,
'SEARCH-ON-BING-QUERY',
`Error while resolving search queries | title="${promotion.title}" | message=${error instanceof Error ? error.message : String(error)} | fallback=promotionTitle`
)
return [promotion.title]
}
}
}

View File

@@ -2,12 +2,7 @@
{
"title": "Houses near you",
"queries": [
"Houses near me",
"Homes for sale near me",
"Apartments near me",
"Real estate listings near me",
"Zillow homes near me",
"houses for rent near me"
"Houses near me"
]
},
{
@@ -15,10 +10,7 @@
"queries": [
"Rash on forearm",
"Stuffy nose",
"Tickling cough",
"sore throat remedies",
"headache and nausea causes",
"fever symptoms adults"
"Tickling cough"
]
},
{
@@ -26,12 +18,7 @@
"queries": [
"Buy PS5",
"Buy Xbox",
"Chair deals",
"wireless mouse deals",
"best gaming headset price",
"laptop deals",
"buy office chair",
"SSD deals"
"Chair deals"
]
},
{
@@ -39,21 +26,13 @@
"queries": [
"Translate welcome home to Korean",
"Translate welcome home to Japanese",
"Translate goodbye to Japanese",
"Translate good morning to Spanish",
"Translate thank you to French",
"Translate see you later to Italian"
"Translate goodbye to Japanese"
]
},
{
"title": "Search the lyrics of a song",
"queries": [
"Debarge rhythm of the night lyrics",
"bohemian rhapsody lyrics",
"hotel california lyrics",
"blinding lights lyrics",
"lose yourself lyrics",
"smells like teen spirit lyrics"
"Debarge rhythm of the night lyrics"
]
},
{
@@ -62,24 +41,14 @@
"Alien movie",
"Aliens movie",
"Alien 3 movie",
"Predator movie",
"Terminator movie",
"John Wick movie",
"Interstellar movie",
"The Matrix movie"
"Predator movie"
]
},
{
"title": "Plan a quick getaway",
"queries": [
"Flights Amsterdam to Tokyo",
"Flights New York to Tokyo",
"cheap flights to paris",
"flights amsterdam to rome",
"last minute flight deals",
"direct flights from amsterdam",
"weekend getaway europe",
"best time to visit tokyo"
"Flights New York to Tokyo"
]
},
{
@@ -88,22 +57,13 @@
"jobs at Microsoft",
"Microsoft Job Openings",
"Jobs near me",
"jobs at Boeing worked",
"software engineer jobs near me",
"remote developer jobs",
"IT jobs netherlands",
"customer support jobs near me"
"jobs at Boeing worked"
]
},
{
"title": "You can track your package",
"queries": [
"USPS tracking",
"UPS tracking",
"DHL tracking",
"FedEx tracking",
"track my package",
"international package tracking"
"USPS tracking"
]
},
{
@@ -111,12 +71,7 @@
"queries": [
"Directions to Berlin",
"Directions to Tokyo",
"Directions to New York",
"things to do in berlin",
"tourist attractions tokyo",
"best places to visit in new york",
"hidden gems near me",
"day trips near me"
"Directions to New York"
]
},
{
@@ -124,174 +79,67 @@
"queries": [
"KFC near me",
"Burger King near me",
"McDonalds near me",
"pizza delivery near me",
"restaurants open now",
"best takeout near me",
"quick dinner ideas",
"easy dinner recipes"
"McDonalds near me"
]
},
{
"title": "Quickly convert your money",
"queries": [
"convert 250 USD to yen",
"convert 500 USD to yen",
"usd to eur",
"gbp to eur",
"eur to jpy",
"currency converter",
"exchange rate today",
"1000 yen to euro"
"convert 500 USD to yen"
]
},
{
"title": "Learn to cook a new recipe",
"queries": [
"How to cook ratatouille",
"How to cook lasagna",
"easy pasta recipe",
"how to make pancakes",
"how to make fried rice",
"simple chicken recipe"
"How to cook lasagna"
]
},
{
"title": "Find places to stay!",
"queries": [
"Hotels Berlin Germany",
"Hotels Amsterdam Netherlands",
"hotels in paris",
"best hotels in tokyo",
"cheap hotels london",
"places to stay in barcelona",
"hotel deals",
"booking hotels near me"
"Hotels Amsterdam Netherlands"
]
},
{
"title": "How's the economy?",
"queries": [
"sp 500",
"nasdaq",
"dow jones today",
"inflation rate europe",
"interest rates today",
"stock market today",
"economic news",
"recession forecast"
"sp 500"
]
},
{
"title": "Who won?",
"queries": [
"braves score",
"champions league results",
"premier league results",
"nba score",
"formula 1 winner",
"latest football scores",
"ucl final winner",
"world cup final result"
"braves score"
]
},
{
"title": "Gaming time",
"queries": [
"Overwatch video game",
"Call of duty video game",
"best games 2025",
"top xbox games",
"popular steam games",
"new pc games",
"game reviews",
"best co-op games"
"Call of duty video game"
]
},
{
"title": "Expand your vocabulary",
"queries": [
"definition definition",
"meaning of serendipity",
"define nostalgia",
"synonym for happy",
"define eloquent",
"what does epiphany mean",
"word of the day",
"define immaculate"
"definition definition"
]
},
{
"title": "What time is it?",
"queries": [
"Japan time",
"New York time",
"time in london",
"time in tokyo",
"current time in amsterdam",
"time in los angeles"
]
},
{
"title": "Find deals on Bing",
"queries": [
"best laptop deals",
"tech deals today",
"wireless earbuds deals",
"gaming chair deals",
"discount codes electronics",
"best amazon deals today",
"smartphone deals",
"ssd deals"
]
},
{
"title": "Prepare for the weather",
"queries": [
"weather tomorrow",
"weekly weather forecast",
"rain forecast today",
"weather in amsterdam",
"storm forecast europe",
"uv index today",
"temperature this weekend",
"snow forecast"
]
},
{
"title": "Track your delivery",
"queries": [
"track my package",
"postnl track and trace",
"dhl parcel tracking",
"ups tracking",
"fedex tracking",
"usps tracking",
"parcel tracking",
"international package tracking"
]
},
{
"title": "Explore a new spot today",
"queries": [
"places to visit near me",
"things to do near me",
"hidden gems netherlands",
"best museums near me",
"parks near me",
"tourist attractions nearby",
"best cafes near me",
"day trip ideas"
"New York time"
]
},
{
"title": "Maisons près de chez vous",
"queries": [
"Maisons près de chez moi",
"Maisons à vendre près de chez moi",
"Appartements près de chez moi",
"Annonces immobilières près de chez moi",
"Maisons à louer près de chez moi"
"Maisons près de chez moi"
]
},
{
@@ -299,10 +147,7 @@
"queries": [
"Éruption cutanée sur l'avant-bras",
"Nez bouché",
"Toux chatouilleuse",
"mal de gorge remèdes",
"maux de tête causes",
"symptômes de la grippe"
"Toux chatouilleuse"
]
},
{
@@ -310,12 +155,7 @@
"queries": [
"Acheter une PS5",
"Acheter une Xbox",
"Offres sur les chaises",
"offres ordinateur portable",
"meilleures offres casque",
"acheter souris sans fil",
"promotions ssd",
"bons plans tech"
"Offres sur les chaises"
]
},
{
@@ -323,21 +163,13 @@
"queries": [
"Traduction bienvenue à la maison en coréen",
"Traduction bienvenue à la maison en japonais",
"Traduction au revoir en japonais",
"Traduire bonjour en espagnol",
"Traduire merci en anglais",
"Traduire à plus tard en italien"
"Traduction au revoir en japonais"
]
},
{
"title": "Rechercher paroles de chanson",
"queries": [
"Paroles de Debarge rhythm of the night",
"paroles bohemian rhapsody",
"paroles hotel california",
"paroles blinding lights",
"paroles lose yourself",
"paroles smells like teen spirit"
"Paroles de Debarge rhythm of the night"
]
},
{
@@ -346,23 +178,14 @@
"Alien film",
"Film Aliens",
"Film Alien 3",
"Film Predator",
"Film Terminator",
"Film John Wick",
"Film Interstellar",
"Film Matrix"
"Film Predator"
]
},
{
"title": "Planifiez une petite escapade",
"queries": [
"Vols Amsterdam-Tokyo",
"Vols New York-Tokyo",
"vols pas chers paris",
"vols amsterdam rome",
"offres vols dernière minute",
"week-end en europe",
"vols directs depuis amsterdam"
"Vols New York-Tokyo"
]
},
{
@@ -371,21 +194,13 @@
"emplois chez Microsoft",
"Offres d'emploi Microsoft",
"Emplois près de chez moi",
"emplois chez Boeing",
"emplois développeur à distance",
"emplois informatique pays-bas",
"offres d'emploi près de chez moi"
"emplois chez Boeing"
]
},
{
"title": "Vous pouvez suivre votre colis",
"queries": [
"Suivi Chronopost",
"suivi colis",
"suivi DHL",
"suivi UPS",
"suivi FedEx",
"suivi international colis"
"Suivi Chronopost"
]
},
{
@@ -393,11 +208,7 @@
"queries": [
"Itinéraire vers Berlin",
"Itinéraire vers Tokyo",
"Itinéraire vers New York",
"que faire à berlin",
"attractions tokyo",
"meilleurs endroits à visiter à new york",
"endroits à visiter près de chez moi"
"Itinéraire vers New York"
]
},
{
@@ -405,178 +216,74 @@
"queries": [
"KFC près de chez moi",
"Burger King près de chez moi",
"McDonalds près de chez moi",
"livraison pizza près de chez moi",
"restaurants ouverts maintenant",
"idées dîner rapide",
"quoi manger ce soir"
"McDonalds près de chez moi"
]
},
{
"title": "Convertissez rapidement votre argent",
"queries": [
"convertir 250 EUR en yen",
"convertir 500 EUR en yen",
"usd en eur",
"gbp en eur",
"eur en jpy",
"convertisseur de devises",
"taux de change aujourd'hui",
"1000 yen en euro"
"convertir 500 EUR en yen"
]
},
{
"title": "Apprenez à cuisiner une nouvelle recette",
"queries": [
"Comment faire cuire la ratatouille",
"Comment faire cuire les lasagnes",
"recette pâtes facile",
"comment faire des crêpes",
"recette riz sauté",
"recette poulet simple"
"Comment faire cuire les lasagnes"
]
},
{
"title": "Trouvez des emplacements pour rester!",
"queries": [
"Hôtels Berlin Allemagne",
"Hôtels Amsterdam Pays-Bas",
"hôtels paris",
"meilleurs hôtels tokyo",
"hôtels pas chers londres",
"hébergement barcelone",
"offres hôtels",
"hôtels près de chez moi"
"Hôtels Amsterdam Pays-Bas"
]
},
{
"title": "Comment se porte l'économie ?",
"queries": [
"CAC 40",
"indice dax",
"dow jones aujourd'hui",
"inflation europe",
"taux d'intérêt aujourd'hui",
"marché boursier aujourd'hui",
"actualités économie",
"prévisions récession"
"CAC 40"
]
},
{
"title": "Qui a gagné ?",
"queries": [
"score du Paris Saint-Germain",
"résultats ligue des champions",
"résultats premier league",
"score nba",
"vainqueur formule 1",
"derniers scores football",
"vainqueur finale ldc"
"score du Paris Saint-Germain"
]
},
{
"title": "Temps de jeu",
"queries": [
"Jeu vidéo Overwatch",
"Jeu vidéo Call of Duty",
"meilleurs jeux 2025",
"top jeux xbox",
"jeux steam populaires",
"nouveaux jeux pc",
"avis jeux vidéo",
"meilleurs jeux coop"
"Jeu vidéo Call of Duty"
]
},
{
"title": "Enrichissez votre vocabulaire",
"queries": [
"definition definition",
"signification sérendipité",
"définir nostalgie",
"synonyme heureux",
"définir éloquent",
"mot du jour",
"que veut dire épiphanie"
"definition definition"
]
},
{
"title": "Quelle heure est-il ?",
"queries": [
"Heure du Japon",
"Heure de New York",
"heure de londres",
"heure de tokyo",
"heure actuelle amsterdam",
"heure de los angeles"
"Heure de New York"
]
},
{
"title": "Vérifier la météo",
"queries": [
"Météo de Paris",
"Météo de la France",
"météo demain",
"prévisions météo semaine",
"météo amsterdam",
"risque de pluie aujourd'hui"
"Météo de la France"
]
},
{
"title": "Tenez-vous informé des sujets d'actualité",
"queries": [
"Augmentation Impots",
"Mort célébrité",
"actualités france",
"actualité internationale",
"dernières nouvelles économie",
"news technologie"
]
},
{
"title": "Préparez-vous pour la météo",
"queries": [
"météo demain",
"prévisions météo semaine",
"météo amsterdam",
"risque de pluie aujourd'hui",
"indice uv aujourd'hui",
"température ce week-end",
"alerte tempête"
]
},
{
"title": "Suivez votre livraison",
"queries": [
"suivi colis",
"postnl suivi colis",
"suivi DHL colis",
"suivi UPS",
"suivi FedEx",
"suivi international colis",
"suivre ma livraison"
]
},
{
"title": "Trouvez des offres sur Bing",
"queries": [
"meilleures offres ordinateur portable",
"bons plans tech",
"promotions écouteurs",
"offres chaise gamer",
"codes promo électronique",
"meilleures offres amazon aujourd'hui"
]
},
{
"title": "Explorez un nouvel endroit aujourd'hui",
"queries": [
"endroits à visiter près de chez moi",
"que faire près de chez moi",
"endroits insolites pays-bas",
"meilleurs musées près de chez moi",
"parcs près de chez moi",
"attractions touristiques à proximité",
"meilleurs cafés près de chez moi"
"Mort célébrité"
]
}
]
]

File diff suppressed because it is too large Load Diff

View File

@@ -1,15 +1,19 @@
export interface Account {
email: string
password: string
totp?: string
geoLocale: 'auto' | string
proxy: AccountProxy
/** Enable/disable this account (if false, account will be skipped during execution) */
enabled?: boolean;
email: string;
password: string;
/** Optional TOTP secret in Base32 (e.g., from Microsoft Authenticator setup) */
totp?: string;
/** Optional recovery email used to verify masked address on Microsoft login screens */
recoveryEmail?: string;
proxy: AccountProxy;
}
export interface AccountProxy {
proxyAxios: boolean
url: string
port: number
password: string
username: string
}
proxyAxios: boolean;
url: string;
port: number;
password: string;
username: string;
}

View File

@@ -0,0 +1,21 @@
import type { MorePromotion, PromotionalItem } from './DashboardData'
import type { Page } from 'playwright'
/**
* Activity handler contract for solving a single dashboard activity.
* Implementations should be stateless (or hold only a reference to the bot)
* and perform all required steps on the provided page.
*/
export interface ActivityHandler {
/** Optional identifier for diagnostics */
id?: string
/**
* Return true if this handler knows how to process the given activity.
*/
canHandle(activity: MorePromotion | PromotionalItem): boolean
/**
* Execute the activity on the provided page. The page is already
* navigated to the activity tab/window by the caller.
*/
run(page: Page, activity: MorePromotion | PromotionalItem): Promise<void>
}

View File

@@ -1,105 +0,0 @@
export interface AppDashboardData {
response: Response
correlationId: string
code: number
}
export interface Response {
profile: Profile
balance: number
counters: null
promotions: Promotion[]
catalog: null
goal_item: GoalItem
activities: null
cashback: null
orders: unknown[]
rebateProfile: null
rebatePayouts: null
giveProfile: null
autoRedeemProfile: null
autoRedeemItem: null
thirdPartyProfile: null
notifications: null
waitlist: null
autoOpenFlyout: null
coupons: null
recommendedAffordableCatalog: null
generativeAICreditsBalance: null
requestCountryCatalog: null
donationCatalog: null
}
export interface GoalItem {
name: string
provider: string
price: number
attributes: GoalItemAttributes
config: Config
}
export interface GoalItemAttributes {
category: string
CategoryDescription: string
'desc.group_text': string
'desc.legal_text': string
'desc.sc_description': string
'desc.sc_title': string
display_order: string
ExtraLargeImage: string
group: string
group_image: string
group_sc_image: string
group_title: string
hidden: string
large_image: string
large_sc_image: string
medium_image: string
MobileImage: string
original_price: string
points_destination: string
points_source: string
Remarks: string
ShortText: string
showcase: string
small_image: string
title: string
cimsid: string
user_defined_goal: string
}
export interface Config {
isHidden: string
}
export interface Profile {
ruid: string
attributes: ProfileAttributes
offline_attributes: OfflineAttributes
}
export interface ProfileAttributes {
ismsaautojoined: string
created: Date
creative: string
publisher: string
program: string
country: string
target: string
epuid: string
level: string
level_upd: Date
iris_segmentation: string
iris_segmentation_upd: Date
waitlistattributes: string
waitlistattributes_upd: Date
}
export interface OfflineAttributes {}
export interface Promotion {
name: string
priority: number
attributes: { [key: string]: string }
tags: string[]
}

View File

@@ -1,151 +1,151 @@
export interface AppUserData {
response: Response
correlationId: string
code: number
response: Response;
correlationId: string;
code: number;
}
export interface Response {
profile: Profile
balance: number
counters: null
promotions: Promotion[]
catalog: null
goal_item: GoalItem
activities: null
cashback: null
orders: Order[]
rebateProfile: null
rebatePayouts: null
giveProfile: GiveProfile
autoRedeemProfile: null
autoRedeemItem: null
thirdPartyProfile: null
notifications: null
waitlist: null
autoOpenFlyout: null
coupons: null
recommendedAffordableCatalog: null
profile: Profile;
balance: number;
counters: null;
promotions: Promotion[];
catalog: null;
goal_item: GoalItem;
activities: null;
cashback: null;
orders: Order[];
rebateProfile: null;
rebatePayouts: null;
giveProfile: GiveProfile;
autoRedeemProfile: null;
autoRedeemItem: null;
thirdPartyProfile: null;
notifications: null;
waitlist: null;
autoOpenFlyout: null;
coupons: null;
recommendedAffordableCatalog: null;
}
export interface GiveProfile {
give_user: string
give_organization: { [key: string]: GiveOrganization | null }
first_give_optin: string
last_give_optout: string
give_lifetime_balance: string
give_lifetime_donation_balance: string
give_balance: string
form: null
give_user: string;
give_organization: { [key: string]: GiveOrganization | null };
first_give_optin: string;
last_give_optout: string;
give_lifetime_balance: string;
give_lifetime_donation_balance: string;
give_balance: string;
form: null;
}
export interface GiveOrganization {
give_organization_donation_points: number
give_organization_donation_point_to_currency_ratio: number
give_organization_donation_currency: number
give_organization_donation_points: number;
give_organization_donation_point_to_currency_ratio: number;
give_organization_donation_currency: number;
}
export interface GoalItem {
name: string
provider: string
price: number
attributes: GoalItemAttributes
config: GoalItemConfig
name: string;
provider: string;
price: number;
attributes: GoalItemAttributes;
config: GoalItemConfig;
}
export interface GoalItemAttributes {
category: string
CategoryDescription: string
'desc.group_text': string
'desc.legal_text'?: string
'desc.sc_description': string
'desc.sc_title': string
display_order: string
ExtraLargeImage: string
group: string
group_image: string
group_sc_image: string
group_title: string
hidden?: string
large_image: string
large_sc_image: string
medium_image: string
MobileImage: string
original_price: string
Remarks?: string
ShortText?: string
showcase?: string
small_image: string
title: string
cimsid: string
user_defined_goal?: string
disable_bot_redemptions?: string
'desc.large_text'?: string
english_title?: string
etid?: string
sku?: string
coupon_discount?: string
category: string;
CategoryDescription: string;
'desc.group_text': string;
'desc.legal_text'?: string;
'desc.sc_description': string;
'desc.sc_title': string;
display_order: string;
ExtraLargeImage: string;
group: string;
group_image: string;
group_sc_image: string;
group_title: string;
hidden?: string;
large_image: string;
large_sc_image: string;
medium_image: string;
MobileImage: string;
original_price: string;
Remarks?: string;
ShortText?: string;
showcase?: string;
small_image: string;
title: string;
cimsid: string;
user_defined_goal?: string;
disable_bot_redemptions?: string;
'desc.large_text'?: string;
english_title?: string;
etid?: string;
sku?: string;
coupon_discount?: string;
}
export interface GoalItemConfig {
amount: string
currencyCode: string
isHidden: string
PointToCurrencyConversionRatio: string
amount: string;
currencyCode: string;
isHidden: string;
PointToCurrencyConversionRatio: string;
}
export interface Order {
id: string
t: Date
sku: string
item_snapshot: ItemSnapshot
p: number
s: S
a: A
child_redemption: null
third_party_partner: null
log: Log[]
id: string;
t: Date;
sku: string;
item_snapshot: ItemSnapshot;
p: number;
s: S;
a: A;
child_redemption: null;
third_party_partner: null;
log: Log[];
}
export interface A {
form?: string
OrderId: string
CorrelationId: string
Channel: string
Language: string
Country: string
EvaluationId: string
provider?: string
referenceOrderID?: string
externalRefID?: string
denomination?: string
rewardName?: string
sendEmail?: string
status?: string
createdAt?: Date
bal_before_deduct?: string
bal_after_deduct?: string
form?: string;
OrderId: string;
CorrelationId: string;
Channel: string;
Language: string;
Country: string;
EvaluationId: string;
provider?: string;
referenceOrderID?: string;
externalRefID?: string;
denomination?: string;
rewardName?: string;
sendEmail?: string;
status?: string;
createdAt?: Date;
bal_before_deduct?: string;
bal_after_deduct?: string;
}
export interface ItemSnapshot {
name: string
provider: string
price: number
attributes: GoalItemAttributes
config: ItemSnapshotConfig
name: string;
provider: string;
price: number;
attributes: GoalItemAttributes;
config: ItemSnapshotConfig;
}
export interface ItemSnapshotConfig {
amount: string
countryCode: string
currencyCode: string
sku: string
amount: string;
countryCode: string;
currencyCode: string;
sku: string;
}
export interface Log {
time: Date
from: From
to: S
reason: string
time: Date;
from: From;
to: S;
reason: string;
}
export enum From {
@@ -162,57 +162,58 @@ export enum S {
}
export interface Profile {
ruid: string
attributes: ProfileAttributes
offline_attributes: OfflineAttributes
ruid: string;
attributes: ProfileAttributes;
offline_attributes: OfflineAttributes;
}
export interface ProfileAttributes {
publisher: string
publisher_upd: Date
creative: string
creative_upd: Date
program: string
program_upd: Date
country: string
country_upd: Date
referrerhash: string
referrerhash_upd: Date
optout_upd: Date
language: string
language_upd: Date
target: string
target_upd: Date
created: Date
created_upd: Date
epuid: string
epuid_upd: Date
goal: string
goal_upd: Date
waitlistattributes: string
waitlistattributes_upd: Date
serpbotscore_upd: Date
iscashbackeligible: string
cbedc: string
rlscpct_upd: Date
give_user: string
rebcpc_upd: Date
SerpBotScore_upd: Date
AdsBotScore_upd: Date
dbs_upd: Date
rbs: string
rbs_upd: Date
iris_segmentation: string
iris_segmentation_upd: Date
publisher: string;
publisher_upd: Date;
creative: string;
creative_upd: Date;
program: string;
program_upd: Date;
country: string;
country_upd: Date;
referrerhash: string;
referrerhash_upd: Date;
optout_upd: Date;
language: string;
language_upd: Date;
target: string;
target_upd: Date;
created: Date;
created_upd: Date;
epuid: string;
epuid_upd: Date;
goal: string;
goal_upd: Date;
waitlistattributes: string;
waitlistattributes_upd: Date;
serpbotscore_upd: Date;
iscashbackeligible: string;
cbedc: string;
rlscpct_upd: Date;
give_user: string;
rebcpc_upd: Date;
SerpBotScore_upd: Date;
AdsBotScore_upd: Date;
dbs_upd: Date;
rbs: string;
rbs_upd: Date;
iris_segmentation: string;
iris_segmentation_upd: Date;
}
export interface OfflineAttributes {}
export interface OfflineAttributes {
}
export interface Promotion {
name: string
priority: number
attributes: { [key: string]: string }
tags: Tag[]
name: string;
priority: number;
attributes: { [key: string]: string };
tags: Tag[];
}
export enum Tag {

View File

@@ -1,81 +1,174 @@
export interface Config {
baseURL: string
sessionPath: string
headless: boolean
runOnZeroPoints: boolean
clusters: number
errorDiagnostics: boolean
saveFingerprint: ConfigSaveFingerprint
workers: ConfigWorkers
searchOnBingLocalQueries: boolean
globalTimeout: number | string
searchSettings: ConfigSearchSettings
debugLogs: boolean
proxy: ConfigProxy
consoleLogFilter: LogFilter
webhook: ConfigWebhook
baseURL: string;
sessionPath: string;
headless: boolean;
browser?: ConfigBrowser; // Optional nested browser config
fingerprinting?: ConfigFingerprinting; // Optional nested fingerprinting config
parallel: boolean;
runOnZeroPoints: boolean;
clusters: number;
saveFingerprint: ConfigSaveFingerprint;
workers: ConfigWorkers;
searchOnBingLocalQueries: boolean;
globalTimeout: number | string;
searchSettings: ConfigSearchSettings;
humanization?: ConfigHumanization; // Anti-ban humanization controls
retryPolicy?: ConfigRetryPolicy; // Global retry/backoff policy
jobState?: ConfigJobState; // Persistence of per-activity checkpoints
logExcludeFunc: string[];
webhookLogExcludeFunc: string[];
logging?: ConfigLogging; // Preserve original logging object (for live webhook settings)
proxy: ConfigProxy;
webhook: ConfigWebhook;
conclusionWebhook?: ConfigWebhook; // Optional secondary webhook for final summary
ntfy: ConfigNtfy;
vacation?: ConfigVacation; // Optional monthly contiguous off-days
crashRecovery?: ConfigCrashRecovery; // Automatic restart / graceful shutdown
riskManagement?: ConfigRiskManagement; // NEW: Risk-aware throttling and ban prediction
dryRun?: boolean; // NEW: Dry-run mode (simulate without executing)
queryDiversity?: ConfigQueryDiversity; // NEW: Multi-source query generation
}
export interface ConfigSaveFingerprint {
mobile: boolean
desktop: boolean
mobile: boolean;
desktop: boolean;
}
export interface ConfigBrowser {
headless?: boolean;
globalTimeout?: number | string;
}
export interface ConfigFingerprinting {
saveFingerprint?: ConfigSaveFingerprint;
}
export interface ConfigSearchSettings {
scrollRandomResults: boolean
clickRandomResults: boolean
parallelSearching: boolean
searchResultVisitTime: number | string
searchDelay: ConfigDelay
readDelay: ConfigDelay
useGeoLocaleQueries: boolean;
scrollRandomResults: boolean;
clickRandomResults: boolean;
searchDelay: ConfigSearchDelay;
retryMobileSearchAmount: number;
localFallbackCount?: number; // Number of local fallback queries to sample when trends fail
extraFallbackRetries?: number; // Additional mini-retry loops with fallback terms
}
export interface ConfigDelay {
min: number | string
max: number | string
export interface ConfigSearchDelay {
min: number | string;
max: number | string;
}
export interface ConfigWebhook {
enabled: boolean;
url: string;
username?: string; // Custom webhook username (default: "Microsoft Rewards")
avatarUrl?: string; // Custom webhook avatar URL
}
export interface ConfigNtfy {
enabled: boolean;
url: string;
topic: string;
authToken?: string; // Optional authentication token
}
export interface ConfigProxy {
queryEngine: boolean
proxyGoogleTrends: boolean;
proxyBingTerms: boolean;
}
export interface ConfigVacation {
enabled?: boolean; // default false
minDays?: number; // default 3
maxDays?: number; // default 5
}
export interface ConfigCrashRecovery {
autoRestart?: boolean; // Restart the root process after fatal crash
maxRestarts?: number; // Max restart attempts (default 2)
backoffBaseMs?: number; // Base backoff before restart (default 2000)
restartFailedWorker?: boolean; // (future) attempt to respawn crashed worker
restartFailedWorkerAttempts?: number; // attempts per worker (default 1)
}
export interface ConfigWorkers {
doDailySet: boolean
doMorePromotions: boolean
doPunchCards: boolean
doAppPromotions: boolean
doDesktopSearch: boolean
doMobileSearch: boolean
doDailyCheckIn: boolean
doReadToEarn: boolean
doDailySet: boolean;
doMorePromotions: boolean;
doPunchCards: boolean;
doDesktopSearch: boolean;
doMobileSearch: boolean;
doDailyCheckIn: boolean;
doReadToEarn: boolean;
bundleDailySetWithSearch?: boolean; // If true, run desktop search right after Daily Set
}
// Webhooks
export interface ConfigWebhook {
discord?: WebhookDiscordConfig
ntfy?: WebhookNtfyConfig
webhookLogFilter: LogFilter
// Anti-ban humanization
export interface ConfigHumanization {
// Master toggle for Human Mode. When false, humanization is minimized.
enabled?: boolean;
// If true, stop processing remaining accounts after a ban is detected
stopOnBan?: boolean;
// If true, send an immediate webhook/NTFY alert when a ban is detected
immediateBanAlert?: boolean;
// Additional random waits between actions
actionDelay?: { min: number | string; max: number | string };
// Probability [0..1] to perform micro mouse moves per step
gestureMoveProb?: number;
// Probability [0..1] to perform tiny scrolls per step
gestureScrollProb?: number;
// Allowed execution windows (local time). Each item is "HH:mm-HH:mm".
// If provided, runs outside these windows will be delayed until the next allowed window.
allowedWindows?: string[];
// Randomly skip N days per week to look more human (0-7). Default 1.
randomOffDaysPerWeek?: number;
}
export interface LogFilter {
enabled: boolean
mode: 'whitelist' | 'blacklist'
levels?: Array<'debug' | 'info' | 'warn' | 'error'>
keywords?: string[]
regexPatterns?: string[]
// Retry/backoff policy
export interface ConfigRetryPolicy {
maxAttempts?: number; // default 3
baseDelay?: number | string; // default 1000ms
maxDelay?: number | string; // default 30s
multiplier?: number; // default 2
jitter?: number; // 0..1; default 0.2
}
export interface WebhookDiscordConfig {
enabled: boolean
url: string
// Job state persistence
export interface ConfigJobState {
enabled?: boolean; // default true
dir?: string; // base directory; defaults to <sessionPath>/job-state
}
export interface WebhookNtfyConfig {
enabled?: boolean
url: string
topic?: string
token?: string
title?: string
tags?: string[]
priority?: 1 | 2 | 3 | 4 | 5 // 5 highest (important)
// Live logging configuration
export interface ConfigLoggingLive {
enabled?: boolean; // master switch for live webhook logs
redactEmails?: boolean; // if true, redact emails in outbound logs
}
export interface ConfigLogging {
excludeFunc?: string[];
webhookExcludeFunc?: string[];
live?: ConfigLoggingLive;
liveWebhookUrl?: string; // legacy/dedicated live webhook override
redactEmails?: boolean; // legacy top-level redaction flag
// Optional nested live.url support (already handled dynamically in Logger)
[key: string]: unknown; // forward compatibility
}
// CommunityHelp removed (privacy-first policy)
// NEW FEATURES: Risk Management, Query Diversity
export interface ConfigRiskManagement {
enabled?: boolean; // master toggle for risk-aware throttling
autoAdjustDelays?: boolean; // automatically increase delays when risk is high
stopOnCritical?: boolean; // halt execution if risk reaches critical level
banPrediction?: boolean; // enable ML-style ban prediction
riskThreshold?: number; // 0-100, pause if risk exceeds this
}
export interface ConfigQueryDiversity {
enabled?: boolean; // use multi-source query generation
sources?: Array<'google-trends' | 'reddit' | 'news' | 'wikipedia' | 'local-fallback'>; // which sources to use
maxQueriesPerSource?: number; // limit per source
cacheMinutes?: number; // cache duration
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,44 @@
export interface GoogleTrends {
default: Default;
}
export interface Default {
trendingSearchesDays: TrendingSearchesDay[];
endDateForNextRequest: string;
rssFeedPageUrl: string;
}
export interface TrendingSearchesDay {
date: string;
formattedDate: string;
trendingSearches: TrendingSearch[];
}
export interface TrendingSearch {
title: Title;
formattedTraffic: string;
relatedQueries: Title[];
image: Image;
articles: Article[];
shareUrl: string;
}
export interface Article {
title: string;
timeAgo: string;
source: string;
image?: Image;
url: string;
snippet: string;
}
export interface Image {
newsUrl: string;
source: string;
imageUrl: string;
}
export interface Title {
query: string;
exploreLink: string;
}

View File

@@ -1,9 +1,9 @@
export interface OAuth {
access_token: string
refresh_token: string
scope: string
expires_in: number
ext_expires_in: number
foci: string
token_type: string
}
access_token: string;
refresh_token: string;
scope: string;
expires_in: number;
ext_expires_in: number;
foci: string;
token_type: string;
}

View File

@@ -1,20 +1,7 @@
export interface BrowserEarnablePoints {
export interface EarnablePoints {
desktopSearchPoints: number
mobileSearchPoints: number
dailySetPoints: number
morePromotionsPoints: number
totalEarnablePoints: number
}
export interface AppEarnablePoints {
readToEarn: number
checkIn: number
totalEarnablePoints: number
}
export interface MissingSearchPoints {
mobilePoints: number
desktopPoints: number
edgePoints: number
totalPoints: number
}
}

View File

@@ -1,50 +1,50 @@
export interface QuizData {
offerId: string
quizId: string
quizCategory: string
IsCurrentQuestionCompleted: boolean
quizRenderSummaryPage: boolean
resetQuiz: boolean
userClickedOnHint: boolean
isDemoEnabled: boolean
correctAnswer: string
isMultiChoiceQuizType: boolean
isPutInOrderQuizType: boolean
isListicleQuizType: boolean
isWOTQuizType: boolean
isBugsForRewardsQuizType: boolean
currentQuestionNumber: number
maxQuestions: number
resetTrackingCounters: boolean
showWelcomePanel: boolean
isAjaxCall: boolean
showHint: boolean
numberOfOptions: number
isMobile: boolean
inRewardsMode: boolean
enableDailySetWelcomePane: boolean
enableDailySetNonWelcomePane: boolean
isDailySetUrlOffer: boolean
isDailySetFlightEnabled: boolean
dailySetUrlOfferId: string
earnedCredits: number
maxCredits: number
creditsPerQuestion: number
userAlreadyClickedOptions: number
hasUserClickedOnOption: boolean
recentAnswerChoice: string
sessionTimerSeconds: string
isOverlayMinimized: number
ScreenReaderMsgOnMove: string
ScreenReaderMsgOnDrop: string
IsPartialPointsEnabled: boolean
PrioritizeUrlOverCookies: boolean
UseNewReportActivityAPI: boolean
CorrectlyAnsweredQuestionCount: number
showJoinRewardsPage: boolean
CorrectOptionAnswer_WOT: string
WrongOptionAnswer_WOT: string
enableSlideAnimation: boolean
ariaLoggingEnabled: boolean
UseQuestionIndexInActivityId: boolean
offerId: string;
quizId: string;
quizCategory: string;
IsCurrentQuestionCompleted: boolean;
quizRenderSummaryPage: boolean;
resetQuiz: boolean;
userClickedOnHint: boolean;
isDemoEnabled: boolean;
correctAnswer: string;
isMultiChoiceQuizType: boolean;
isPutInOrderQuizType: boolean;
isListicleQuizType: boolean;
isWOTQuizType: boolean;
isBugsForRewardsQuizType: boolean;
currentQuestionNumber: number;
maxQuestions: number;
resetTrackingCounters: boolean;
showWelcomePanel: boolean;
isAjaxCall: boolean;
showHint: boolean;
numberOfOptions: number;
isMobile: boolean;
inRewardsMode: boolean;
enableDailySetWelcomePane: boolean;
enableDailySetNonWelcomePane: boolean;
isDailySetUrlOffer: boolean;
isDailySetFlightEnabled: boolean;
dailySetUrlOfferId: string;
earnedCredits: number;
maxCredits: number;
creditsPerQuestion: number;
userAlreadyClickedOptions: number;
hasUserClickedOnOption: boolean;
recentAnswerChoice: string;
sessionTimerSeconds: string;
isOverlayMinimized: number;
ScreenReaderMsgOnMove: string;
ScreenReaderMsgOnDrop: string;
IsPartialPointsEnabled: boolean;
PrioritizeUrlOverCookies: boolean;
UseNewReportActivityAPI: boolean;
CorrectlyAnsweredQuestionCount: number;
showJoinRewardsPage: boolean;
CorrectOptionAnswer_WOT: string;
WrongOptionAnswer_WOT: string;
enableSlideAnimation: boolean;
ariaLoggingEnabled: boolean;
UseQuestionIndexInActivityId: boolean;
}

View File

@@ -1,96 +1,4 @@
// Google Trends
export type GoogleTrendsResponse = [string, [string, ...null[], [string, ...string[]]][]]
export interface GoogleSearch {
topic: string
related: string[]
}
// Bing Suggestions
export interface BingSuggestionResponse {
_type: string
instrumentation: BingInstrumentation
queryContext: BingQueryContext
suggestionGroups: BingSuggestionGroup[]
}
export interface BingInstrumentation {
_type: string
pingUrlBase: string
pageLoadPingUrl: string
llmPingUrlBase: string
llmLogPingUrlBase: string
}
export interface BingQueryContext {
originalQuery: string
}
export interface BingSuggestionGroup {
name: string
searchSuggestions: BingSearchSuggestion[]
}
export interface BingSearchSuggestion {
url: string
urlPingSuffix: string
displayText: string
query: string
result?: BingResult[]
searchKind?: string
}
export interface BingResult {
id: string
readLink: string
readLinkPingSuffix: string
webSearchUrl: string
webSearchUrlPingSuffix: string
name: string
image: BingSuggestionImage
description: string
entityPresentationInfo: BingEntityPresentationInfo
bingId: string
}
export interface BingEntityPresentationInfo {
entityScenario: string
entityTypeDisplayHint: string
query: string
}
export interface BingSuggestionImage {
thumbnailUrl: string
hostPageUrl: string
hostPageUrlPingSuffix: string
width: number
height: number
sourceWidth: number
sourceHeight: number
}
// Bing Tending Topics
export interface BingTrendingTopicsResponse {
_type: string
instrumentation: BingInstrumentation
value: BingValue[]
}
export interface BingValue {
webSearchUrl: string
webSearchUrlPingSuffix: string
name: string
image: BingTrendingImage
isBreakingNews: boolean
query: BingTrendingQuery
newsSearchUrl: string
newsSearchUrlPingSuffix: string
}
export interface BingTrendingImage {
url: string
}
export interface BingTrendingQuery {
text: string
}
topic: string;
related: string[];
}

View File

@@ -1,37 +1,37 @@
// Chrome Product Data
export interface ChromeVersion {
timestamp: Date
channels: Channels
timestamp: Date;
channels: Channels;
}
export interface Channels {
Stable: Beta
Beta: Beta
Dev: Beta
Canary: Beta
Stable: Beta;
Beta: Beta;
Dev: Beta;
Canary: Beta;
}
export interface Beta {
channel: string
version: string
revision: string
channel: string;
version: string;
revision: string;
}
// Edge Product Data
export interface EdgeVersion {
Product: string
Releases: Release[]
Product: string;
Releases: Release[];
}
export interface Release {
ReleaseId: number
Platform: Platform
Architecture: Architecture
CVEs: string[]
ProductVersion: string
Artifacts: Artifact[]
PublishedTime: Date
ExpectedExpiryDate: Date
ReleaseId: number;
Platform: Platform;
Architecture: Architecture;
CVEs: string[];
ProductVersion: string;
Artifacts: Artifact[];
PublishedTime: Date;
ExpectedExpiryDate: Date;
}
export enum Architecture {
@@ -42,11 +42,11 @@ export enum Architecture {
}
export interface Artifact {
ArtifactName: string
Location: string
Hash: string
HashAlgorithm: HashAlgorithm
SizeInBytes: number
ArtifactName: string;
Location: string;
Hash: string;
HashAlgorithm: HashAlgorithm;
SizeInBytes: number;
}
export enum HashAlgorithm {
@@ -59,4 +59,4 @@ export enum Platform {
Linux = 'Linux',
MACOS = 'MacOS',
Windows = 'Windows'
}
}

View File

@@ -1,43 +0,0 @@
export interface XboxDashboardData {
response: Response
correlationId: string
code: number
}
export interface Response {
profile: null
balance: number
counters: { [key: string]: string }
promotions: Promotion[]
catalog: null
goal_item: null
activities: null
cashback: null
orders: null
rebateProfile: null
rebatePayouts: null
giveProfile: null
autoRedeemProfile: null
autoRedeemItem: null
thirdPartyProfile: null
notifications: null
waitlist: null
autoOpenFlyout: null
coupons: null
recommendedAffordableCatalog: null
generativeAICreditsBalance: null
requestCountryCatalog: null
donationCatalog: null
}
export interface Promotion {
name: string
priority: number
attributes: { [key: string]: string }
tags: Tag[]
}
export enum Tag {
ExcludeHidden = 'exclude_hidden',
NonGlobalConfig = 'non_global_config'
}

View File

@@ -1,50 +0,0 @@
import axios, { AxiosRequestConfig } from 'axios'
import PQueue from 'p-queue'
import type { LogLevel } from './Logger'
const DISCORD_LIMIT = 2000
export interface DiscordConfig {
enabled?: boolean
url: string
}
const discordQueue = new PQueue({
interval: 1000,
intervalCap: 2,
carryoverConcurrencyCount: true
})
function truncate(text: string) {
return text.length <= DISCORD_LIMIT ? text : text.slice(0, DISCORD_LIMIT - 14) + ' …(truncated)'
}
export async function sendDiscord(discordUrl: string, content: string, level: LogLevel): Promise<void> {
if (!discordUrl) return
const request: AxiosRequestConfig = {
method: 'POST',
url: discordUrl,
headers: { 'Content-Type': 'application/json' },
data: { content: truncate(content), allowed_mentions: { parse: [] } },
timeout: 10000
}
await discordQueue.add(async () => {
try {
await axios(request)
} catch (err: any) {
const status = err?.response?.status
if (status === 429) return
}
})
}
export async function flushDiscordQueue(timeoutMs = 5000): Promise<void> {
await Promise.race([
(async () => {
await discordQueue.onIdle()
})(),
new Promise<void>((_, reject) => setTimeout(() => reject(new Error('discord flush timeout')), timeoutMs))
]).catch(() => {})
}

View File

@@ -1,189 +0,0 @@
import chalk from 'chalk'
import cluster from 'cluster'
import { sendDiscord } from './Discord'
import { sendNtfy } from './Ntfy'
import type { MicrosoftRewardsBot } from '../index'
import { errorDiagnostic } from '../util/ErrorDiagnostic'
import type { LogFilter } from '../interface/Config'
export type Platform = boolean | 'main'
export type LogLevel = 'info' | 'warn' | 'error' | 'debug'
export type ColorKey = keyof typeof chalk
export interface IpcLog {
content: string
level: LogLevel
}
type ChalkFn = (msg: string) => string
function platformText(platform: Platform): string {
return platform === 'main' ? 'MAIN' : platform ? 'MOBILE' : 'DESKTOP'
}
function platformBadge(platform: Platform): string {
return platform === 'main' ? chalk.bgCyan('MAIN') : platform ? chalk.bgBlue('MOBILE') : chalk.bgMagenta('DESKTOP')
}
function getColorFn(color?: ColorKey): ChalkFn | null {
return color && typeof chalk[color] === 'function' ? (chalk[color] as ChalkFn) : null
}
function consoleOut(level: LogLevel, msg: string, chalkFn: ChalkFn | null): void {
const out = chalkFn ? chalkFn(msg) : msg
switch (level) {
case 'warn':
return console.warn(out)
case 'error':
return console.error(out)
default:
return console.log(out)
}
}
function formatMessage(message: string | Error): string {
return message instanceof Error ? `${message.message}\n${message.stack || ''}` : message
}
export class Logger {
constructor(private bot: MicrosoftRewardsBot) {}
info(isMobile: Platform, title: string, message: string, color?: ColorKey) {
return this.baseLog('info', isMobile, title, message, color)
}
warn(isMobile: Platform, title: string, message: string | Error, color?: ColorKey) {
return this.baseLog('warn', isMobile, title, message, color)
}
error(isMobile: Platform, title: string, message: string | Error, color?: ColorKey) {
return this.baseLog('error', isMobile, title, message, color)
}
debug(isMobile: Platform, title: string, message: string | Error, color?: ColorKey) {
return this.baseLog('debug', isMobile, title, message, color)
}
private baseLog(
level: LogLevel,
isMobile: Platform,
title: string,
message: string | Error,
color?: ColorKey
): void {
const now = new Date().toLocaleString()
const formatted = formatMessage(message)
const levelTag = level.toUpperCase()
const cleanMsg = `[${now}] [${this.bot.userData.userName}] [${levelTag}] ${platformText(
isMobile
)} [${title}] ${formatted}`
const config = this.bot.config
if (level === 'debug' && !config.debugLogs && !process.argv.includes('-dev')) {
return
}
const badge = platformBadge(isMobile)
const consoleStr = `[${now}] [${this.bot.userData.userName}] [${levelTag}] ${badge} [${title}] ${formatted}`
let logColor: ColorKey | undefined = color
if (!logColor) {
switch (level) {
case 'error':
logColor = 'red'
break
case 'warn':
logColor = 'yellow'
break
case 'debug':
logColor = 'magenta'
break
default:
break
}
}
if (level === 'error' && config.errorDiagnostics) {
const page = this.bot.isMobile ? this.bot.mainMobilePage : this.bot.mainDesktopPage
const error = message instanceof Error ? message : new Error(String(message))
errorDiagnostic(page, error)
}
const consoleAllowed = this.shouldPassFilter(config.consoleLogFilter, level, cleanMsg)
const webhookAllowed = this.shouldPassFilter(config.webhook.webhookLogFilter, level, cleanMsg)
if (consoleAllowed) {
consoleOut(level, consoleStr, getColorFn(logColor))
}
if (!webhookAllowed) {
return
}
if (cluster.isPrimary) {
if (config.webhook.discord?.enabled && config.webhook.discord.url) {
if (level === 'debug') return
sendDiscord(config.webhook.discord.url, cleanMsg, level)
}
if (config.webhook.ntfy?.enabled && config.webhook.ntfy.url) {
if (level === 'debug') return
sendNtfy(config.webhook.ntfy, cleanMsg, level)
}
} else {
process.send?.({ __ipcLog: { content: cleanMsg, level } })
}
}
private shouldPassFilter(filter: LogFilter | undefined, level: LogLevel, message: string): boolean {
// If disabled or not, let all logs pass
if (!filter || !filter.enabled) {
return true
}
// Always log error levelo logs, remove these lines to disable this!
if (level === 'error') {
return true
}
const { mode, levels, keywords, regexPatterns } = filter
const hasLevelRule = Array.isArray(levels) && levels.length > 0
const hasKeywordRule = Array.isArray(keywords) && keywords.length > 0
const hasPatternRule = Array.isArray(regexPatterns) && regexPatterns.length > 0
if (!hasLevelRule && !hasKeywordRule && !hasPatternRule) {
return mode === 'blacklist'
}
const lowerMessage = message.toLowerCase()
let isMatch = false
if (hasLevelRule && levels!.includes(level)) {
isMatch = true
}
if (!isMatch && hasKeywordRule) {
if (keywords!.some(k => lowerMessage.includes(k.toLowerCase()))) {
isMatch = true
}
}
// Fancy regex filtering if set!
if (!isMatch && hasPatternRule) {
for (const pattern of regexPatterns!) {
try {
const regex = new RegExp(pattern, 'i')
if (regex.test(message)) {
isMatch = true
break
}
} catch {}
}
}
return mode === 'whitelist' ? isMatch : !isMatch
}
}

View File

@@ -1,61 +0,0 @@
import axios, { AxiosRequestConfig } from 'axios'
import PQueue from 'p-queue'
import type { WebhookNtfyConfig } from '../interface/Config'
import type { LogLevel } from './Logger'
const ntfyQueue = new PQueue({
interval: 1000,
intervalCap: 2,
carryoverConcurrencyCount: true
})
export async function sendNtfy(config: WebhookNtfyConfig, content: string, level: LogLevel): Promise<void> {
if (!config?.url) return
switch (level) {
case 'error':
config.priority = 5 // Highest
break
case 'warn':
config.priority = 4
break
default:
break
}
const headers: Record<string, string> = { 'Content-Type': 'text/plain' }
if (config.title) headers['Title'] = config.title
if (config.tags?.length) headers['Tags'] = config.tags.join(',')
if (config.priority) headers['Priority'] = String(config.priority)
if (config.token) headers['Authorization'] = `Bearer ${config.token}`
const url = config.topic ? `${config.url}/${config.topic}` : config.url
const request: AxiosRequestConfig = {
method: 'POST',
url: url,
headers,
data: content,
timeout: 10000
}
await ntfyQueue.add(async () => {
try {
await axios(request)
} catch (err: any) {
const status = err?.response?.status
if (status === 429) return
}
})
}
export async function flushNtfyQueue(timeoutMs = 5000): Promise<void> {
await Promise.race([
(async () => {
await ntfyQueue.onIdle()
})(),
new Promise<void>((_, reject) => setTimeout(() => reject(new Error('ntfy flush timeout')), timeoutMs))
]).catch(() => {})
}

7
src/luxon.d.ts vendored Normal file
View File

@@ -0,0 +1,7 @@
/* Minimal ambient declarations to unblock TypeScript when @types/luxon is absent. */
declare module 'luxon' {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const DateTime: any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const IANAZone: any
}

1
scripts/docker/run_daily.sh → src/run_daily.sh Normal file → Executable file
View File

@@ -1,6 +1,7 @@
#!/usr/bin/env bash
set -euo pipefail
export PATH="/usr/local/bin:/usr/bin:/bin"
export PLAYWRIGHT_BROWSERS_PATH=0
export TZ="${TZ:-UTC}"

View File

@@ -0,0 +1,25 @@
export class AdaptiveThrottler {
private errorCount = 0
private successCount = 0
private window: Array<{ ok: boolean; at: number }> = []
private readonly maxWindow = 50
record(ok: boolean) {
this.window.push({ ok, at: Date.now() })
if (ok) this.successCount++
else this.errorCount++
if (this.window.length > this.maxWindow) {
const removed = this.window.shift()
if (removed) removed.ok ? this.successCount-- : this.errorCount--
}
}
/** Return a multiplier to apply to waits (1 = normal). */
getDelayMultiplier(): number {
const total = Math.max(1, this.successCount + this.errorCount)
const errRatio = this.errorCount / total
// 0% errors -> 1x; 50% errors -> ~1.8x; 80% -> ~2.5x (cap)
const mult = 1 + Math.min(1.5, errRatio * 2)
return Number(mult.toFixed(2))
}
}

View File

@@ -1,9 +1,8 @@
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import axiosRetry from 'axios-retry'
import axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { HttpProxyAgent } from 'http-proxy-agent'
import { HttpsProxyAgent } from 'https-proxy-agent'
import { URL } from 'url'
import type { AccountProxy } from '../interface/Account'
import { SocksProxyAgent } from 'socks-proxy-agent'
import { AccountProxy } from '../interface/Account'
class AxiosClient {
private instance: AxiosInstance
@@ -11,79 +10,87 @@ class AxiosClient {
constructor(account: AccountProxy) {
this.account = account
this.instance = axios.create()
this.instance = axios.create({
timeout: 20000
})
// If a proxy configuration is provided, set up the agent
if (this.account.url && this.account.proxyAxios) {
const agent = this.getAgentForProxy(this.account)
this.instance.defaults.httpAgent = agent
this.instance.defaults.httpsAgent = agent
}
axiosRetry(this.instance, {
retries: 5,
retryDelay: axiosRetry.exponentialDelay,
shouldResetTimeout: true,
retryCondition: error => {
if (axiosRetry.isNetworkError(error)) return true
if (!error.response) return true
const status = error.response.status
return status === 429 || (status >= 500 && status <= 599)
}
})
}
private getAgentForProxy(proxyConfig: AccountProxy): HttpProxyAgent<string> | HttpsProxyAgent<string> {
const { url: baseUrl, port, username, password } = proxyConfig
private getAgentForProxy(proxyConfig: AccountProxy): HttpProxyAgent<string> | HttpsProxyAgent<string> | SocksProxyAgent {
const { url, port } = proxyConfig
let urlObj: URL
try {
urlObj = new URL(baseUrl)
} catch (e) {
try {
urlObj = new URL(`http://${baseUrl}`)
} catch (error) {
throw new Error(`Invalid proxy URL format: ${baseUrl}`)
}
}
const protocol = urlObj.protocol.toLowerCase()
let proxyUrl: string
if (username && password) {
urlObj.username = encodeURIComponent(username)
urlObj.password = encodeURIComponent(password)
urlObj.port = port.toString()
proxyUrl = urlObj.toString()
} else {
proxyUrl = `${protocol}//${urlObj.hostname}:${port}`
}
switch (protocol) {
case 'http:':
return new HttpProxyAgent(proxyUrl)
case 'https:':
return new HttpsProxyAgent(proxyUrl)
switch (true) {
case proxyConfig.url.startsWith('http://'):
return new HttpProxyAgent(`${url}:${port}`)
case proxyConfig.url.startsWith('https://'):
return new HttpsProxyAgent(`${url}:${port}`)
case proxyConfig.url.startsWith('socks://') || proxyConfig.url.startsWith('socks4://') || proxyConfig.url.startsWith('socks5://'):
return new SocksProxyAgent(`${url}:${port}`)
default:
throw new Error(`Unsupported proxy protocol: ${protocol}. Only HTTP(S) is supported!`)
throw new Error(`Unsupported proxy protocol in "${url}". Supported: http://, https://, socks://, socks4://, socks5://`)
}
}
// Generic method to make any Axios request
public async request(config: AxiosRequestConfig, bypassProxy = false): Promise<AxiosResponse> {
if (bypassProxy) {
const bypassInstance = axios.create()
axiosRetry(bypassInstance, {
retries: 3,
retryDelay: axiosRetry.exponentialDelay
})
return bypassInstance.request(config)
}
return this.instance.request(config)
let lastError: unknown
const maxAttempts = 2
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await this.instance.request(config)
} catch (err: unknown) {
lastError = err
const axiosErr = err as AxiosError | undefined
// Detect HTTP proxy auth failures (status 407) and retry without proxy
if (axiosErr && axiosErr.response && axiosErr.response.status === 407) {
if (attempt < maxAttempts) {
await this.sleep(1000 * attempt) // Exponential backoff
}
const bypassInstance = axios.create()
return bypassInstance.request(config)
}
// If proxied request fails with common proxy/network errors, retry with backoff
const e = err as { code?: string; cause?: { code?: string }; message?: string } | undefined
const code = e?.code || e?.cause?.code
const isNetErr = code === 'ECONNREFUSED' || code === 'ETIMEDOUT' || code === 'ECONNRESET' || code === 'ENOTFOUND'
const msg = String(e?.message || '')
const looksLikeProxyIssue = /proxy|tunnel|socks|agent/i.test(msg)
if (isNetErr || looksLikeProxyIssue) {
if (attempt < maxAttempts) {
// Exponential backoff: 1s, 2s, 4s, etc.
const delayMs = 1000 * Math.pow(2, attempt - 1)
await this.sleep(delayMs)
continue
}
// Last attempt: try without proxy
const bypassInstance = axios.create()
return bypassInstance.request(config)
}
// Non-retryable error
throw err
}
}
throw lastError
}
private sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms))
}
}
export default AxiosClient
export default AxiosClient

16
src/util/BanDetector.ts Normal file
View File

@@ -0,0 +1,16 @@
export type BanStatus = { status: boolean; reason: string }
const BAN_PATTERNS: Array<{ re: RegExp; reason: string }> = [
{ re: /suspend|suspended|suspension/i, reason: 'account suspended' },
{ re: /locked|lockout|serviceabuse|abuse/i, reason: 'locked or service abuse detected' },
{ re: /unusual.*activity|unusual activity/i, reason: 'unusual activity prompts' },
{ re: /verify.*identity|identity.*verification/i, reason: 'identity verification required' }
]
export function detectBanReason(input: unknown): BanStatus {
const s = input instanceof Error ? (input.message || '') : String(input || '')
for (const p of BAN_PATTERNS) {
if (p.re.test(s)) return { status: true, reason: p.reason }
}
return { status: false, reason: '' }
}

View File

@@ -0,0 +1,335 @@
import axios from 'axios'
import { Config } from '../interface/Config'
import { Ntfy } from './Ntfy'
import { DISCORD } from '../constants'
import { log } from './Logger'
interface DiscordField {
name: string
value: string
inline?: boolean
}
interface DiscordEmbed {
title?: string
description?: string
color?: number
fields?: DiscordField[]
timestamp?: string
footer?: {
text: string
icon_url?: string
}
thumbnail?: {
url: string
}
author?: {
name: string
icon_url?: string
}
}
interface AccountSummary {
email: string
totalCollected: number
desktopCollected: number
mobileCollected: number
initialTotal: number
endTotal: number
durationMs: number
errors: string[]
banned?: { status: boolean; reason?: string }
}
interface ConclusionData {
version: string
runId: string
totalAccounts: number
successes: number
accountsWithErrors: number
accountsBanned: number
totalCollected: number
totalInitial: number
totalEnd: number
avgPointsPerAccount: number
totalDuration: number
avgDuration: number
summaries: AccountSummary[]
}
/**
* Send a clean, structured Discord webhook notification
*/
export async function ConclusionWebhook(
config: Config,
title: string,
description: string,
fields?: DiscordField[],
color?: number
) {
const hasConclusion = config.conclusionWebhook?.enabled && config.conclusionWebhook.url
const hasWebhook = config.webhook?.enabled && config.webhook.url
if (!hasConclusion && !hasWebhook) return
const embed: DiscordEmbed = {
title,
description,
color: color || 0x0078D4,
timestamp: new Date().toISOString()
}
if (fields && fields.length > 0) {
embed.fields = fields
}
const postWebhook = async (url: string, label: string) => {
const maxAttempts = 3
let lastError: unknown = null
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
await axios.post(url,
{
embeds: [embed]
},
{
headers: { 'Content-Type': 'application/json' },
timeout: 15000
})
log('main', 'WEBHOOK', `${label} notification sent successfully (attempt ${attempt})`)
return
} catch (error) {
lastError = error
if (attempt < maxAttempts) {
// Exponential backoff: 1s, 2s, 4s
const delayMs = 1000 * Math.pow(2, attempt - 1)
await new Promise(resolve => setTimeout(resolve, delayMs))
}
}
}
log('main', 'WEBHOOK', `${label} failed after ${maxAttempts} attempts: ${lastError instanceof Error ? lastError.message : String(lastError)}`, 'error')
}
const urls = new Set<string>()
if (hasConclusion) urls.add(config.conclusionWebhook!.url)
if (hasWebhook) urls.add(config.webhook!.url)
await Promise.all(
Array.from(urls).map((url, index) => postWebhook(url, `webhook-${index + 1}`))
)
// Optional NTFY notification
if (config.ntfy?.enabled && config.ntfy.url && config.ntfy.topic) {
const message = `${title}\n${description}${fields ? '\n\n' + fields.map(f => `${f.name}: ${f.value}`).join('\n') : ''}`
const ntfyType = color === 0xFF0000 ? 'error' : color === 0xFFAA00 ? 'warn' : 'log'
try {
await Ntfy(message, ntfyType)
log('main', 'NTFY', 'Notification sent successfully')
} catch (error) {
log('main', 'NTFY', `Failed to send notification: ${error instanceof Error ? error.message : String(error)}`, 'error')
}
}
}
/**
* Enhanced conclusion webhook with beautiful formatting and clear statistics
*/
export async function ConclusionWebhookEnhanced(config: Config, data: ConclusionData) {
const hasConclusion = config.conclusionWebhook?.enabled && config.conclusionWebhook.url
const hasWebhook = config.webhook?.enabled && config.webhook.url
if (!hasConclusion && !hasWebhook) return
// Helper to format duration
const formatDuration = (ms: number): string => {
const totalSeconds = Math.floor(ms / 1000)
const hours = Math.floor(totalSeconds / 3600)
const minutes = Math.floor((totalSeconds % 3600) / 60)
const seconds = totalSeconds % 60
if (hours > 0) return `${hours}h ${minutes}m ${seconds}s`
if (minutes > 0) return `${minutes}m ${seconds}s`
return `${seconds}s`
}
// Helper to create progress bar (future use)
// const createProgressBar = (current: number, max: number, length: number = 10): string => {
// const percentage = Math.min(100, Math.max(0, (current / max) * 100))
// const filled = Math.round((percentage / 100) * length)
// const empty = length - filled
// return `${'█'.repeat(filled)}${'░'.repeat(empty)} ${percentage.toFixed(0)}%`
// }
// Determine overall status and color
let statusEmoji = '✅'
let statusText = 'Success'
let embedColor: number = DISCORD.COLOR_GREEN
if (data.accountsBanned > 0) {
statusEmoji = '🚫'
statusText = 'Banned Accounts Detected'
embedColor = DISCORD.COLOR_RED
} else if (data.accountsWithErrors > 0) {
statusEmoji = '⚠️'
statusText = 'Completed with Warnings'
embedColor = DISCORD.COLOR_ORANGE
}
// Build main summary description
const mainDescription = [
`**Status:** ${statusEmoji} ${statusText}`,
`**Version:** v${data.version} • **Run ID:** \`${data.runId}\``,
'',
'━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'
].join('\n')
// Build global statistics field
const globalStats = [
'**💎 Total Points Earned**',
`\`${data.totalInitial.toLocaleString()}\`\`${data.totalEnd.toLocaleString()}\` **(+${data.totalCollected.toLocaleString()})**`,
'',
'**📊 Accounts Processed**',
`✅ Success: **${data.successes}** | ⚠️ Errors: **${data.accountsWithErrors}** | 🚫 Banned: **${data.accountsBanned}**`,
`Total: **${data.totalAccounts}** ${data.totalAccounts === 1 ? 'account' : 'accounts'}`,
'',
'**⚡ Performance**',
`Average: **${data.avgPointsPerAccount}pts/account** in **${formatDuration(data.avgDuration)}**`,
`Total Runtime: **${formatDuration(data.totalDuration)}**`
].join('\n')
// Build per-account breakdown (split if too many accounts)
const accountFields: DiscordField[] = []
const maxAccountsPerField = 5
const accountChunks: AccountSummary[][] = []
for (let i = 0; i < data.summaries.length; i += maxAccountsPerField) {
accountChunks.push(data.summaries.slice(i, i + maxAccountsPerField))
}
accountChunks.forEach((chunk, chunkIndex) => {
const accountLines: string[] = []
chunk.forEach((acc) => {
const statusIcon = acc.banned?.status ? '🚫' : (acc.errors.length > 0 ? '⚠️' : '✅')
const emailShort = acc.email.length > 25 ? acc.email.substring(0, 22) + '...' : acc.email
accountLines.push(`${statusIcon} **${emailShort}**`)
accountLines.push(`└ Points: **+${acc.totalCollected}** (🖥️ ${acc.desktopCollected} • 📱 ${acc.mobileCollected})`)
accountLines.push(`└ Duration: ${formatDuration(acc.durationMs)}`)
if (acc.banned?.status) {
accountLines.push(`└ 🚫 **Banned:** ${acc.banned.reason || 'Account suspended'}`)
} else if (acc.errors.length > 0) {
const errorPreview = acc.errors.slice(0, 1).join(', ')
accountLines.push(`└ ⚠️ **Error:** ${errorPreview.length > 50 ? errorPreview.substring(0, 47) + '...' : errorPreview}`)
}
accountLines.push('') // Empty line between accounts
})
const fieldName = accountChunks.length > 1
? `📈 Account Details (${chunkIndex + 1}/${accountChunks.length})`
: '📈 Account Details'
accountFields.push({
name: fieldName,
value: accountLines.join('\n').trim(),
inline: false
})
})
// Create embeds
const embeds: DiscordEmbed[] = []
// Main embed with summary
embeds.push({
title: '🎯 Microsoft Rewards — Daily Summary',
description: mainDescription,
color: embedColor,
fields: [
{
name: '📊 Global Statistics',
value: globalStats,
inline: false
}
],
footer: {
text: `Microsoft Rewards Bot v${data.version} • Completed at`
},
timestamp: new Date().toISOString()
})
// Add account details in separate embed(s) if needed
if (accountFields.length > 0) {
// If we have multiple fields, split into multiple embeds
accountFields.forEach((field, index) => {
if (index === 0 && embeds[0] && embeds[0].fields) {
// Add first field to main embed
embeds[0].fields.push(field)
} else {
// Create additional embeds for remaining fields
embeds.push({
color: embedColor,
fields: [field],
timestamp: new Date().toISOString()
})
}
})
}
const postWebhook = async (url: string, label: string) => {
const maxAttempts = 3
let lastError: unknown = null
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
await axios.post(url, {
embeds: embeds
}, {
headers: { 'Content-Type': 'application/json' },
timeout: 15000
})
log('main', 'WEBHOOK', `${label} conclusion sent successfully (${data.totalAccounts} accounts, +${data.totalCollected}pts)`)
return
} catch (error) {
lastError = error
if (attempt < maxAttempts) {
const delayMs = 1000 * Math.pow(2, attempt - 1)
await new Promise(resolve => setTimeout(resolve, delayMs))
}
}
}
log('main', 'WEBHOOK', `${label} failed after ${maxAttempts} attempts: ${lastError instanceof Error ? lastError.message : String(lastError)}`, 'error')
}
const urls = new Set<string>()
if (hasConclusion) urls.add(config.conclusionWebhook!.url)
if (hasWebhook) urls.add(config.webhook!.url)
await Promise.all(
Array.from(urls).map((url, index) => postWebhook(url, `conclusion-webhook-${index + 1}`))
)
// Optional NTFY notification (simplified summary)
if (config.ntfy?.enabled && config.ntfy.url && config.ntfy.topic) {
const message = [
'🎯 Microsoft Rewards Summary',
`Status: ${statusText}`,
`Points: ${data.totalInitial}${data.totalEnd} (+${data.totalCollected})`,
`Accounts: ${data.successes}/${data.totalAccounts} successful`,
`Duration: ${formatDuration(data.totalDuration)}`
].join('\n')
const ntfyType = embedColor === DISCORD.COLOR_RED ? 'error' : embedColor === DISCORD.COLOR_ORANGE ? 'warn' : 'log'
try {
await Ntfy(message, ntfyType)
log('main', 'NTFY', 'Conclusion notification sent successfully')
} catch (error) {
log('main', 'NTFY', `Failed to send conclusion notification: ${error instanceof Error ? error.message : String(error)}`, 'error')
}
}
}

481
src/util/ConfigValidator.ts Normal file
View File

@@ -0,0 +1,481 @@
import fs from 'fs'
import { Config } from '../interface/Config'
import { Account } from '../interface/Account'
export interface ValidationIssue {
severity: 'error' | 'warning' | 'info'
field: string
message: string
suggestion?: string
}
export interface ValidationResult {
valid: boolean
issues: ValidationIssue[]
}
/**
* ConfigValidator performs intelligent validation of config.json and accounts.json
* before execution to catch common mistakes, conflicts, and security issues.
*/
export class ConfigValidator {
/**
* Validate the main config file
*/
static validateConfig(config: Config): ValidationResult {
const issues: ValidationIssue[] = []
// Check baseURL
if (!config.baseURL || !config.baseURL.startsWith('https://')) {
issues.push({
severity: 'error',
field: 'baseURL',
message: 'baseURL must be a valid HTTPS URL',
suggestion: 'Use https://rewards.bing.com'
})
}
// Check sessionPath
if (!config.sessionPath || config.sessionPath.trim() === '') {
issues.push({
severity: 'error',
field: 'sessionPath',
message: 'sessionPath cannot be empty'
})
}
// Check clusters
if (config.clusters < 1) {
issues.push({
severity: 'error',
field: 'clusters',
message: 'clusters must be at least 1'
})
}
if (config.clusters > 10) {
issues.push({
severity: 'warning',
field: 'clusters',
message: 'High cluster count may consume excessive resources',
suggestion: 'Consider using 2-4 clusters for optimal performance'
})
}
// Check globalTimeout
const timeout = this.parseTimeout(config.globalTimeout)
if (timeout < 10000) {
issues.push({
severity: 'warning',
field: 'globalTimeout',
message: 'Very short timeout may cause frequent failures',
suggestion: 'Use at least 15s for stability'
})
}
if (timeout > 120000) {
issues.push({
severity: 'warning',
field: 'globalTimeout',
message: 'Very long timeout may slow down execution',
suggestion: 'Use 30-60s for optimal balance'
})
}
// Check search settings
if (config.searchSettings) {
const searchDelay = config.searchSettings.searchDelay
const minDelay = this.parseTimeout(searchDelay.min)
const maxDelay = this.parseTimeout(searchDelay.max)
if (minDelay >= maxDelay) {
issues.push({
severity: 'error',
field: 'searchSettings.searchDelay',
message: 'min delay must be less than max delay'
})
}
if (minDelay < 10000) {
issues.push({
severity: 'warning',
field: 'searchSettings.searchDelay.min',
message: 'Very short search delays increase ban risk',
suggestion: 'Use at least 30s between searches'
})
}
if (config.searchSettings.retryMobileSearchAmount > 5) {
issues.push({
severity: 'warning',
field: 'searchSettings.retryMobileSearchAmount',
message: 'Too many retries may waste time',
suggestion: 'Use 2-3 retries maximum'
})
}
}
// Check humanization
if (config.humanization) {
if (config.humanization.enabled === false && config.humanization.stopOnBan === true) {
issues.push({
severity: 'warning',
field: 'humanization',
message: 'stopOnBan is enabled but humanization is disabled',
suggestion: 'Enable humanization for better ban protection'
})
}
const actionDelay = config.humanization.actionDelay
if (actionDelay) {
const minAction = this.parseTimeout(actionDelay.min)
const maxAction = this.parseTimeout(actionDelay.max)
if (minAction >= maxAction) {
issues.push({
severity: 'error',
field: 'humanization.actionDelay',
message: 'min action delay must be less than max'
})
}
}
if (config.humanization.allowedWindows && config.humanization.allowedWindows.length > 0) {
for (const window of config.humanization.allowedWindows) {
if (!/^\d{2}:\d{2}-\d{2}:\d{2}$/.test(window)) {
issues.push({
severity: 'error',
field: 'humanization.allowedWindows',
message: `Invalid time window format: ${window}`,
suggestion: 'Use format HH:mm-HH:mm (e.g., 09:00-17:00)'
})
}
}
}
}
// Check proxy config
if (config.proxy) {
if (config.proxy.proxyGoogleTrends === false && config.proxy.proxyBingTerms === false) {
issues.push({
severity: 'info',
field: 'proxy',
message: 'All proxy options disabled - outbound requests will use direct connection'
})
}
}
// Check webhooks
if (config.webhook?.enabled && (!config.webhook.url || config.webhook.url.trim() === '')) {
issues.push({
severity: 'error',
field: 'webhook.url',
message: 'Webhook enabled but URL is empty'
})
}
if (config.conclusionWebhook?.enabled && (!config.conclusionWebhook.url || config.conclusionWebhook.url.trim() === '')) {
issues.push({
severity: 'error',
field: 'conclusionWebhook.url',
message: 'Conclusion webhook enabled but URL is empty'
})
}
// Check ntfy
if (config.ntfy?.enabled) {
if (!config.ntfy.url || config.ntfy.url.trim() === '') {
issues.push({
severity: 'error',
field: 'ntfy.url',
message: 'NTFY enabled but URL is empty'
})
}
if (!config.ntfy.topic || config.ntfy.topic.trim() === '') {
issues.push({
severity: 'error',
field: 'ntfy.topic',
message: 'NTFY enabled but topic is empty'
})
}
}
// Check workers
if (config.workers) {
const allDisabled = !config.workers.doDailySet &&
!config.workers.doMorePromotions &&
!config.workers.doPunchCards &&
!config.workers.doDesktopSearch &&
!config.workers.doMobileSearch &&
!config.workers.doDailyCheckIn &&
!config.workers.doReadToEarn
if (allDisabled) {
issues.push({
severity: 'warning',
field: 'workers',
message: 'All workers are disabled - bot will not perform any tasks',
suggestion: 'Enable at least one worker type'
})
}
}
const valid = !issues.some(i => i.severity === 'error')
return { valid, issues }
}
/**
* Validate accounts.json
*/
static validateAccounts(accounts: Account[]): ValidationResult {
const issues: ValidationIssue[] = []
if (accounts.length === 0) {
issues.push({
severity: 'error',
field: 'accounts',
message: 'No accounts found in accounts.json'
})
return { valid: false, issues }
}
const seenEmails = new Set<string>()
const seenProxies = new Map<string, string[]>() // proxy -> [emails]
for (let i = 0; i < accounts.length; i++) {
const acc = accounts[i]
const prefix = `accounts[${i}]`
if (!acc) continue
// Check email
if (!acc.email || acc.email.trim() === '') {
issues.push({
severity: 'error',
field: `${prefix}.email`,
message: 'Account email is empty'
})
} else {
if (seenEmails.has(acc.email)) {
issues.push({
severity: 'error',
field: `${prefix}.email`,
message: `Duplicate email: ${acc.email}`
})
}
seenEmails.add(acc.email)
if (!/@/.test(acc.email)) {
issues.push({
severity: 'error',
field: `${prefix}.email`,
message: 'Invalid email format'
})
}
}
// Check password
if (!acc.password || acc.password.trim() === '') {
issues.push({
severity: 'error',
field: `${prefix}.password`,
message: 'Account password is empty'
})
} else if (acc.password.length < 8) {
issues.push({
severity: 'warning',
field: `${prefix}.password`,
message: 'Very short password - verify it\'s correct'
})
}
// Check proxy
if (acc.proxy) {
const proxyUrl = acc.proxy.url
if (proxyUrl && proxyUrl.trim() !== '') {
if (!acc.proxy.port) {
issues.push({
severity: 'error',
field: `${prefix}.proxy.port`,
message: 'Proxy URL specified but port is missing'
})
}
// Track proxy reuse
const proxyKey = `${proxyUrl}:${acc.proxy.port}`
if (!seenProxies.has(proxyKey)) {
seenProxies.set(proxyKey, [])
}
seenProxies.get(proxyKey)?.push(acc.email)
}
}
// Check TOTP
if (acc.totp && acc.totp.trim() !== '') {
if (acc.totp.length < 16) {
issues.push({
severity: 'warning',
field: `${prefix}.totp`,
message: 'TOTP secret seems too short - verify it\'s correct'
})
}
}
}
// Warn about excessive proxy reuse
for (const [proxyKey, emails] of seenProxies) {
if (emails.length > 3) {
issues.push({
severity: 'warning',
field: 'accounts.proxy',
message: `Proxy ${proxyKey} used by ${emails.length} accounts - may trigger rate limits`,
suggestion: 'Use different proxies per account for better safety'
})
}
}
const valid = !issues.some(i => i.severity === 'error')
return { valid, issues }
}
/**
* Validate both config and accounts together (cross-checks)
*/
static validateAll(config: Config, accounts: Account[]): ValidationResult {
const configResult = this.validateConfig(config)
const accountsResult = this.validateAccounts(accounts)
const issues = [...configResult.issues, ...accountsResult.issues]
// Cross-validation: clusters vs accounts
if (accounts.length > 0 && config.clusters > accounts.length) {
issues.push({
severity: 'info',
field: 'clusters',
message: `${config.clusters} clusters configured but only ${accounts.length} account(s)`,
suggestion: 'Reduce clusters to match account count for efficiency'
})
}
// Cross-validation: parallel mode with single account
if (config.parallel && accounts.length === 1) {
issues.push({
severity: 'info',
field: 'parallel',
message: 'Parallel mode enabled with single account has no effect',
suggestion: 'Disable parallel mode or add more accounts'
})
}
const valid = !issues.some(i => i.severity === 'error')
return { valid, issues }
}
/**
* Load and validate from file paths
*/
static validateFromFiles(configPath: string, accountsPath: string): ValidationResult {
try {
if (!fs.existsSync(configPath)) {
return {
valid: false,
issues: [{
severity: 'error',
field: 'config',
message: `Config file not found: ${configPath}`
}]
}
}
if (!fs.existsSync(accountsPath)) {
return {
valid: false,
issues: [{
severity: 'error',
field: 'accounts',
message: `Accounts file not found: ${accountsPath}`
}]
}
}
const configRaw = fs.readFileSync(configPath, 'utf-8')
const accountsRaw = fs.readFileSync(accountsPath, 'utf-8')
const configJson = configRaw.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, '')
const config: Config = JSON.parse(configJson)
const accounts: Account[] = JSON.parse(accountsRaw)
return this.validateAll(config, accounts)
} catch (error) {
return {
valid: false,
issues: [{
severity: 'error',
field: 'parse',
message: `Failed to parse files: ${error instanceof Error ? error.message : String(error)}`
}]
}
}
}
/**
* Print validation results to console with color
* Note: This method intentionally uses console.log for CLI output formatting
*/
static printResults(result: ValidationResult): void {
if (result.valid) {
console.log('✅ Configuration validation passed\n')
} else {
console.log('❌ Configuration validation failed\n')
}
if (result.issues.length === 0) {
console.log('No issues found.')
return
}
const errors = result.issues.filter(i => i.severity === 'error')
const warnings = result.issues.filter(i => i.severity === 'warning')
const infos = result.issues.filter(i => i.severity === 'info')
if (errors.length > 0) {
console.log(`\n🚫 ERRORS (${errors.length}):`)
for (const issue of errors) {
console.log(` ${issue.field}: ${issue.message}`)
if (issue.suggestion) {
console.log(`${issue.suggestion}`)
}
}
}
if (warnings.length > 0) {
console.log(`\n⚠ WARNINGS (${warnings.length}):`)
for (const issue of warnings) {
console.log(` ${issue.field}: ${issue.message}`)
if (issue.suggestion) {
console.log(`${issue.suggestion}`)
}
}
}
if (infos.length > 0) {
console.log(`\n INFO (${infos.length}):`)
for (const issue of infos) {
console.log(` ${issue.field}: ${issue.message}`)
if (issue.suggestion) {
console.log(`${issue.suggestion}`)
}
}
}
console.log()
}
private static parseTimeout(value: number | string): number {
if (typeof value === 'number') return value
const str = String(value).toLowerCase()
if (str.endsWith('ms')) return parseInt(str, 10)
if (str.endsWith('s')) return parseInt(str, 10) * 1000
if (str.endsWith('min')) return parseInt(str, 10) * 60000
return parseInt(str, 10) || 30000
}
}

View File

@@ -1,46 +0,0 @@
import fs from 'fs/promises'
import path from 'path'
import type { Page } from 'patchright'
export async function errorDiagnostic(page: Page, error: Error): Promise<void> {
try {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
const folderName = `error-${timestamp}`
const outputDir = path.join(process.cwd(), 'diagnostics', folderName)
if (!page) {
return
}
if (page.isClosed()) {
return
}
// Error log content
const errorLog = `
Name: ${error.name}
Message: ${error.message}
Timestamp: ${new Date().toISOString()}
---------------------------------------------------
Stack Trace:
${error.stack || 'No stack trace available'}
`.trim()
const [htmlContent, screenshotBuffer] = await Promise.all([
page.content(),
page.screenshot({ fullPage: true, type: 'png' })
])
await fs.mkdir(outputDir, { recursive: true })
await Promise.all([
fs.writeFile(path.join(outputDir, 'dump.html'), htmlContent),
fs.writeFile(path.join(outputDir, 'screenshot.png'), screenshotBuffer),
fs.writeFile(path.join(outputDir, 'error.txt'), errorLog)
])
console.log(`Diagnostics saved to: ${outputDir}`)
} catch (error) {
console.error('Unable to create error diagnostics:', error)
}
}

54
src/util/Humanizer.ts Normal file
View File

@@ -0,0 +1,54 @@
import { Page } from 'rebrowser-playwright'
import Util from './Utils'
import type { ConfigHumanization } from '../interface/Config'
export class Humanizer {
private util: Util
private cfg: ConfigHumanization | undefined
constructor(util: Util, cfg?: ConfigHumanization) {
this.util = util
this.cfg = cfg
}
async microGestures(page: Page): Promise<void> {
if (this.cfg && this.cfg.enabled === false) return
const moveProb = this.cfg?.gestureMoveProb ?? 0.4
const scrollProb = this.cfg?.gestureScrollProb ?? 0.2
try {
if (Math.random() < moveProb) {
const x = Math.floor(Math.random() * 40) + 5
const y = Math.floor(Math.random() * 30) + 5
await page.mouse.move(x, y, { steps: 2 }).catch(() => {})
}
if (Math.random() < scrollProb) {
const dy = (Math.random() < 0.5 ? 1 : -1) * (Math.floor(Math.random() * 150) + 50)
await page.mouse.wheel(0, dy).catch(() => {})
}
} catch {/* noop */}
}
async actionPause(): Promise<void> {
if (this.cfg && this.cfg.enabled === false) return
const defMin = 150
const defMax = 450
let min = defMin
let max = defMax
if (this.cfg?.actionDelay) {
const parse = (v: number | string) => {
if (typeof v === 'number') return v
try {
const n = this.util.stringToMs(String(v))
return Math.max(0, Math.min(n, 10_000))
} catch { return defMin }
}
min = parse(this.cfg.actionDelay.min)
max = parse(this.cfg.actionDelay.max)
if (min > max) [min, max] = [max, min]
max = Math.min(max, 5_000)
}
await this.util.wait(this.util.randomNumber(min, max))
}
}
export default Humanizer

58
src/util/JobState.ts Normal file
View File

@@ -0,0 +1,58 @@
import fs from 'fs'
import path from 'path'
import type { Config } from '../interface/Config'
type DayState = {
doneOfferIds: string[]
}
type FileState = {
days: Record<string, DayState>
}
export class JobState {
private baseDir: string
constructor(cfg: Config) {
const dir = cfg.jobState?.dir || path.join(process.cwd(), cfg.sessionPath, 'job-state')
this.baseDir = dir
if (!fs.existsSync(this.baseDir)) fs.mkdirSync(this.baseDir, { recursive: true })
}
private fileFor(email: string): string {
const safe = email.replace(/[^a-z0-9._-]/gi, '_')
return path.join(this.baseDir, `${safe}.json`)
}
private load(email: string): FileState {
const file = this.fileFor(email)
if (!fs.existsSync(file)) return { days: {} }
try {
const raw = fs.readFileSync(file, 'utf-8')
const parsed = JSON.parse(raw)
return parsed && typeof parsed === 'object' && parsed.days ? parsed as FileState : { days: {} }
} catch { return { days: {} } }
}
private save(email: string, state: FileState): void {
const file = this.fileFor(email)
fs.writeFileSync(file, JSON.stringify(state, null, 2), 'utf-8')
}
isDone(email: string, day: string, offerId: string): boolean {
const st = this.load(email)
const d = st.days[day]
if (!d) return false
return d.doneOfferIds.includes(offerId)
}
markDone(email: string, day: string, offerId: string): void {
const st = this.load(email)
if (!st.days[day]) st.days[day] = { doneOfferIds: [] }
const d = st.days[day]
if (!d.doneOfferIds.includes(offerId)) d.doneOfferIds.push(offerId)
this.save(email, st)
}
}
export default JobState

View File

@@ -1,57 +1,235 @@
import type { Cookie } from 'patchright'
import type { BrowserFingerprintWithHeaders } from 'fingerprint-generator'
import { BrowserContext, Cookie } from 'rebrowser-playwright'
import { BrowserFingerprintWithHeaders } from 'fingerprint-generator'
import fs from 'fs'
import path from 'path'
import type { Account } from '../interface/Account'
import type { Config, ConfigSaveFingerprint } from '../interface/Config'
import { Account } from '../interface/Account'
import { Config, ConfigSaveFingerprint } from '../interface/Config'
let configCache: Config
let configSourcePath = ''
// Normalize both legacy (flat) and new (nested) config schemas into the flat Config interface
function normalizeConfig(raw: unknown): Config {
// Using any here is necessary to support both legacy flat config and new nested config structures
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const n = (raw || {}) as any
// Browser / execution
const headless = n.browser?.headless ?? n.headless ?? false
const globalTimeout = n.browser?.globalTimeout ?? n.globalTimeout ?? '30s'
const parallel = n.execution?.parallel ?? n.parallel ?? false
const runOnZeroPoints = n.execution?.runOnZeroPoints ?? n.runOnZeroPoints ?? false
const clusters = n.execution?.clusters ?? n.clusters ?? 1
// Search
const useLocalQueries = n.search?.useLocalQueries ?? n.searchOnBingLocalQueries ?? false
const searchSettingsSrc = n.search?.settings ?? n.searchSettings ?? {}
const delaySrc = searchSettingsSrc.delay ?? searchSettingsSrc.searchDelay ?? { min: '3min', max: '5min' }
const searchSettings = {
useGeoLocaleQueries: !!(searchSettingsSrc.useGeoLocaleQueries ?? false),
scrollRandomResults: !!(searchSettingsSrc.scrollRandomResults ?? false),
clickRandomResults: !!(searchSettingsSrc.clickRandomResults ?? false),
retryMobileSearchAmount: Number(searchSettingsSrc.retryMobileSearchAmount ?? 2),
searchDelay: {
min: delaySrc.min ?? '3min',
max: delaySrc.max ?? '5min'
},
localFallbackCount: Number(searchSettingsSrc.localFallbackCount ?? 25),
extraFallbackRetries: Number(searchSettingsSrc.extraFallbackRetries ?? 1)
}
// Workers
const workers = n.workers ?? {
doDailySet: true,
doMorePromotions: true,
doPunchCards: true,
doDesktopSearch: true,
doMobileSearch: true,
doDailyCheckIn: true,
doReadToEarn: true,
bundleDailySetWithSearch: false
}
// Ensure missing flag gets a default
if (typeof workers.bundleDailySetWithSearch !== 'boolean') workers.bundleDailySetWithSearch = false
// Logging
const logging = n.logging ?? {}
const logExcludeFunc = Array.isArray(logging.excludeFunc) ? logging.excludeFunc : (n.logExcludeFunc ?? [])
const webhookLogExcludeFunc = Array.isArray(logging.webhookExcludeFunc) ? logging.webhookExcludeFunc : (n.webhookLogExcludeFunc ?? [])
// Notifications
const notifications = n.notifications ?? {}
const webhook = notifications.webhook ?? n.webhook ?? { enabled: false, url: '' }
const conclusionWebhook = notifications.conclusionWebhook ?? n.conclusionWebhook ?? { enabled: false, url: '' }
const ntfy = notifications.ntfy ?? n.ntfy ?? { enabled: false, url: '', topic: '', authToken: '' }
// Fingerprinting
const saveFingerprint = (n.fingerprinting?.saveFingerprint ?? n.saveFingerprint) ?? { mobile: false, desktop: false }
// Humanization defaults (single on/off)
if (!n.humanization) n.humanization = {}
if (typeof n.humanization.enabled !== 'boolean') n.humanization.enabled = true
if (typeof n.humanization.stopOnBan !== 'boolean') n.humanization.stopOnBan = false
if (typeof n.humanization.immediateBanAlert !== 'boolean') n.humanization.immediateBanAlert = true
if (typeof n.humanization.randomOffDaysPerWeek !== 'number') {
n.humanization.randomOffDaysPerWeek = 1
}
// Strong default gestures when enabled (explicit values still win)
if (typeof n.humanization.gestureMoveProb !== 'number') {
n.humanization.gestureMoveProb = n.humanization.enabled === false ? 0 : 0.5
}
if (typeof n.humanization.gestureScrollProb !== 'number') {
n.humanization.gestureScrollProb = n.humanization.enabled === false ? 0 : 0.25
}
// Vacation mode (monthly contiguous off-days)
if (!n.vacation) n.vacation = {}
if (typeof n.vacation.enabled !== 'boolean') n.vacation.enabled = false
const vMin = Number(n.vacation.minDays)
const vMax = Number(n.vacation.maxDays)
n.vacation.minDays = isFinite(vMin) && vMin > 0 ? Math.floor(vMin) : 3
n.vacation.maxDays = isFinite(vMax) && vMax > 0 ? Math.floor(vMax) : 5
if (n.vacation.maxDays < n.vacation.minDays) {
const t = n.vacation.minDays; n.vacation.minDays = n.vacation.maxDays; n.vacation.maxDays = t
}
const cfg: Config = {
baseURL: n.baseURL ?? 'https://rewards.bing.com',
sessionPath: n.sessionPath ?? 'sessions',
headless,
parallel,
runOnZeroPoints,
clusters,
saveFingerprint,
workers,
searchOnBingLocalQueries: !!useLocalQueries,
globalTimeout,
searchSettings,
humanization: n.humanization,
retryPolicy: n.retryPolicy,
jobState: n.jobState,
logExcludeFunc,
webhookLogExcludeFunc,
logging, // retain full logging object for live webhook usage
proxy: n.proxy ?? { proxyGoogleTrends: true, proxyBingTerms: true },
webhook,
conclusionWebhook,
ntfy,
vacation: n.vacation,
crashRecovery: n.crashRecovery || {}
}
return cfg
}
export function loadAccounts(): Account[] {
try {
// 1) CLI dev override
let file = 'accounts.json'
if (process.argv.includes('-dev')) {
file = 'accounts.dev.json'
}
const accountDir = path.join(__dirname, '../', file)
const accounts = fs.readFileSync(accountDir, 'utf-8')
// 2) Docker-friendly env overrides
const envJson = process.env.ACCOUNTS_JSON
const envFile = process.env.ACCOUNTS_FILE
return JSON.parse(accounts)
let json: string | undefined
if (envJson && envJson.trim().startsWith('[')) {
json = envJson
} else if (envFile && envFile.trim()) {
const full = path.isAbsolute(envFile) ? envFile : path.join(process.cwd(), envFile)
if (!fs.existsSync(full)) {
throw new Error(`ACCOUNTS_FILE not found: ${full}`)
}
json = fs.readFileSync(full, 'utf-8')
} else {
// Try multiple locations to support both root mounts and dist mounts
// Support both .json and .json extensions
const candidates = [
path.join(__dirname, '../', file),
path.join(__dirname, '../src', file),
path.join(process.cwd(), file),
path.join(process.cwd(), 'src', file),
path.join(__dirname, file)
]
let chosen: string | null = null
for (const p of candidates) {
try { if (fs.existsSync(p)) { chosen = p; break } } catch { /* ignore */ }
}
if (!chosen) throw new Error(`accounts file not found in: ${candidates.join(' | ')}`)
json = fs.readFileSync(chosen, 'utf-8')
}
// Support comments in accounts file (same as config)
const parsedUnknown = JSON.parse(json)
// Accept either a root array or an object with an `accounts` array, ignore `_note`
const parsed = Array.isArray(parsedUnknown) ? parsedUnknown : (parsedUnknown && typeof parsedUnknown === 'object' && Array.isArray((parsedUnknown as { accounts?: unknown }).accounts) ? (parsedUnknown as { accounts: unknown[] }).accounts : null)
if (!Array.isArray(parsed)) throw new Error('accounts must be an array')
// minimal shape validation
for (const a of parsed) {
if (!a || typeof a.email !== 'string' || typeof a.password !== 'string') {
throw new Error('each account must have email and password strings')
}
}
// Filter out disabled accounts (enabled: false)
const allAccounts = parsed as Account[]
const enabledAccounts = allAccounts.filter(acc => acc.enabled !== false)
return enabledAccounts
} catch (error) {
throw new Error(error as string)
}
}
export function getConfigPath(): string { return configSourcePath }
export function loadConfig(): Config {
try {
if (configCache) {
return configCache
}
const configDir = path.join(__dirname, '../', 'config.json')
const config = fs.readFileSync(configDir, 'utf-8')
// Resolve configuration file from common locations
const names = ['config.json']
const bases = [
path.join(__dirname, '../'), // dist root when compiled
path.join(__dirname, '../src'), // fallback: running dist but config still in src
process.cwd(), // repo root
path.join(process.cwd(), 'src'), // repo/src when running ts-node
__dirname // dist/util
]
const candidates: string[] = []
for (const base of bases) {
for (const name of names) {
candidates.push(path.join(base, name))
}
}
let cfgPath: string | null = null
for (const p of candidates) {
try { if (fs.existsSync(p)) { cfgPath = p; break } } catch { /* ignore */ }
}
if (!cfgPath) throw new Error(`config.json not found in: ${candidates.join(' | ')}`)
const config = fs.readFileSync(cfgPath, 'utf-8')
const json = config.replace(/^\uFEFF/, '')
const raw = JSON.parse(json)
const normalized = normalizeConfig(raw)
configCache = normalized // Set as cache
configSourcePath = cfgPath
const configData = JSON.parse(config)
configCache = configData
return configData
return normalized
} catch (error) {
throw new Error(error as string)
}
}
export async function loadSessionData(
sessionPath: string,
email: string,
saveFingerprint: ConfigSaveFingerprint,
isMobile: boolean
) {
export async function loadSessionData(sessionPath: string, email: string, isMobile: boolean, saveFingerprint: ConfigSaveFingerprint) {
try {
const cookiesFileName = isMobile ? 'session_mobile.json' : 'session_desktop.json'
const cookieFile = path.join(__dirname, '../browser/', sessionPath, email, cookiesFileName)
// Fetch cookie file
const cookieFile = path.join(__dirname, '../browser/', sessionPath, email, `${isMobile ? 'mobile_cookies' : 'desktop_cookies'}.json`)
let cookies: Cookie[] = []
if (fs.existsSync(cookieFile)) {
@@ -59,40 +237,45 @@ export async function loadSessionData(
cookies = JSON.parse(cookiesData)
}
const fingerprintFileName = isMobile ? 'session_fingerprint_mobile.json' : 'session_fingerprint_desktop.json'
const fingerprintFile = path.join(__dirname, '../browser/', sessionPath, email, fingerprintFileName)
// Fetch fingerprint file (support both legacy typo "fingerpint" and corrected "fingerprint")
const baseDir = path.join(__dirname, '../browser/', sessionPath, email)
const legacyFile = path.join(baseDir, `${isMobile ? 'mobile_fingerpint' : 'desktop_fingerpint'}.json`)
const correctFile = path.join(baseDir, `${isMobile ? 'mobile_fingerprint' : 'desktop_fingerprint'}.json`)
let fingerprint!: BrowserFingerprintWithHeaders
const shouldLoadFingerprint = isMobile ? saveFingerprint.mobile : saveFingerprint.desktop
if (shouldLoadFingerprint && fs.existsSync(fingerprintFile)) {
const fingerprintData = await fs.promises.readFile(fingerprintFile, 'utf-8')
fingerprint = JSON.parse(fingerprintData)
const shouldLoad = (saveFingerprint.desktop && !isMobile) || (saveFingerprint.mobile && isMobile)
if (shouldLoad) {
const chosen = fs.existsSync(correctFile) ? correctFile : (fs.existsSync(legacyFile) ? legacyFile : '')
if (chosen) {
const fingerprintData = await fs.promises.readFile(chosen, 'utf-8')
fingerprint = JSON.parse(fingerprintData)
}
}
return {
cookies: cookies,
fingerprint: fingerprint
}
} catch (error) {
throw new Error(error as string)
}
}
export async function saveSessionData(
sessionPath: string,
cookies: Cookie[],
email: string,
isMobile: boolean
): Promise<string> {
export async function saveSessionData(sessionPath: string, browser: BrowserContext, email: string, isMobile: boolean): Promise<string> {
try {
const sessionDir = path.join(__dirname, '../browser/', sessionPath, email)
const cookiesFileName = isMobile ? 'session_mobile.json' : 'session_desktop.json'
const cookies = await browser.cookies()
// Fetch path
const sessionDir = path.join(__dirname, '../browser/', sessionPath, email)
// Create session dir
if (!fs.existsSync(sessionDir)) {
await fs.promises.mkdir(sessionDir, { recursive: true })
}
await fs.promises.writeFile(path.join(sessionDir, cookiesFileName), JSON.stringify(cookies))
// Save cookies to a file
await fs.promises.writeFile(path.join(sessionDir, `${isMobile ? 'mobile_cookies' : 'desktop_cookies'}.json`), JSON.stringify(cookies))
return sessionDir
} catch (error) {
@@ -100,21 +283,22 @@ export async function saveSessionData(
}
}
export async function saveFingerprintData(
sessionPath: string,
email: string,
isMobile: boolean,
fingerpint: BrowserFingerprintWithHeaders
): Promise<string> {
export async function saveFingerprintData(sessionPath: string, email: string, isMobile: boolean, fingerprint: BrowserFingerprintWithHeaders): Promise<string> {
try {
// Fetch path
const sessionDir = path.join(__dirname, '../browser/', sessionPath, email)
const fingerprintFileName = isMobile ? 'session_fingerprint_mobile.json' : 'session_fingerprint_desktop.json'
// Create session dir
if (!fs.existsSync(sessionDir)) {
await fs.promises.mkdir(sessionDir, { recursive: true })
}
await fs.promises.writeFile(path.join(sessionDir, fingerprintFileName), JSON.stringify(fingerpint))
// Save fingerprint to files (write both legacy and corrected names for compatibility)
const legacy = path.join(sessionDir, `${isMobile ? 'mobile_fingerpint' : 'desktop_fingerpint'}.json`)
const correct = path.join(sessionDir, `${isMobile ? 'mobile_fingerprint' : 'desktop_fingerprint'}.json`)
const payload = JSON.stringify(fingerprint)
await fs.promises.writeFile(correct, payload)
try { await fs.promises.writeFile(legacy, payload) } catch { /* ignore */ }
return sessionDir
} catch (error) {

249
src/util/Logger.ts Normal file
View File

@@ -0,0 +1,249 @@
import axios from 'axios'
import chalk from 'chalk'
import { Ntfy } from './Ntfy'
import { loadConfig } from './Load'
import { DISCORD } from '../constants'
type WebhookBuffer = {
lines: string[]
sending: boolean
timer?: NodeJS.Timeout
}
const webhookBuffers = new Map<string, WebhookBuffer>()
// Periodic cleanup of old/idle webhook buffers to prevent memory leaks
setInterval(() => {
const now = Date.now()
const BUFFER_MAX_AGE_MS = 3600000 // 1 hour
for (const [url, buf] of webhookBuffers.entries()) {
if (!buf.sending && buf.lines.length === 0) {
const lastActivity = (buf as unknown as { lastActivity?: number }).lastActivity || 0
if (now - lastActivity > BUFFER_MAX_AGE_MS) {
webhookBuffers.delete(url)
}
}
}
}, 600000) // Check every 10 minutes
function getBuffer(url: string): WebhookBuffer {
let buf = webhookBuffers.get(url)
if (!buf) {
buf = { lines: [], sending: false }
webhookBuffers.set(url, buf)
}
// Track last activity for cleanup
(buf as unknown as { lastActivity: number }).lastActivity = Date.now()
return buf
}
async function sendBatch(url: string, buf: WebhookBuffer) {
if (buf.sending) return
buf.sending = true
while (buf.lines.length > 0) {
const chunk: string[] = []
let currentLength = 0
while (buf.lines.length > 0) {
const next = buf.lines[0]!
const projected = currentLength + next.length + (chunk.length > 0 ? 1 : 0)
if (projected > DISCORD.MAX_EMBED_LENGTH && chunk.length > 0) break
buf.lines.shift()
chunk.push(next)
currentLength = projected
}
const content = chunk.join('\n').slice(0, DISCORD.MAX_EMBED_LENGTH)
if (!content) {
continue
}
// Enhanced webhook payload with embed, username and avatar
const payload = {
embeds: [{
description: `\`\`\`\n${content}\n\`\`\``,
color: determineColorFromContent(content),
timestamp: new Date().toISOString()
}]
}
try {
await axios.post(url, payload, { headers: { 'Content-Type': 'application/json' }, timeout: DISCORD.WEBHOOK_TIMEOUT })
await new Promise(resolve => setTimeout(resolve, DISCORD.RATE_LIMIT_DELAY))
} catch (error) {
// Re-queue failed batch at front and exit loop
buf.lines = chunk.concat(buf.lines)
console.error('[Webhook] live log delivery failed:', error)
break
}
}
buf.sending = false
}
function determineColorFromContent(content: string): number {
const lower = content.toLowerCase()
// Security/Ban alerts - Red
if (lower.includes('[banned]') || lower.includes('[security]') || lower.includes('suspended') || lower.includes('compromised')) {
return DISCORD.COLOR_RED
}
// Errors - Dark Red
if (lower.includes('[error]') || lower.includes('✗')) {
return DISCORD.COLOR_CRIMSON
}
// Warnings - Orange/Yellow
if (lower.includes('[warn]') || lower.includes('⚠')) {
return DISCORD.COLOR_ORANGE
}
// Success - Green
if (lower.includes('[ok]') || lower.includes('✓') || lower.includes('complet')) {
return DISCORD.COLOR_GREEN
}
// Info/Main - Blue
if (lower.includes('[main]')) {
return DISCORD.COLOR_BLUE
}
// Default - Gray
return 0x95A5A6 // Gray
}
function enqueueWebhookLog(url: string, line: string) {
const buf = getBuffer(url)
buf.lines.push(line)
if (!buf.timer) {
buf.timer = setTimeout(() => {
buf.timer = undefined
void sendBatch(url, buf)
}, DISCORD.DEBOUNCE_DELAY)
}
}
// Synchronous logger that returns an Error when type === 'error' so callers can `throw log(...)` safely.
export function log(isMobile: boolean | 'main', title: string, message: string, type: 'log' | 'warn' | 'error' = 'log', color?: keyof typeof chalk): Error | void {
const configData = loadConfig()
// Access logging config with fallback for backward compatibility
const configAny = configData as unknown as Record<string, unknown>
const logging = configAny.logging as { excludeFunc?: string[]; logExcludeFunc?: string[] } | undefined
const logExcludeFunc = logging?.excludeFunc ?? (configData as { logExcludeFunc?: string[] }).logExcludeFunc ?? []
if (logExcludeFunc.some((x: string) => x.toLowerCase() === title.toLowerCase())) {
return
}
const currentTime = new Date().toLocaleString()
const platformText = isMobile === 'main' ? 'MAIN' : isMobile ? 'MOBILE' : 'DESKTOP'
// Clean string for notifications (no chalk, structured)
type LoggingCfg = { excludeFunc?: string[]; webhookExcludeFunc?: string[]; redactEmails?: boolean }
const loggingCfg: LoggingCfg = (configAny.logging || {}) as LoggingCfg
const shouldRedact = !!loggingCfg.redactEmails
const redact = (s: string) => shouldRedact ? s.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/ig, (m) => {
const [u, d] = m.split('@'); return `${(u || '').slice(0, 2)}***@${d || ''}`
}) : s
const cleanStr = redact(`[${currentTime}] [PID: ${process.pid}] [${type.toUpperCase()}] ${platformText} [${title}] ${message}`)
// Define conditions for sending to NTFY
const ntfyConditions = {
log: [
message.toLowerCase().includes('started tasks for account'),
message.toLowerCase().includes('press the number'),
message.toLowerCase().includes('no points to earn')
],
error: [],
warn: [
message.toLowerCase().includes('aborting'),
message.toLowerCase().includes('didn\'t gain')
]
}
// Check if the current log type and message meet the NTFY conditions
try {
if (type in ntfyConditions && ntfyConditions[type as keyof typeof ntfyConditions].some(condition => condition)) {
// Fire-and-forget
Promise.resolve(Ntfy(cleanStr, type)).catch(() => { /* ignore ntfy errors */ })
}
} catch { /* ignore */ }
// Console output with better formatting and contextual icons
const typeIndicator = type === 'error' ? '✗' : type === 'warn' ? '⚠' : '✓'
const platformColor = isMobile === 'main' ? chalk.cyan : isMobile ? chalk.blue : chalk.magenta
const typeColor = type === 'error' ? chalk.red : type === 'warn' ? chalk.yellow : chalk.green
// Add contextual icon based on title/message (ASCII-safe for Windows PowerShell)
const titleLower = title.toLowerCase()
const msgLower = message.toLowerCase()
// ASCII-safe icons for Windows PowerShell compatibility
const iconMap: Array<[RegExp, string]> = [
[/security|compromised/i, '[SECURITY]'],
[/ban|suspend/i, '[BANNED]'],
[/error/i, '[ERROR]'],
[/warn/i, '[WARN]'],
[/success|complet/i, '[OK]'],
[/login/i, '[LOGIN]'],
[/point/i, '[POINTS]'],
[/search/i, '[SEARCH]'],
[/activity|quiz|poll/i, '[ACTIVITY]'],
[/browser/i, '[BROWSER]'],
[/main/i, '[MAIN]']
]
let icon = ''
for (const [pattern, symbol] of iconMap) {
if (pattern.test(titleLower) || pattern.test(msgLower)) {
icon = chalk.dim(symbol)
break
}
}
const iconPart = icon ? icon + ' ' : ''
const formattedStr = [
chalk.gray(`[${currentTime}]`),
chalk.gray(`[${process.pid}]`),
typeColor(`${typeIndicator}`),
platformColor(`[${platformText}]`),
chalk.bold(`[${title}]`),
iconPart + redact(message)
].join(' ')
const applyChalk = color && typeof chalk[color] === 'function' ? chalk[color] as (msg: string) => string : null
// Log based on the type
switch (type) {
case 'warn':
applyChalk ? console.warn(applyChalk(formattedStr)) : console.warn(formattedStr)
break
case 'error':
applyChalk ? console.error(applyChalk(formattedStr)) : console.error(formattedStr)
break
default:
applyChalk ? console.log(applyChalk(formattedStr)) : console.log(formattedStr)
break
}
// Webhook streaming (live logs)
try {
const loggingCfg: Record<string, unknown> = (configAny.logging || {}) as Record<string, unknown>
const webhookCfg = configData.webhook
const liveUrlRaw = typeof loggingCfg.liveWebhookUrl === 'string' ? loggingCfg.liveWebhookUrl.trim() : ''
const liveUrl = liveUrlRaw || (webhookCfg?.enabled && webhookCfg.url ? webhookCfg.url : '')
const webhookExclude = Array.isArray(loggingCfg.webhookExcludeFunc) ? loggingCfg.webhookExcludeFunc : configData.webhookLogExcludeFunc || []
const webhookExcluded = Array.isArray(webhookExclude) && webhookExclude.some((x: string) => x.toLowerCase() === title.toLowerCase())
if (liveUrl && !webhookExcluded) {
enqueueWebhookLog(liveUrl, cleanStr)
}
} catch (error) {
console.error('[Logger] Failed to enqueue webhook log:', error)
}
// Return an Error when logging an error so callers can `throw log(...)`
if (type === 'error') {
// CommunityReporter disabled per project policy
return new Error(cleanStr)
}
}

27
src/util/Ntfy.ts Normal file
View File

@@ -0,0 +1,27 @@
import { loadConfig } from './Load'
import axios from 'axios'
const NOTIFICATION_TYPES = {
error: { priority: 'max', tags: 'rotating_light' }, // Customize the ERROR icon here, see: https://docs.ntfy.sh/emojis/
warn: { priority: 'high', tags: 'warning' }, // Customize the WARN icon here, see: https://docs.ntfy.sh/emojis/
log: { priority: 'default', tags: 'medal_sports' } // Customize the LOG icon here, see: https://docs.ntfy.sh/emojis/
}
export async function Ntfy(message: string, type: keyof typeof NOTIFICATION_TYPES = 'log'): Promise<void> {
const config = loadConfig().ntfy
if (!config?.enabled || !config.url || !config.topic) return
try {
const { priority, tags } = NOTIFICATION_TYPES[type]
const headers = {
Title: 'Microsoft Rewards Script',
Priority: priority,
Tags: tags,
...(config.authToken && { Authorization: `Bearer ${config.authToken}` })
}
await axios.post(`${config.url}/${config.topic}`, message, { headers })
} catch (error) {
// Silently fail - NTFY is a non-critical notification service
}
}

View File

@@ -0,0 +1,340 @@
import axios from 'axios'
export interface QuerySource {
name: string
weight: number // 0-1, probability of selection
fetchQueries: () => Promise<string[]>
}
export interface QueryDiversityConfig {
sources: Array<'google-trends' | 'reddit' | 'news' | 'wikipedia' | 'local-fallback'>
deduplicate: boolean
mixStrategies: boolean // Mix different source types in same session
maxQueriesPerSource: number
cacheMinutes: number
}
/**
* QueryDiversityEngine fetches search queries from multiple sources to avoid patterns.
* Supports Google Trends, Reddit, News APIs, Wikipedia, and local fallbacks.
*/
export class QueryDiversityEngine {
private config: QueryDiversityConfig
private cache: Map<string, { queries: string[]; expires: number }> = new Map()
constructor(config?: Partial<QueryDiversityConfig>) {
this.config = {
sources: config?.sources || ['google-trends', 'reddit', 'local-fallback'],
deduplicate: config?.deduplicate !== false,
mixStrategies: config?.mixStrategies !== false,
maxQueriesPerSource: config?.maxQueriesPerSource || 10,
cacheMinutes: config?.cacheMinutes || 30
}
}
/**
* Fetch diverse queries from configured sources
*/
async fetchQueries(count: number): Promise<string[]> {
const allQueries: string[] = []
for (const sourceName of this.config.sources) {
try {
const queries = await this.getFromSource(sourceName)
allQueries.push(...queries.slice(0, this.config.maxQueriesPerSource))
} catch (error) {
// Silently fail and try other sources
}
}
// Deduplicate
let final = this.config.deduplicate ? Array.from(new Set(allQueries)) : allQueries
// Mix strategies: interleave queries from different sources
if (this.config.mixStrategies && this.config.sources.length > 1) {
final = this.interleaveQueries(final, count)
}
// Shuffle and limit to requested count
final = this.shuffleArray(final).slice(0, count)
return final.length > 0 ? final : this.getLocalFallback(count)
}
/**
* Fetch from a specific source with caching
*/
private async getFromSource(source: string): Promise<string[]> {
const cached = this.cache.get(source)
if (cached && Date.now() < cached.expires) {
return cached.queries
}
let queries: string[] = []
switch (source) {
case 'google-trends':
queries = await this.fetchGoogleTrends()
break
case 'reddit':
queries = await this.fetchReddit()
break
case 'news':
queries = await this.fetchNews()
break
case 'wikipedia':
queries = await this.fetchWikipedia()
break
case 'local-fallback':
queries = this.getLocalFallback(20)
break
default:
// Unknown source, skip silently
break
}
this.cache.set(source, {
queries,
expires: Date.now() + (this.config.cacheMinutes * 60000)
})
return queries
}
/**
* Fetch from Google Trends (existing logic can be reused)
*/
private async fetchGoogleTrends(): Promise<string[]> {
try {
const response = await axios.get('https://trends.google.com/trends/api/dailytrends?geo=US', {
timeout: 10000
})
const data = response.data.toString().replace(')]}\',', '')
const parsed = JSON.parse(data)
const queries: string[] = []
for (const item of parsed.default.trendingSearchesDays || []) {
for (const search of item.trendingSearches || []) {
if (search.title?.query) {
queries.push(search.title.query)
}
}
}
return queries.slice(0, 20)
} catch {
return []
}
}
/**
* Fetch from Reddit (top posts from popular subreddits)
*/
private async fetchReddit(): Promise<string[]> {
try {
const subreddits = ['news', 'worldnews', 'todayilearned', 'askreddit', 'technology']
const randomSub = subreddits[Math.floor(Math.random() * subreddits.length)]
const response = await axios.get(`https://www.reddit.com/r/${randomSub}/hot.json?limit=15`, {
timeout: 10000,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
})
const posts = response.data.data.children || []
const queries: string[] = []
for (const post of posts) {
const title = post.data?.title
if (title && title.length > 10 && title.length < 100) {
queries.push(title)
}
}
return queries
} catch {
return []
}
}
/**
* Fetch from News API (requires API key - fallback to headlines scraping)
*/
private async fetchNews(): Promise<string[]> {
try {
// Using NewsAPI.org free tier (limited requests)
const apiKey = process.env.NEWS_API_KEY
if (!apiKey) {
return this.fetchNewsFallback()
}
const response = await axios.get('https://newsapi.org/v2/top-headlines', {
params: {
country: 'us',
pageSize: 15,
apiKey
},
timeout: 10000
})
const articles = response.data.articles || []
return articles.map((a: { title?: string }) => a.title).filter((t: string | undefined) => t && t.length > 10)
} catch {
return this.fetchNewsFallback()
}
}
/**
* Fallback news scraper (BBC/CNN headlines)
*/
private async fetchNewsFallback(): Promise<string[]> {
try {
const response = await axios.get('https://www.bbc.com/news', {
timeout: 10000,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
})
const html = response.data
const regex = /<h3[^>]*>(.*?)<\/h3>/gi
const matches: RegExpMatchArray[] = []
let match
while ((match = regex.exec(html)) !== null) {
matches.push(match)
}
return matches
.map(m => m[1]?.replace(/<[^>]+>/g, '').trim())
.filter((t: string | undefined) => t && t.length > 10 && t.length < 100)
.slice(0, 10) as string[]
} catch {
return []
}
}
/**
* Fetch from Wikipedia (featured articles / trending topics)
*/
private async fetchWikipedia(): Promise<string[]> {
try {
const response = await axios.get('https://en.wikipedia.org/w/api.php', {
params: {
action: 'query',
list: 'random',
rnnamespace: 0,
rnlimit: 15,
format: 'json'
},
timeout: 10000
})
const pages = response.data.query?.random || []
return pages.map((p: { title?: string }) => p.title).filter((t: string | undefined) => t && t.length > 3)
} catch {
return []
}
}
/**
* Local fallback queries (curated list)
*/
private getLocalFallback(count: number): string[] {
const fallback = [
'weather forecast',
'news today',
'stock market',
'sports scores',
'movie reviews',
'recipes',
'travel destinations',
'health tips',
'technology news',
'best restaurants near me',
'how to cook pasta',
'python tutorial',
'world events',
'climate change',
'electric vehicles',
'space exploration',
'artificial intelligence',
'cryptocurrency',
'gaming news',
'fashion trends',
'fitness workout',
'home improvement',
'gardening tips',
'pet care',
'book recommendations',
'music charts',
'streaming shows',
'historical events',
'science discoveries',
'education resources'
]
return this.shuffleArray(fallback).slice(0, count)
}
/**
* Interleave queries from different sources for diversity
*/
private interleaveQueries(queries: string[], targetCount: number): string[] {
const result: string[] = []
const sourceMap = new Map<string, string[]>()
// Group queries by estimated source (simple heuristic)
for (const q of queries) {
const source = this.guessSource(q)
if (!sourceMap.has(source)) {
sourceMap.set(source, [])
}
sourceMap.get(source)?.push(q)
}
const sources = Array.from(sourceMap.values())
let index = 0
while (result.length < targetCount && sources.some(s => s.length > 0)) {
const source = sources[index % sources.length]
if (source && source.length > 0) {
const q = source.shift()
if (q) result.push(q)
}
index++
}
return result
}
/**
* Guess which source a query came from (basic heuristic)
*/
private guessSource(query: string): string {
if (/^[A-Z]/.test(query) && query.includes(' ')) return 'news'
if (query.length > 80) return 'reddit'
if (/how to|what is|why/i.test(query)) return 'local'
return 'trends'
}
/**
* Shuffle array (Fisher-Yates)
*/
private shuffleArray<T>(array: T[]): T[] {
const shuffled = [...array]
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j]!, shuffled[i]!]
}
return shuffled
}
/**
* Clear cache (call between runs)
*/
clearCache(): void {
this.cache.clear()
}
}

63
src/util/Retry.ts Normal file
View File

@@ -0,0 +1,63 @@
import type { ConfigRetryPolicy } from '../interface/Config'
import Util from './Utils'
type NumericPolicy = {
maxAttempts: number
baseDelay: number
maxDelay: number
multiplier: number
jitter: number
}
export type Retryable<T> = () => Promise<T>
export class Retry {
private policy: NumericPolicy
constructor(policy?: ConfigRetryPolicy) {
const def: NumericPolicy = {
maxAttempts: 3,
baseDelay: 1000,
maxDelay: 30000,
multiplier: 2,
jitter: 0.2
}
const merged: ConfigRetryPolicy = { ...(policy || {}) }
// normalize string durations
const util = new Util()
const parse = (v: number | string) => {
if (typeof v === 'number') return v
try { return util.stringToMs(String(v)) } catch { return def.baseDelay }
}
this.policy = {
maxAttempts: (merged.maxAttempts as number) ?? def.maxAttempts,
baseDelay: parse(merged.baseDelay ?? def.baseDelay),
maxDelay: parse(merged.maxDelay ?? def.maxDelay),
multiplier: (merged.multiplier as number) ?? def.multiplier,
jitter: (merged.jitter as number) ?? def.jitter
}
}
async run<T>(fn: Retryable<T>, isRetryable?: (e: unknown) => boolean): Promise<T> {
let attempt = 0
let delay = this.policy.baseDelay
let lastErr: unknown
while (attempt < this.policy.maxAttempts) {
try {
return await fn()
} catch (e) {
lastErr = e
attempt += 1
const retry = isRetryable ? isRetryable(e) : true
if (!retry || attempt >= this.policy.maxAttempts) break
const jitter = 1 + (Math.random() * 2 - 1) * this.policy.jitter
const sleep = Math.min(this.policy.maxDelay, Math.max(0, Math.floor(delay * jitter)))
await new Promise((r) => setTimeout(r, sleep))
delay = Math.min(this.policy.maxDelay, Math.floor(delay * (this.policy.multiplier || 2)))
}
}
throw lastErr instanceof Error ? lastErr : new Error(String(lastErr))
}
}
export default Retry

84
src/util/Totp.ts Normal file
View File

@@ -0,0 +1,84 @@
import crypto from 'crypto'
/**
* Decode Base32 (RFC 4648) to a Buffer.
* Accepts lowercase/uppercase, optional padding.
*/
function base32Decode(input: string): Buffer {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
const clean = input.toUpperCase().replace(/=+$/g, '').replace(/[^A-Z2-7]/g, '')
let bits = 0
let value = 0
const bytes: number[] = []
for (const char of clean) {
const idx = alphabet.indexOf(char)
if (idx < 0) continue
value = (value << 5) | idx
bits += 5
if (bits >= 8) {
bits -= 8
bytes.push((value >>> bits) & 0xff)
}
}
return Buffer.from(bytes)
}
/**
* Generate an HMAC using Node's crypto and return Buffer.
*/
function hmac(algorithm: string, key: Buffer, data: Buffer): Buffer {
return crypto.createHmac(algorithm, key).update(data).digest()
}
export type TotpOptions = { digits?: number; step?: number; algorithm?: 'SHA1' | 'SHA256' | 'SHA512' }
/**
* Generate TOTP per RFC 6238.
* @param secretBase32 - shared secret in Base32
* @param time - Unix time in seconds (defaults to now)
* @param options - { digits, step, algorithm }
* @returns numeric TOTP as string (zero-padded)
*/
export function generateTOTP(
secretBase32: string,
time: number = Math.floor(Date.now() / 1000),
options?: TotpOptions
): string {
const digits = options?.digits ?? 6
const step = options?.step ?? 30
const alg = (options?.algorithm ?? 'SHA1').toUpperCase()
const key = base32Decode(secretBase32)
const counter = Math.floor(time / step)
// 8-byte big-endian counter
const counterBuffer = Buffer.alloc(8)
counterBuffer.writeBigUInt64BE(BigInt(counter), 0)
let hmacAlg: string
if (alg === 'SHA1') hmacAlg = 'sha1'
else if (alg === 'SHA256') hmacAlg = 'sha256'
else if (alg === 'SHA512') hmacAlg = 'sha512'
else throw new Error('Unsupported algorithm. Use SHA1, SHA256 or SHA512.')
const hash = hmac(hmacAlg, key, counterBuffer)
if (!hash || hash.length < 20) {
// Minimal sanity check; for SHA1 length is 20
throw new Error('Invalid HMAC output for TOTP')
}
// Dynamic truncation
const offset = hash[hash.length - 1]! & 0x0f
if (offset + 3 >= hash.length) {
throw new Error('Invalid dynamic truncation offset')
}
const code =
((hash[offset]! & 0x7f) << 24) |
((hash[offset + 1]! & 0xff) << 16) |
((hash[offset + 2]! & 0xff) << 8) |
(hash[offset + 3]! & 0xff)
const otp = (code % 10 ** digits).toString().padStart(digits, '0')
return otp
}

282
src/util/UserAgent.ts Normal file
View File

@@ -0,0 +1,282 @@
import axios from 'axios'
import { BrowserFingerprintWithHeaders } from 'fingerprint-generator'
import { log } from './Logger'
import Retry from './Retry'
import { ChromeVersion, EdgeVersion, Architecture, Platform } from '../interface/UserAgentUtil'
const NOT_A_BRAND_VERSION = '99'
const EDGE_VERSION_URL = 'https://edgeupdates.microsoft.com/api/products'
const EDGE_VERSION_CACHE_TTL_MS = 1000 * 60 * 60
type EdgeVersionResult = {
android?: string
windows?: string
}
let edgeVersionCache: { data: EdgeVersionResult; expiresAt: number } | null = null
let edgeVersionInFlight: Promise<EdgeVersionResult> | null = null
export async function getUserAgent(isMobile: boolean) {
const system = getSystemComponents(isMobile)
const app = await getAppComponents(isMobile)
const uaTemplate = isMobile ?
`Mozilla/5.0 (${system}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${app.chrome_reduced_version} Mobile Safari/537.36 EdgA/${app.edge_version}` :
`Mozilla/5.0 (${system}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${app.chrome_reduced_version} Safari/537.36 Edg/${app.edge_version}`
const platformVersion = `${isMobile ? Math.floor(Math.random() * 5) + 9 : Math.floor(Math.random() * 15) + 1}.0.0`
const uaMetadata = {
mobile: isMobile,
isMobile,
platform: isMobile ? 'Android' : 'Windows',
fullVersionList: [
{ brand: 'Not/A)Brand', version: `${NOT_A_BRAND_VERSION}.0.0.0` },
{ brand: 'Microsoft Edge', version: app['edge_version'] },
{ brand: 'Chromium', version: app['chrome_version'] }
],
brands: [
{ brand: 'Not/A)Brand', version: NOT_A_BRAND_VERSION },
{ brand: 'Microsoft Edge', version: app['edge_major_version'] },
{ brand: 'Chromium', version: app['chrome_major_version'] }
],
platformVersion,
architecture: isMobile ? '' : 'x86',
bitness: isMobile ? '' : '64',
model: '',
uaFullVersion: app['chrome_version']
}
return { userAgent: uaTemplate, userAgentMetadata: uaMetadata }
}
export async function getChromeVersion(isMobile: boolean): Promise<string> {
try {
const request = {
url: 'https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions.json',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
const response = await axios(request)
const data: ChromeVersion = response.data
return data.channels.Stable.version
} catch (error) {
throw log(isMobile, 'USERAGENT-CHROME-VERSION', 'An error occurred:' + error, 'error')
}
}
export async function getEdgeVersions(isMobile: boolean) {
const now = Date.now()
if (edgeVersionCache && edgeVersionCache.expiresAt > now) {
return edgeVersionCache.data
}
if (edgeVersionInFlight) {
try {
return await edgeVersionInFlight
} catch (error) {
if (edgeVersionCache) {
log(isMobile, 'USERAGENT-EDGE-VERSION', 'Using cached Edge versions after in-flight failure: ' + formatEdgeError(error), 'warn')
return edgeVersionCache.data
}
throw error
}
}
const fetchPromise = fetchEdgeVersionsWithRetry(isMobile)
.then(result => {
edgeVersionCache = { data: result, expiresAt: Date.now() + EDGE_VERSION_CACHE_TTL_MS }
edgeVersionInFlight = null
return result
})
.catch(error => {
edgeVersionInFlight = null
if (edgeVersionCache) {
log(isMobile, 'USERAGENT-EDGE-VERSION', 'Falling back to cached Edge versions: ' + formatEdgeError(error), 'warn')
return edgeVersionCache.data
}
throw log(isMobile, 'USERAGENT-EDGE-VERSION', 'Failed to fetch Edge versions: ' + formatEdgeError(error), 'error')
})
edgeVersionInFlight = fetchPromise
return fetchPromise
}
export function getSystemComponents(mobile: boolean): string {
if (mobile) {
const androidVersion = 10 + Math.floor(Math.random() * 5)
return `Linux; Android ${androidVersion}; K`
}
return 'Windows NT 10.0; Win64; x64'
}
export async function getAppComponents(isMobile: boolean) {
const versions = await getEdgeVersions(isMobile)
const edgeVersion = isMobile ? versions.android : versions.windows as string
const edgeMajorVersion = edgeVersion?.split('.')[0]
const chromeVersion = await getChromeVersion(isMobile)
const chromeMajorVersion = chromeVersion?.split('.')[0]
const chromeReducedVersion = `${chromeMajorVersion}.0.0.0`
return {
not_a_brand_version: `${NOT_A_BRAND_VERSION}.0.0.0`,
not_a_brand_major_version: NOT_A_BRAND_VERSION,
edge_version: edgeVersion as string,
edge_major_version: edgeMajorVersion as string,
chrome_version: chromeVersion as string,
chrome_major_version: chromeMajorVersion as string,
chrome_reduced_version: chromeReducedVersion as string
}
}
async function fetchEdgeVersionsWithRetry(isMobile: boolean): Promise<EdgeVersionResult> {
const retry = new Retry()
return retry.run(async () => {
const versions = await fetchEdgeVersionsOnce(isMobile)
if (!versions.android && !versions.windows) {
throw new Error('Stable Edge releases did not include Android or Windows versions')
}
return versions
}, () => true)
}
async function fetchEdgeVersionsOnce(isMobile: boolean): Promise<EdgeVersionResult> {
try {
const response = await axios<EdgeVersion[]>({
url: EDGE_VERSION_URL,
method: 'GET',
headers: {
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (compatible; rewards-bot/2.1)' // Provide UA to avoid stricter servers
},
timeout: 10000
})
return mapEdgeVersions(response.data)
} catch (primaryError) {
const fallback = await tryNativeFetchFallback(isMobile)
if (fallback) {
log(isMobile, 'USERAGENT-EDGE-VERSION', 'Axios failed, native fetch succeeded: ' + formatEdgeError(primaryError), 'warn')
return fallback
}
throw primaryError
}
}
async function tryNativeFetchFallback(isMobile: boolean): Promise<EdgeVersionResult | null> {
let timeoutHandle: NodeJS.Timeout | undefined
try {
const controller = new AbortController()
timeoutHandle = setTimeout(() => controller.abort(), 10000)
const response = await fetch(EDGE_VERSION_URL, {
headers: {
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (compatible; rewards-bot/2.1)'
},
signal: controller.signal
})
clearTimeout(timeoutHandle)
timeoutHandle = undefined
if (!response.ok) {
throw new Error('HTTP ' + response.status)
}
const data = await response.json() as EdgeVersion[]
return mapEdgeVersions(data)
} catch (error) {
if (timeoutHandle) clearTimeout(timeoutHandle)
log(isMobile, 'USERAGENT-EDGE-VERSION', 'Native fetch fallback failed: ' + formatEdgeError(error), 'warn')
return null
}
}
function mapEdgeVersions(data: EdgeVersion[]): EdgeVersionResult {
const stable = data.find(entry => entry.Product.toLowerCase() === 'stable')
?? data.find(entry => /stable/i.test(entry.Product))
if (!stable) {
throw new Error('Stable Edge channel not found in response payload')
}
const androidRelease = stable.Releases.find(release => release.Platform === Platform.Android)
const windowsRelease = stable.Releases.find(release => release.Platform === Platform.Windows && release.Architecture === Architecture.X64)
?? stable.Releases.find(release => release.Platform === Platform.Windows)
return {
android: androidRelease?.ProductVersion,
windows: windowsRelease?.ProductVersion
}
}
function formatEdgeError(error: unknown): string {
if (isAggregateErrorLike(error)) {
const inner = error.errors
.map(innerErr => formatEdgeError(innerErr))
.filter(Boolean)
.join('; ')
const message = error.message || 'AggregateError'
return inner ? `${message} | causes: ${inner}` : message
}
if (error instanceof Error) {
const parts = [`${error.name}: ${error.message}`]
const cause = getErrorCause(error)
if (cause) {
parts.push('cause => ' + formatEdgeError(cause))
}
return parts.join(' | ')
}
return String(error)
}
type AggregateErrorLike = { message?: string; errors: unknown[] }
function isAggregateErrorLike(error: unknown): error is AggregateErrorLike {
if (!error || typeof error !== 'object') {
return false
}
const candidate = error as { errors?: unknown }
return Array.isArray(candidate.errors)
}
function getErrorCause(error: { cause?: unknown } | Error): unknown {
if (typeof (error as { cause?: unknown }).cause === 'undefined') {
return undefined
}
return (error as { cause?: unknown }).cause
}
export async function updateFingerprintUserAgent(fingerprint: BrowserFingerprintWithHeaders, isMobile: boolean): Promise<BrowserFingerprintWithHeaders> {
try {
const userAgentData = await getUserAgent(isMobile)
const componentData = await getAppComponents(isMobile)
fingerprint.fingerprint.navigator.userAgentData = userAgentData.userAgentMetadata
fingerprint.fingerprint.navigator.userAgent = userAgentData.userAgent
fingerprint.fingerprint.navigator.appVersion = userAgentData.userAgent.replace(`${fingerprint.fingerprint.navigator.appCodeName}/`, '')
fingerprint.headers['user-agent'] = userAgentData.userAgent
fingerprint.headers['sec-ch-ua'] = `"Microsoft Edge";v="${componentData.edge_major_version}", "Not=A?Brand";v="${componentData.not_a_brand_major_version}", "Chromium";v="${componentData.chrome_major_version}"`
fingerprint.headers['sec-ch-ua-full-version-list'] = `"Microsoft Edge";v="${componentData.edge_version}", "Not=A?Brand";v="${componentData.not_a_brand_version}", "Chromium";v="${componentData.chrome_version}"`
/*
Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Mobile Safari/537.36 EdgA/129.0.0.0
sec-ch-ua-full-version-list: "Microsoft Edge";v="129.0.2792.84", "Not=A?Brand";v="8.0.0.0", "Chromium";v="129.0.6668.90"
sec-ch-ua: "Microsoft Edge";v="129", "Not=A?Brand";v="8", "Chromium";v="129"
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36
"Google Chrome";v="129.0.6668.90", "Not=A?Brand";v="8.0.0.0", "Chromium";v="129.0.6668.90"
*/
return fingerprint
} catch (error) {
throw log(isMobile, 'USER-AGENT-UPDATE', 'An error occurred:' + error, 'error')
}
}

View File

@@ -1,19 +1,29 @@
import ms, { StringValue } from 'ms'
import ms from 'ms'
export default class Util {
async wait(time: number | string): Promise<void> {
if (typeof time === 'string') {
time = this.stringToNumber(time)
}
return new Promise<void>(resolve => {
setTimeout(resolve, time)
async wait(ms: number): Promise<void> {
// Safety check: prevent extremely long or negative waits
const MAX_WAIT_MS = 3600000 // 1 hour max
const safeMs = Math.min(Math.max(0, ms), MAX_WAIT_MS)
if (ms !== safeMs) {
console.warn(`[Utils] wait() clamped from ${ms}ms to ${safeMs}ms (max: ${MAX_WAIT_MS}ms)`)
}
return new Promise<void>((resolve) => {
setTimeout(resolve, safeMs)
})
}
async waitRandom(minMs: number, maxMs: number): Promise<void> {
const delta = this.randomNumber(minMs, maxMs)
return this.wait(delta)
}
getFormattedDate(ms = Date.now()): string {
const today = new Date(ms)
const month = String(today.getMonth() + 1).padStart(2, '0') // January is 0
const month = String(today.getMonth() + 1).padStart(2, '0') // January is 0
const day = String(today.getDate()).padStart(2, '0')
const year = today.getFullYear()
@@ -21,8 +31,7 @@ export default class Util {
}
shuffleArray<T>(array: T[]): T[] {
return array
.map(value => ({ value, sort: Math.random() }))
return array.map(value => ({ value, sort: Math.random() }))
.sort((a, b) => a.sort - b.sort)
.map(({ value }) => value)
}
@@ -32,7 +41,17 @@ export default class Util {
}
chunkArray<T>(arr: T[], numChunks: number): T[][] {
const chunkSize = Math.ceil(arr.length / numChunks)
// Validate input to prevent division by zero or invalid chunks
if (numChunks <= 0) {
throw new Error(`Invalid numChunks: ${numChunks}. Must be a positive integer.`)
}
if (arr.length === 0) {
return []
}
const safeNumChunks = Math.max(1, Math.floor(numChunks))
const chunkSize = Math.ceil(arr.length / safeNumChunks)
const chunks: T[][] = []
for (let i = 0; i < arr.length; i += chunkSize) {
@@ -43,39 +62,12 @@ export default class Util {
return chunks
}
stringToNumber(input: string | number): number {
if (typeof input === 'number') {
return input
stringToMs(input: string | number): number {
const milisec = ms(input.toString())
if (!milisec) {
throw new Error('The string provided cannot be parsed to a valid time! Use a format like "1 min", "1m" or "1 minutes"')
}
const value = input.trim()
const milisec = ms(value as StringValue)
if (milisec === undefined) {
throw new Error(
`The input provided (${input}) cannot be parsed to a valid time! Use a format like "1 min", "1m" or "1 minutes"`
)
}
return milisec
}
normalizeString(string: string): string {
return string
.normalize('NFD')
.trim()
.toLowerCase()
.replace(/[^\x20-\x7E]/g, '')
.replace(/[?!]/g, '')
}
getEmailUsername(email: string): string {
return email.split('@')[0] ?? 'Unknown'
}
randomDelay(min: string | number, max: string | number): number {
const minMs = typeof min === 'number' ? min : this.stringToNumber(min)
const maxMs = typeof max === 'number' ? max : this.stringToNumber(max)
return Math.floor(this.randomNumber(minMs, maxMs))
}
}
}

View File

@@ -2,18 +2,18 @@
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
"target": "ES2020" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
"target": "ES2020", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
"declaration": true /* Generates corresponding '.d.ts' file. */,
"declarationMap": true /* Generates a sourcemap for each corresponding '.d.ts' file. */,
"sourceMap": true /* Generates corresponding '.map' file. */,
"declaration": true, /* Generates corresponding '.d.ts' file. */
"declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist" /* Redirect output structure to the directory. */,
"rootDir": "./src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
"outDir": "./dist", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
@@ -22,34 +22,33 @@
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
"noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
"strictNullChecks": true /* Enable strict null checks. */,
"strictFunctionTypes": true /* Enable strict checking of function types. */,
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
"strictNullChecks": true, /* Enable strict null checks. */
"strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
"noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */,
"alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */,
"noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
"alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
"noUnusedLocals": true /* Report errors on unused locals. */,
"noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
"noImplicitReturns": true /* Report error when not all code paths in function return a value. */,
"noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */,
"noUncheckedIndexedAccess": true /* Include 'undefined' in index signature results */,
"noImplicitOverride": true /* Ensure overriding members in derived classes are marked with an 'override' modifier. */,
"noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
"noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
"noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
"noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
/* Module Resolution Options */
"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
"types": ["node"],
"typeRoots": ["./node_modules/@types"],
// Keep explicit typeRoots to ensure resolution in environments that don't auto-detect before full install.
"moduleResolution":"node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
"types": ["node"],
// Keep explicit typeRoots to ensure resolution in environments that don't auto-detect before full install.
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
@@ -61,10 +60,16 @@
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */,
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
"resolveJsonModule": true
},
"include": ["src/**/*.ts", "src/accounts.json", "src/config.json", "src/functions/queries.json"],
"exclude": ["node_modules"]
}
"include": [
"src/**/*.ts",
"src/**/*.d.ts",
"src/functions/queries.json"
],
"exclude": [
"node_modules"
]
}