92 Commits
v1.2.1 ... main

Author SHA1 Message Date
Netsky
ee16f1fd10 Update URL to fetch queries from v1 branch 2025-12-27 15:10:34 +01:00
Netsky
0059192519 Proper 1.5 readme
Updated configuration reference and options in README.md.
2025-11-11 13:11:36 +01:00
Netsky
a36b7eaef5 Remove setup script 2025-11-11 11:18:47 +01:00
Netsky
59b9f25d2c Delete setup directory 2025-11-11 11:17:26 +01:00
Netsky
e89b8c0c52 Update Nix setup instructions in README
Reorganize Nix setup instructions for clarity.
2025-11-11 11:16:28 +01:00
Netsky
649cf28ad9 Revise README for setup and features clarity
Updated README with detailed setup instructions and features overview.
2025-11-11 11:12:30 +01:00
Hasbullah Almughniy
624f5a32e1 ignore .playwright-chromium-installed from git (#387) 2025-11-06 07:39:03 +01:00
Netsky
3b21f45fcc Change Bing login URL to rewards dashboard
Updated the Bing login URL to redirect to the rewards dashboard.
2025-11-05 13:12:28 +01:00
Netsky
f857b3ad1a Refactor README for clarity and updates
Updated README to improve clarity and structure, removed outdated sections, and added Discord badge.
2025-11-03 11:25:31 +01:00
Netsky
0b7088a7e6 Add GNU GPL v3 license
Added the GNU General Public License version 3 to the project.
2025-11-03 11:19:28 +01:00
Michael Cammarata
64ffabcceb Update run_daily.sh (#398)
Fix for scheduler for docker version
2025-11-01 14:39:34 +01:00
Michael Cammarata
86f65b448d Port Dockerfile optimizations from v2 to v1.53, no functionality changes. (#386)
* port v2 optimizations to v1.5

Updated dockerfile with v2 optimizations. Ported Login.ts no dialogs fix.

* Update entrypoint.sh

Fix playwright path in entrypoint as well
2025-10-21 15:48:59 +02:00
Light
14492b27cb Edit README.md (#376)
* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Fix markdown formatting in README.md

* Update README.md
2025-10-11 16:54:40 +02:00
Light
62d1a0a14b README.md modification of Legacy 1.5.3 (#366)
* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Revise README for v2 beta release announcement

Updated README for Microsoft Rewards Script v2 beta release, including new version notice and feedback encouragement.
2025-10-01 18:29:39 +02:00
Light
02160a07d9 Small update to be deployed quickly. (#358)
* chore: Update TypeScript configuration and add @types/node as a dev dependency

* feat: Add unified cross-platform setup script for easier configuration and installation

* docs: Revise README for improved setup instructions and clarity

* feat: Enhance setup scripts with improved prerequisite checks and user prompts

* feat: Refactor setup scripts and enhance browser handling with automatic Playwright installation
2025-09-16 09:34:49 +02:00
Light
b66114d4dd feat: Add conclusion webhook support for final summary notifications (#355)
- Updated README.md to include new configuration options for conclusion webhook.
- Enhanced BrowserFunc.ts with improved error handling during page reloads.
- Implemented conclusionWebhook configuration in config.json.
- Refactored Login.ts to use Playwright types and improved passkey handling.
- Added safeClick method in SearchOnBing.ts to handle click timeouts and overlays.
- Introduced account summary collection in index.ts for reporting.
- Created ConclusionWebhook.ts to send structured summaries to a dedicated webhook.
- Updated TypeScript definitions for better type safety across the project.
2025-09-14 08:29:09 +02:00
Light
2e80266ad1 Update Login.ts (#349) 2025-09-10 20:44:20 +02:00
Michael Cammarata
072e96dd53 Improvements to docker scheduling and lock file (#339)
* improved logic that prevents overlapping runs, added logic to kill the process if it is stuck or doesn't exit properly

* Improve lock file logic

Improve lock file logic to release lock if the script didn't finish cleanly on a prior run. Otherwise shouldn't interrupt actual run.

* Tidy up readme for docker
2025-09-10 09:29:28 +02:00
hmcdat
eea4407454 disable fido (passkey, face id, security key) authentication (#342) 2025-08-30 15:22:32 +02:00
Simon Gardling
ad2e0b8bb3 Update Playwright + Use Nix (#311)
* use nix for execution

* update setup instructions

* headless

* headless via xvfb-run
2025-08-22 00:43:17 +02:00
qingzt
ad3b215dbc fix skip 2FA (#332) 2025-08-10 15:10:38 +02:00
Michael Cammarata
f51daf06d6 Docker rewrite and optimizations (#321)
* Optimizations of dockerfile

Massive test optimizations with drop in image size to about 256mb from about 1.2 gb. Drawback is that I currently have to keep the dockerfile playwright version matched to the package.json version

* further optimizations

Removed redundant (hopefully) sessions directory creation during build

* Fix docker cron dependencies

Small fix that should make cron run properly

* Major docker update!

- **Dockerfile rewritten as a multi-stage build**
  - Split into a “builder” stage (`node:18-slim`) to install dependencies and compile TypeScript, and a “runtime” stage (official Playwright image) to run the script.
  - This keeps build tools and dependencies out of the final image, making it smaller, faster to pull, and more secure.

- **Entrypoint script (`entrypoint.sh`)**
  - Introduced an entrypoint that runs inside the container at startup to:
    1. Set the container’s timezone (`TZ`) correctly, based on the environment or defaulting to UTC.
    2. Validate that the user provided a `CRON_SCHEDULE` (exiting early with an error if missing).
    3. Optionally perform an initial run of the script immediately (when `RUN_ON_START=true`), without any random sleep.
  - Centralizing setup in an entrypoint keeps the Dockerfile simpler and ensures proper signal handling.

- **`run_daily.sh` improvements**
  - Removed custom browser-path override so Playwright uses bundled browsers in the official image.
  - Added a lock using `flock` to prevent overlapping runs if a previous run is still in progress.
  - Retained the random sleep between 5 and 50 minutes before each run.
  - Logs are timestamped and clearly report success or failure.

- **Cron template tweaks**
  - Updated `src/crontab.template` so that each job line redirects both stdout and stderr into Docker’s stdout (`>> /proc/1/fd/1 2>&1`), making it easy to view logs via `docker logs`.

- **Initial-run logic**
  - The entrypoint checks `RUN_ON_START=true` and, if set, invokes `npm start` immediately (without random sleep). This provides an immediate first execution on container startup.
  - Scheduled runs via cron still go through the normal `run_daily.sh` (with sleep and locking).

- **Cron logging and visibility**
  - By redirecting cron job output to the container’s stdout, all logs (initial run and scheduled runs) appear in `docker logs`, avoiding the need to tail log files manually.

- **Error handling and validation**
  - Entry point exits early if `CRON_SCHEDULE` is missing, preventing silent misconfiguration.
  - If the initial run fails, it logs a warning but still starts cron so future scheduled runs can proceed.
  - `run_daily.sh` will exit early if a previous run is still active (locking), avoiding overlapping executions.

* Docker (multi-stage) improvements

- added cron logging in entrypoint and fixed timezone support for cron-invoked script runs
- further optimized multi-stage dockerfile
- bumped playwright version to 1.52.0 in dockerfile and package.json
- added customization and enable/disable randomization for cron start times
- optionally add container health  monitor and resource limits in compose.yaml
2025-07-17 12:16:22 +02:00
TheNetsky
e7c27ac16e Fix login issues for mobile 2025-06-08 18:28:37 +02:00
hmcdat
9f5601d44b Fix 2FA problem on new login page (#305)
* fix 2FA on new login page

* change 2fa login checking element

* temporary disable parallel due to errors when script tries to dismiss buttons
2025-05-30 11:43:15 +02:00
TheNetsky
d5fd06d229 1.5.3
Fix issue with pop-up dismissal
2025-04-30 16:20:56 +02:00
TheNetsky
0ddc964878 1.5.2
- Updated packages
- Cleanup
- Improved message dismissal
- Improved login functionality

With help from @LightZirconite
2025-04-24 14:50:22 +02:00
CNOCM
325bf65b30 Update README (#264)
* Update Search.ts

* Update README.md
2025-03-03 10:59:06 +01:00
HMCDAT
6f19bd4b0e Update Dockerfile (#262) 2025-02-28 12:34:47 +01:00
AariaX
caf6a42a38 Make shuffleArray more random? (#254) 2025-02-25 16:14:51 +01:00
TheNetsky
352d47229b Merge branch 'main' of https://github.com/TheNetsky/Microsoft-Rewards-Script 2025-02-24 17:59:28 +01:00
TheNetsky
9a12ee1ec8 Fix geoLocale not being uppercase 2025-02-24 17:59:20 +01:00
Netsky
b630c3ddda Update README.md 2025-02-24 15:52:53 +01:00
Netsky
287e3897da Update README.md 2025-02-24 15:51:08 +01:00
Netsky
fcf6aba446 Bump version 2025-02-24 15:49:45 +01:00
AariaX
1102f2ca94 Google API Update (1.5.1) (#247)
* switch to google internal api

* A bit of tidying up

* A bit more of tidying up

* A bit more of tidying up

* Pre 1.5.1

- Add proxy exclusions
- Update ReadMe
- Update config Interface

---------

Co-authored-by: TheNetsky <56271887+TheNetsky@users.noreply.github.com>
2025-02-24 15:49:19 +01:00
1OSA
82a896e83f added webhooklogexcludefunc (#240) 2025-02-20 23:21:46 +01:00
Netsky
b0bd1f52c4 Update queries.json 2025-02-19 19:32:45 +01:00
Netsky
7e4121e01b Update run_daily.sh 2025-02-19 15:29:51 +01:00
Netsky
849406c44f 1.5 inital (#234)
* 1.4.12

* Update README.md

* Update package.json

* Update package.json

* 1.5 initial

- Added parallel mode (experimental, likely no Docker supported)
- Added chalk for clearer logging
- Added support for "SearchOnBing" Activities
- Added more configurable options for certain things
- Redone some of the popup/banner clicking for searching (Redo the entire "popup" clicking, so they're more specifically targeted)
- Axios proxy is now optional in the config
- Fingerprint saving is now optional for desktop and mobile

There needs to be many changes for Docker support, including parallel, the new config settings and general testing!

This is still highly experimental, if you use Docker or want something more stable, use the version before this commit!

* Add queries.json to build

* fix(Login): update URL within authorization loop to reflect current page (#210)

* Many changes

- Updated Packages
- Fixed mobile searches erroring out for dashboard  data
- Reworked "bad page" detection
- Catching more errors
- Reworked the search and "close tabs"
- More fixes to the login
- Fixed to paralell and clustering, thanks to @AariaX

* Docker 1.5 preliminary support (#211)

* Basic docker functionality for 1.5

Preliminary docker support for 1.5. Requires headless=true, clusters=1

* Tidy up timezone, add TZ to compose file

Minor changes that should improve timezone handling, and (hopefully) improve scheduling function

* updated readme to simplify and clarify docker instructions

also removed env vars from table

* Fix syntax for cron

* Fix scheduling, add .gitattributes to normalize line endings

fixed line endings caused by Windows in crontab.template and run_daily.sh, which were breaking cron and script execution in the Docker container.

* Removed unnecessary scheduling key from config.json

This key isn't necessary for docker or the base script.

* Basic docker functionality for 1.5

Preliminary docker support for 1.5. Requires headless=true, clusters=1

Tidied up timezone, add TZ to compose file

Minor changes that should improve timezone handling, and (hopefully) improve scheduling function

updated readme to simplify and clarify docker instructions

also removed env vars from table

Fixed syntax for cron

Fixed scheduling, add .gitattributes to normalize line endings

Fixed line endings caused by Windows in crontab.template and run_daily.sh, which were breaking cron and script execution in the Docker container.

Removed unnecessary scheduling key from config.json

This key isn't necessary for docker or the base script.

* Improve scheduling handling, show logs in console

Fixes scheduling when RUN_ON_START=true, and fixes scheduled runs not appearing in docker logs.

* Update compose.yaml

revert service and container name, revert volumes for better generalization, add tips to environment to set scheduling, timezone and whether to run on container start

* Update README.md

proper container name

Co-authored-by: AariaX <196196201+AariaX@users.noreply.github.com>

---------

Co-authored-by: AariaX <196196201+AariaX@users.noreply.github.com>

* Fixes

- Reworked some of the point counting
- Reverted back to the "playwright" package
- Fixed error throw for emailPrefill

* Update config.json

* Add pre-build script

* Update package.json

* Handle 2FA in parallel mode (#219)

* catch error in reloadBadPage (#220)

* Use pre-build and simplify dockerfile (#218)

This uses the new pre-build script included in package.json to handle deps greatly simplifying the dockerfile.

* Small improvements

* Small fixes

- Fixed log spam for "Waiting for authorization"
- Increased wait from 2 to 5 seconds
- Increased search to "safer" values for default

* Experimenting with selectors

Seeing #223 I want to try if this is a good new addition, since for most user this SHOULD work just as good as clicking the entire box.

* More stuff

- Added ability to exclude logs by their function name
- Now caching config settings

* fix: don't retry on 0 (#228)

* Improvements

- Check if searches for mobile are enabled before creating the new page in the browser
- Return message if mobile search data cannot be found
- Added more selectors for coupons

* Improve Popup Dismissal

- Now executes in Parallel
- Respects a timeout of 1 second

---------

Co-authored-by: AariaX <196196201+AariaX@users.noreply.github.com>
Co-authored-by: mgrimace <55518507+mgrimace@users.noreply.github.com>
2025-02-15 16:14:47 +01:00
Netsky
d1f4364e18 Change queries format 2024-10-29 15:14:07 +01:00
Netsky
cf79467a4e Update queries.json 2024-10-29 14:03:22 +01:00
Netsky
ae554a0639 Update Queries 2024-10-29 13:56:00 +01:00
Netsky
1a6f9f4ac3 Update queries
Testing stuff
2024-10-28 14:32:36 +01:00
Netsky
45083ed41f Queries for "Search on Bing" activity 2024-10-27 18:02:29 +01:00
mgrimace
8b489d50f7 Dockerfile refactoring (#167)
* Docker updates and maintenance

- Update run_daily.sh to use compose.yaml env var overrides if present on scheduled jobs, not just first run. Defaults back to config.json values if no override specified.
- update sample compose.yaml with volume mapping to keep config.json, accounts.json, and sessions folder persistent on local machine (e.g., to keep data persistent through updates).

* Refactored dockerfile

Combining various steps to reduce layers. Should improve build time and image size.
2024-10-17 21:46:54 +02:00
mgrimace
7151f2351a Docker updates and maintenance (#164)
- Update run_daily.sh to use compose.yaml env var overrides if present on scheduled jobs, not just first run. Defaults back to config.json values if no override specified.
- update sample compose.yaml with volume mapping to keep config.json, accounts.json, and sessions folder persistent on local machine (e.g., to keep data persistent through updates).
2024-10-14 15:21:36 +02:00
Netsky
5afd8cbe1d Update package.json 2024-10-03 15:01:32 +02:00
Netsky
f015649d16 Fix typo 2024-10-02 18:42:01 +02:00
Netsky
034359019c Update README.md 2024-10-02 18:41:06 +02:00
HMCDAT
09ddbee45a 1.4.11 (#146)
* fix misspelling

* fix: avoid skipping eligible items in "More Promotion"

* remove unnecessary output

* Fix Formatting

* replace checking variable

* decrease id length

* revert previous commit

* change condition for eligible promo

* Other fixes

---------

Co-authored-by: TheNetsky <56271887+TheNetsky@users.noreply.github.com>
2024-10-02 18:37:06 +02:00
MuhammaD Usama
7939196e88 Update Dockerfile (#152)
Update Dockerfile for build
2024-09-22 19:46:10 +02:00
TheNetsky
5bc66c5fc9 1.4.10
- Fixed searches for some users
2024-09-02 12:13:38 +02:00
Netsky
c70d6f9cb1 1.4.9 2024-08-30 13:54:35 +02:00
HMCDAT
a47b86e74d Support new quest to get points (#138)
* support passwordless auth (using Authenticator app)

* update readme

* feat: added mobile app tasks (daily check in + read to earn)

* fix some stuff

* make ReadToEarn use the delay config

* fix daily reward search per week

* reorder mobile tasks

* fix message

* Search fixes, reformatting and types

---------

Co-authored-by: TheNetsky <56271887+TheNetsky@users.noreply.github.com>
2024-08-30 13:26:52 +02:00
TheNetsky
ce2a72ee36 1.4.8 2024-08-18 15:06:44 +02:00
CNOCM
755237caa1 Skip locked Promotions (#132) 2024-08-18 14:37:56 +02:00
HMCDAT
2b4cd505c0 Support passwordless auth (#129)
* support passwordless auth (using Authenticator app)

* update readme
2024-07-24 15:01:45 +02:00
Nworm
a39a861dab Update Search.ts (#127) 2024-07-11 14:43:26 +02:00
mgrimace
8d19129906 Docker: improved env var handling (#113)
* Improve env var handling, clarify instructions

updateConfig.js will update dist/config.json with any values specified in the docker compose file as environmental variables (env vars). If not specified it will use the default values in src/config.json (the 'usual' place where folks can customize their config).

A user can make changes to an env var (e.g., disabling Scroll Random Results), then docker compose up -d to quickly restart the container with the change.

* minor update to env vars in table

Make sure to change your compose so the updated flattened values work.

* TZ handling for cron runs of the script

docker logs netsky should now show the proper time zone for script runs that were initiated via cron schedule.
2024-06-01 14:50:29 +02:00
TheNetsky
c6ab80fe54 Delete start.bat
oops
2024-05-28 11:39:34 +02:00
TheNetsky
9b1eed526f 1.4.7
- Updated packages
- Added timeout after scrolling back to top
- Some Docker improvement thanks to @mgrimace
2024-05-28 11:38:49 +02:00
mgrimace
9a144b2e60 Docker with env var support and containerized cron scheduling (#107)
* Script will run on container start, and continue to run daily at 5:00 am.

The goal of this update was to add in-built cronjob support so that the script runs immediately on container start, then will schedule the script to run the daily at 5:00 am without requiring the user to manually create a cronjob. After starting the container and completing the first run, the container should remain active (running) but idle until the next scheduled run. Ideally, the next step will be to include support for environmental variables that will allow the user to customize when the script scheduled runs occur within the docker compose.yaml.

* added --build to docker compose command instructions

building/rebuilding the image (and the script) may reduce problems if folks make changes to their configs

* Updated the crontab default to run twice daily by default, 5am and 11am

* Update crontab

Newline needed

* Environmental variable support, custom scheduling

This is a massive update that includes docker environmental variable support for all config options. If specified, the custom env var value will supersede the default values in the config.json. You do not need to change the values in the config.json if you set a custom env var. For example, if you have headless=false in the config.json, but set it as true in the compose.yaml, it will run as HEADLESS=true. If you do not specify a particular env var, the script will automatically use the default value. Please test and contribute wherever possible!

* Fix scheduled runs, tidied up readme

* timezone support

Minor adjustment to attempt to fix timezone env var support

* Run on start, npm script env

Hopefully two fixes here, the container should again, by default, run on start, then continue per schedule. This defaults to true; however, can be optionally over-ridden in the compose.yaml with the env var RUN_ON_START=false. If set to false, the script should only run on the specified cron schedule. I also passed the TZ write into the npm start command, rather than just the container overall so it should show the proper time.

* Keep docker running after run_on_start to wait for cron

Accidentally set it up like a run_once, this should keep the container active after run_on_start to wait for the next schedule.

* improve order of cmd

This should (1) set time zone for script, (2) run once if set, then (3) idle for scheduled cron job. It was a little hacky before, this should be tidier.

* updated compose to auto-restart container

Noticed the container was exited this am, likely after automated updated to system, adding restart: unless-stopped to compose should keep container running in such circumstances.

* Update env vars in readme
2024-05-16 19:28:55 +02:00
Netsky
28b1881642 Update README.md 2024-05-09 12:38:49 +02:00
TheNetsky
ef6ad569ff 1.4.6 2024-05-09 10:04:11 +02:00
Netsky
da9ba91c5c Merge pull request #98 from jordyamc/main
Bug when detecting earnable points from more promotions
2024-05-07 15:12:10 +02:00
Jordy Mendoza
deb2d58b1b - Fix bug where the script was using x.activityType instead of x.promotionType this was causing that the script wasn't detecting earnable points from more promotions 2024-04-21 23:50:33 -06:00
Netsky
66a82c2584 Merge pull request #89 from mgrimace/docker
Clarify docker instructions, add basic compose.yaml support
2024-04-04 16:43:57 +02:00
mgrimace
8a022d5983 Clarify docker instructions, add basic compose.yaml support
This should help folks get started with docker and hopefully make it easier for testing
2024-04-03 17:59:16 -04:00
TheNetsky
64048e35d7 1.4.5
- Fix login not working
- Sessions are now saved after logging in
- Check if promotions, and searches are available before counting total point amount
2024-03-01 12:19:48 +01:00
TheNetsky
cf7f7ac790 Merge branch 'main' of https://github.com/TheNetsky/Microsoft-Rewards-Script 2024-02-05 11:47:50 +01:00
TheNetsky
f7aa5039f9 1.4.4
- Fixed login getting stuck
- Updated packages
- Fixed some errors not throwing
2024-02-05 11:47:48 +01:00
Netsky
e082fb03f0 Merge pull request #56 from Omniphantasm/patch-1
Update README.md
2024-01-26 18:55:10 +01:00
Omniphantasm
0303b8c605 Update README.md
Script is kill-chrome-win, changed readme to reflect that.
2024-01-26 12:35:30 -05:00
TheNetsky
2fea17c415 1.4.3
- Fixed browser generating mobile browser after the first account
- Hopefully fixed script erroring after not finding parent promotions
- Added support for MacOS (Thanks @alecm858)
- Made some changes to search result scrolling
2024-01-20 12:11:02 +01:00
Netsky
c5beccb54b Update README.md 2024-01-17 22:23:55 +01:00
TheNetsky
b566ccaece 1.4.2
- Scroll back to top before searching
2024-01-17 18:50:43 +01:00
TheNetsky
15b2b827eb 1.4.1
- Fixed typos
- Added Dockerfile (experimental)
- Increased scroll amount
2024-01-14 14:09:57 +01:00
Netsky
02518ee4ba Update README.md 2024-01-07 17:00:23 +01:00
Netsky
69819b5631 Add config explaination 2024-01-07 16:59:15 +01:00
Netsky
b389b87792 Set runOnZeroPoints to false by default 2024-01-07 16:38:47 +01:00
TheNetsky
9ea7f5c452 1.4.0
- Switched from Puppeteer to Playwright
- Fixed mobile searches not working
- Added fingerprint saving in config
- Added mobile search retry in config
2024-01-07 16:33:48 +01:00
TheNetsky
f3fb641ecd 1.3.2
- Better generation of mobile user agents
2023-12-27 11:38:52 +01:00
TheNetsky
bca1e7c896 1.3.1
- Poll clicking will be attempted regardless of the selector being found
- Fix tabs sticking upon search error
- Updated dependencies
2023-12-20 13:03:08 +01:00
Netsky
fd7c8e36d4 Update README.md 2023-12-01 12:12:26 +01:00
Netsky
dcb0c25d46 Remove the feature of Promo Items 2023-12-01 12:02:17 +01:00
TheNetsky
a8cb5482d4 1.3.0 2023-12-01 11:49:14 +01:00
TheNetsky
28286ff9fe Pre 1.3.0 2023-11-23 14:38:58 +01:00
TheNetsky
1d6167aeca Missing await 2023-11-04 16:24:25 +01:00
TheNetsky
3b15fe19a7 1.2.5 2023-11-04 16:21:56 +01:00
TheNetsky
66dcdd4a7a 1.2.4
Disable "This or That" quiz.
2023-10-30 21:10:47 +01:00
TheNetsky
40f32af67f 1.2.3 2023-10-30 20:37:40 +01:00
TheNetsky
c2b68faa74 1.2.2 2023-10-26 15:31:35 +02:00
50 changed files with 8001 additions and 1200 deletions

View File

@@ -28,6 +28,10 @@ module.exports = {
'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'

2
.gitattributes vendored Normal file
View File

@@ -0,0 +1,2 @@
*.sh text eol=lf
*.template text eol=lf

5
.gitignore vendored
View File

@@ -1,8 +1,9 @@
sessions/
dist/
node_modules/
package-lock.json
accounts.json
notes
accounts.dev.json
accounts.main.json
accounts.main.json
.DS_Store
.playwright-chromium-installed

20
.vscode/launch.json vendored
View File

@@ -1,20 +0,0 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${file}",
"outFiles": [
"${workspaceFolder}/**/*.js"
]
}
]
}

89
Dockerfile Normal file
View File

@@ -0,0 +1,89 @@
###############################################################################
# Stage 1: Builder
###############################################################################
FROM node:22-slim AS builder
WORKDIR /usr/src/microsoft-rewards-script
ENV PLAYWRIGHT_BROWSERS_PATH=0
# Copy package files
COPY package.json package-lock.json tsconfig.json ./
# Install all dependencies required to build the script
RUN npm ci --ignore-scripts
# Copy source and build
COPY . .
RUN npm run build
# Remove build dependencies, and reinstall only runtime dependencies
RUN rm -rf node_modules \
&& npm ci --omit=dev --ignore-scripts \
&& npm cache clean --force
# Install Chromium Headless Shell, and cleanup
RUN npx playwright install --with-deps --only-shell chromium \
&& rm -rf /root/.cache /tmp/* /var/tmp/*
###############################################################################
# Stage 2: Runtime
###############################################################################
FROM node:22-slim AS runtime
WORKDIR /usr/src/microsoft-rewards-script
# Set production environment variables
ENV NODE_ENV=production \
TZ=UTC \
PLAYWRIGHT_BROWSERS_PATH=0 \
FORCE_HEADLESS=1
# Install minimal system libraries required for Chromium headless to run
RUN apt-get update && apt-get install -y --no-install-recommends \
cron \
gettext-base \
tzdata \
ca-certificates \
libglib2.0-0 \
libdbus-1-3 \
libexpat1 \
libfontconfig1 \
libgtk-3-0 \
libnspr4 \
libnss3 \
libasound2 \
libflac12 \
libatk1.0-0 \
libatspi2.0-0 \
libdrm2 \
libgbm1 \
libdav1d6 \
libx11-6 \
libx11-xcb1 \
libxcomposite1 \
libxcursor1 \
libxdamage1 \
libxext6 \
libxfixes3 \
libxi6 \
libxrandr2 \
libxrender1 \
libxss1 \
libxtst6 \
libdouble-conversion3 \
&& rm -rf /var/lib/apt/lists/* /var/cache/apt/archives/*
# Copy compiled application and dependencies from builder stage
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 src/run_daily.sh ./src/run_daily.sh
COPY --chmod=644 src/crontab.template /etc/cron.d/microsoft-rewards-cron.template
COPY --chmod=755 entrypoint.sh /usr/local/bin/entrypoint.sh
# Entrypoint handles TZ, initial run toggle, cron templating & launch
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
CMD ["sh", "-c", "echo 'Container started; cron is running.'"]

674
LICENSE Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

338
README.md
View File

@@ -1,45 +1,301 @@
# Microsoft-Rewards-Script
Automated Microsoft Rewards script, however this time using TypeScript, Cheerio and Puppeteer.
[![Discord](https://img.shields.io/badge/Join%20Our%20Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/8BxYbV4pkj)
Under development, however mainly for personal use!
---
## How to setup ##
1. Download or clone source code
2. Run `npm i` to install the packages
3. Change `accounts.example.json` to `accounts.json` and add your account details
4. Change `config.json` to your liking
5. Run `npm run build` to build the script
6. Run `npm run start` to start the built script
## 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)
## Features ##
- [x] Multi-Account Support
- [x] Session Storing
- [x] 2FA Support
- [x] Headless Support
- [x] Discord Webhook Support
- [x] Desktop Searches
- [x] Configurable Tasks
- [x] Microsoft Edge Searches
- [x] Mobile Searches
- [x] Emulated Scrolling Support
- [x] Emulated Link Clicking Support
- [x] Geo Locale Search Queries
- [x] Completing Daily Set
- [x] Completing More Promotions
- [x] Solving Quiz (10 point variant)
- [x] Solving Quiz (30-40 point variant)
- [x] Completing Click Rewards
- [x] Completing Polls
- [x] Completing Punchcards
- [ ] Solving This Or That Quiz
- [x] Clicking Promotional Items
- [x] Solving ABC Quiz
- [ ] Completing Shopping Game
- [ ] Completing Gaming Tab
- [x] Clustering Support
- [x] Proxy Support
---
## Disclaimer ##
Your account may be at risk of getting banned or suspended using this script, you've been warned!
<br />
Use this script at your own risk!
## 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
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 available options (matches the latest version in the repository).
### Core
| Setting | Type | Default | Description |
|----------|------|----------|-------------|
| `baseURL` | string | `"https://rewards.bing.com"` | Microsoft Rewards base URL |
| `sessionPath` | string | `"sessions"` | Directory to store browser sessions |
| `headless` | boolean | `false` | Run browser invisibly |
| `parallel` | boolean | `false` | Run desktop and mobile simultaneously |
| `runOnZeroPoints` | boolean | `false` | Run even when no points are available |
| `clusters` | number | `1` | Number of concurrent account clusters |
| `globalTimeout` | string | `"30s"` | Timeout for all actions |
| `searchOnBingLocalQueries` | boolean | `false` | Use local query list |
### Fingerprinting
| Setting | Type | Default | Description |
|----------|------|----------|-------------|
| `saveFingerprint.mobile` | boolean | `false` | Reuse mobile fingerprint |
| `saveFingerprint.desktop` | boolean | `false` | Reuse desktop fingerprint |
### Workers
| Setting | Type | Default | Description |
|----------|------|----------|-------------|
| `doDailySet` | boolean | `true` | Complete daily set |
| `doMorePromotions` | boolean | `true` | Complete more promotions |
| `doPunchCards` | boolean | `true` | Complete punchcards |
| `doDesktopSearch` | boolean | `true` | Perform desktop searches |
| `doMobileSearch` | boolean | `true` | Perform mobile searches |
| `doDailyCheckIn` | boolean | `true` | Complete daily check-in |
| `doReadToEarn` | boolean | `true` | Complete Read-to-Earn |
### Search
| Setting | Type | Default | Description |
|----------|------|----------|-------------|
| `searchSettings.useGeoLocaleQueries` | boolean | `false` | Use region-based queries |
| `searchSettings.scrollRandomResults` | boolean | `true` | Scroll randomly on results |
| `searchSettings.clickRandomResults` | boolean | `true` | Click random links |
| `searchSettings.searchDelay.min` | string | `"3min"` | Minimum delay between searches |
| `searchSettings.searchDelay.max` | string | `"5min"` | Maximum delay between searches |
| `searchSettings.retryMobileSearchAmount` | number | `2` | Retry mobile searches amount |
### Logging
| Setting | Type | Default | Description |
|----------|------|----------|-------------|
| `logExcludeFunc` | string[] | `["SEARCH-CLOSE-TABS"]` | Exclude from console logs |
| `webhookLogExcludeFunc` | string[] | `["SEARCH-CLOSE-TABS"]` | Exclude from webhook logs |
### Proxy
| Setting | Type | Default | Description |
|----------|------|----------|-------------|
| `proxy.proxyGoogleTrends` | boolean | `true` | Proxy Google Trends requests |
| `proxy.proxyBingTerms` | boolean | `true` | Proxy Bing term requests |
### Webhooks
| Setting | Type | Default | Description |
|----------|------|----------|-------------|
| `webhook.enabled` | boolean | `false` | Enable Discord webhook |
| `webhook.url` | string | `""` | Webhook URL |
| `conclusionWebhook.enabled` | boolean | `false` | Enable summary webhook |
| `conclusionWebhook.url` | string | `""` | Summary webhook URL |
---
## Account Configuration
Edit `src/accounts.json` — the file is an **array** of accounts:
```json
[
{
"email": "email_1",
"password": "password_1",
"proxy": {
"proxyAxios": true,
"url": "",
"port": 0,
"username": "",
"password": ""
}
},
{
"email": "email_2",
"password": "password_2",
"proxy": {
"proxyAxios": true,
"url": "",
"port": 0,
"username": "",
"password": ""
}
}
]
```
**Notes**
- The file is a **flat array** — not `{ "accounts": [ ... ] }`.
- Only `email`, `password`, and `proxy` are supported.
- `proxyAxios` enables Axios-level proxying for API requests.
---
## 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 notifications
- Docker scheduling support
---
## Disclaimer
Use at your own risk.
Automation of Microsoft Rewards may lead to account suspension or bans.
This software is provided for educational purposes only.
The authors are not responsible for any actions taken by Microsoft.

42
compose.yaml Normal file
View File

@@ -0,0 +1,42 @@
services:
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
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"
# 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
# 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

50
entrypoint.sh Executable file
View File

@@ -0,0 +1,50 @@
#!/usr/bin/env bash
set -euo pipefail
# Ensure Playwright uses preinstalled browsers
export PLAYWRIGHT_BROWSERS_PATH=0
# 1. Timezone: default to UTC if not provided
: "${TZ:=UTC}"
ln -snf "/usr/share/zoneinfo/$TZ" /etc/localtime
echo "$TZ" > /etc/timezone
dpkg-reconfigure -f noninteractive tzdata
# 2. Validate CRON_SCHEDULE
if [ -z "${CRON_SCHEDULE:-}" ]; then
echo "ERROR: CRON_SCHEDULE environment variable is not set." >&2
echo "Please set CRON_SCHEDULE (e.g., \"0 2 * * *\")." >&2
exit 1
fi
# 3. Initial run without sleep if RUN_ON_START=true
if [ "${RUN_ON_START:-false}" = "true" ]; then
echo "[entrypoint] Starting initial run in background at $(date)"
(
cd /usr/src/microsoft-rewards-script || {
echo "[entrypoint-bg] ERROR: Unable to cd to /usr/src/microsoft-rewards-script" >&2
exit 1
}
# Skip random sleep for initial run, but preserve setting for cron jobs
SKIP_RANDOM_SLEEP=true src/run_daily.sh
echo "[entrypoint-bg] Initial run completed at $(date)"
) &
echo "[entrypoint] Background process started (PID: $!)"
fi
# 4. Template and register cron file with explicit timezone export
if [ ! -f /etc/cron.d/microsoft-rewards-cron.template ]; then
echo "ERROR: Cron template /etc/cron.d/microsoft-rewards-cron.template not found." >&2
exit 1
fi
# Export TZ for envsubst to use
export TZ
envsubst < /etc/cron.d/microsoft-rewards-cron.template > /etc/cron.d/microsoft-rewards-cron
chmod 0644 /etc/cron.d/microsoft-rewards-cron
crontab /etc/cron.d/microsoft-rewards-cron
echo "[entrypoint] Cron configured with schedule: $CRON_SCHEDULE and timezone: $TZ; starting cron at $(date)"
# 5. Start cron in foreground (PID 1)
exec cron -f

61
flake.lock generated Normal file
View File

@@ -0,0 +1,61 @@
{
"nodes": {
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1731533236,
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1749727998,
"narHash": "sha256-mHv/yeUbmL91/TvV95p+mBVahm9mdQMJoqaTVTALaFw=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "fd487183437963a59ba763c0cc4f27e3447dd6dd",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-25.05",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

40
flake.nix Normal file
View File

@@ -0,0 +1,40 @@
{
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.05";
flake-utils = {
url = "github:numtide/flake-utils";
};
};
outputs =
{ nixpkgs, flake-utils, ... }:
flake-utils.lib.eachDefaultSystem (
system:
let
pkgs = import nixpkgs {
inherit system;
};
in
{
devShell = pkgs.mkShell {
nativeBuildInputs = with pkgs; [
nodejs
playwright-driver.browsers
typescript
playwright-test
# fixes "waiting until load" issue compared to
# setting headless in config.json
xvfb-run
];
shellHook = ''
export PLAYWRIGHT_BROWSERS_PATH=${pkgs.playwright-driver.browsers}
export PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS=true
npm i
npm run build
'';
};
}
);
}

3126
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,16 +1,19 @@
{
"name": "microsoft-rewards-script",
"version": "1.2.1",
"version": "1.5.3",
"description": "Automatically do tasks for Microsoft Rewards but in TS!",
"main": "index.js",
"engines": {
"node": ">=18.0.0"
},
"scripts": {
"pre-build": "npm i && rimraf dist && npx playwright install chromium",
"build": "tsc",
"start": "node ./dist/index.js",
"ts-start": "ts-node ./src/index.ts",
"dev": "ts-node ./src/index.ts -dev"
"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 ."
},
"keywords": [
"Bing Rewards",
@@ -18,23 +21,32 @@
"Bot",
"Script",
"TypeScript",
"Puppeteer",
"Playwright",
"Cheerio"
],
"author": "Netsky",
"license": "ISC",
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^6.7.0",
"typescript": "^5.2.2"
"@types/node": "^20.14.11",
"@types/ms": "^0.7.34",
"@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.5.1",
"cheerio": "^1.0.0-rc.12",
"eslint": "^8.49.0",
"eslint-plugin-modules-newline": "^0.0.6",
"puppeteer": "^21.2.1",
"puppeteer-extra": "^3.3.6",
"puppeteer-extra-plugin-stealth": "^2.11.2",
"ts-node": "^10.9.1"
"axios": "^1.8.4",
"chalk": "^4.1.2",
"cheerio": "^1.0.0",
"fingerprint-generator": "^2.1.66",
"fingerprint-injector": "^2.1.66",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.6",
"ms": "^2.1.3",
"playwright": "1.52.0",
"rebrowser-playwright": "1.52.0",
"socks-proxy-agent": "^8.0.5",
"ts-node": "^10.9.2"
}
}
}

3
run.sh Executable file
View File

@@ -0,0 +1,3 @@
#!/usr/bin/env bash
nix develop --command bash -c "xvfb-run npm run start"

View File

@@ -3,6 +3,7 @@
"email": "email_1",
"password": "password_1",
"proxy": {
"proxyAxios": true,
"url": "",
"port": 0,
"username": "",
@@ -13,6 +14,7 @@
"email": "email_2",
"password": "password_2",
"proxy": {
"proxyAxios": true,
"url": "",
"port": 0,
"username": "",

View File

@@ -1,34 +1,95 @@
import puppeteer from 'puppeteer-extra'
import stealthPlugin from 'puppeteer-extra-plugin-stealth'
import playwright, { BrowserContext } from 'rebrowser-playwright'
import { getUserAgent } from '../util/UserAgent'
import { loadSesion } from './BrowserFunc'
import { newInjectedContext } from 'fingerprint-injector'
import { FingerprintGenerator } from 'fingerprint-generator'
import { MicrosoftRewardsBot } from '../index'
import { loadSessionData, saveFingerprintData } from '../util/Load'
import { updateFingerprintUserAgent } from '../util/UserAgent'
import { AccountProxy } from '../interface/Account'
import { headless } from '../config.json'
puppeteer.use(stealthPlugin())
/* Test Stuff
https://abrahamjuliot.github.io/creepjs/
https://botcheck.luminati.io/
https://fv.pro/
https://pixelscan.net/
https://www.browserscan.net/
*/
class Browser {
private bot: MicrosoftRewardsBot
async createBrowser(email: string, proxy: AccountProxy, isMobile: boolean) {
const userAgent = await getUserAgent(isMobile)
constructor(bot: MicrosoftRewardsBot) {
this.bot = bot
}
const browser = await puppeteer.launch({
headless: headless,
userDataDir: await loadSesion(email),
args: [
'--no-sandbox',
'--mute-audio',
'--disable-setuid-sandbox',
`--user-agent=${userAgent.userAgent}`,
isMobile ? '--window-size=568,1024' : '',
proxy.url ? `--proxy-server=${proxy.url}:${proxy.port}` : ''
]
async createBrowser(proxy: AccountProxy, email: string): Promise<BrowserContext> {
// Optional automatic browser installation (set AUTO_INSTALL_BROWSERS=1)
if (process.env.AUTO_INSTALL_BROWSERS === '1') {
try {
// Dynamically import child_process to avoid overhead otherwise
const { execSync } = await import('child_process') as any
execSync('npx playwright install chromium', { stdio: 'ignore' })
} catch { /* silent */ }
}
let browser: any
try {
browser = await playwright.chromium.launch({
//channel: 'msedge', // Uses Edge instead of chrome
headless: this.bot.config.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'
]
})
} catch (e: any) {
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: "npx playwright install chromium" (or set AUTO_INSTALL_BROWSERS=1 to auto attempt).', '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.isMobile, this.bot.config.saveFingerprint)
const fingerprint = sessionData.fingerprint ? sessionData.fingerprint : await this.generateFingerprint()
const context = await newInjectedContext(browser as any, { fingerprint: fingerprint })
// Set timeout to preferred amount
context.setDefaultTimeout(this.bot.utils.stringToMs(this.bot.config?.globalTimeout ?? 30000))
await context.addCookies(sessionData.cookies)
if (this.bot.config.saveFingerprint) {
await saveFingerprintData(this.bot.config.sessionPath, email, this.bot.isMobile, fingerprint)
}
this.bot.log(this.bot.isMobile, 'BROWSER', `Created browser with User-Agent: "${fingerprint.fingerprint.navigator.userAgent}"`)
return context as BrowserContext
}
async generateFingerprint() {
const fingerPrintData = new FingerprintGenerator().getFingerprint({
devices: this.bot.isMobile ? ['mobile'] : ['desktop'],
operatingSystems: this.bot.isMobile ? ['android'] : ['windows'],
browsers: [{ name: 'edge' }]
})
return browser
const updatedFingerPrintData = await updateFingerprintUserAgent(fingerPrintData, this.bot.isMobile)
return updatedFingerPrintData
}
}

View File

@@ -1,248 +1,383 @@
import { Page } from 'puppeteer'
import fs from 'fs'
import path from 'path'
import { BrowserContext, Page } from 'rebrowser-playwright'
import { CheerioAPI, load } from 'cheerio'
import { AxiosRequestConfig } from 'axios'
import { tryDismissAllMessages, tryDismissCookieBanner } from './BrowserUtil'
import { getFormattedDate, wait } from './../util/Utils'
import { log } from './../util/Logger'
import { MicrosoftRewardsBot } from '../index'
import { saveSessionData } from '../util/Load'
import { Counters, DashboardData, MorePromotion, PromotionalItem } from './../interface/DashboardData'
import { QuizData } from './../interface/QuizData'
import { AppUserData } from '../interface/AppUserData'
import { EarnablePoints } from '../interface/Points'
import { baseURL, sessionPath } from './../config.json'
export async function goHome(page: Page): Promise<boolean> {
export default class BrowserFunc {
private bot: MicrosoftRewardsBot
try {
const dashboardURL = new URL(baseURL)
constructor(bot: MicrosoftRewardsBot) {
this.bot = bot
}
await page.goto(baseURL)
const maxIterations = 5 // Maximum iterations set to 5
/**
* Navigate the provided page to rewards homepage
* @param {Page} page Playwright page
*/
async goHome(page: Page) {
for (let iteration = 1; iteration <= maxIterations; iteration++) {
await wait(3000)
await tryDismissCookieBanner(page)
try {
const dashboardURL = new URL(this.bot.config.baseURL)
// Check if account is suspended
const isSuspended = await page.waitForSelector('#suspendedAccountHeader', { visible: true, timeout: 3000 }).then(() => true).catch(() => false)
if (isSuspended) {
log('GO-HOME', 'This account is suspended!', 'error')
throw new Error('Account has been suspended!')
if (page.url() === dashboardURL.href) {
return
}
try {
// If activities are found, exit the loop
await page.waitForSelector('#more-activities', { timeout: 1000 })
break
await page.goto(this.bot.config.baseURL)
} catch (error) {
// Continue if element is not found
const maxIterations = 5 // Maximum iterations set to 5
for (let iteration = 1; iteration <= maxIterations; iteration++) {
await this.bot.utils.wait(3000)
await this.bot.browser.utils.tryDismissAllMessages(page)
// Check if account is suspended
const isSuspended = await page.waitForSelector('#suspendedAccountHeader', { state: 'visible', timeout: 2000 }).then(() => true).catch(() => false)
if (isSuspended) {
this.bot.log(this.bot.isMobile, 'GO-HOME', 'This account is suspended!', 'error')
throw new Error('Account has been suspended!')
}
try {
// If activities are found, exit the loop
await page.waitForSelector('#more-activities', { timeout: 1000 })
this.bot.log(this.bot.isMobile, 'GO-HOME', 'Visited homepage successfully')
break
} catch (error) {
// Continue if element is not found
}
// Below runs if the homepage was unable to be visited
const currentURL = new URL(page.url())
if (currentURL.hostname !== dashboardURL.hostname) {
await this.bot.browser.utils.tryDismissAllMessages(page)
await this.bot.utils.wait(2000)
await page.goto(this.bot.config.baseURL)
} else {
this.bot.log(this.bot.isMobile, 'GO-HOME', 'Visited homepage successfully')
break
}
await this.bot.utils.wait(5000)
}
const currentURL = new URL(page.url())
} catch (error) {
throw this.bot.log(this.bot.isMobile, 'GO-HOME', 'An error occurred:' + error, 'error')
}
}
/**
* Fetch user dashboard data
* @returns {DashboardData} Object of user bing rewards dashboard data
*/
async getDashboardData(): Promise<DashboardData> {
const dashboardURL = new URL(this.bot.config.baseURL)
const currentURL = new URL(this.bot.homePage.url())
try {
// Should never happen since tasks are opened in a new tab!
if (currentURL.hostname !== dashboardURL.hostname) {
await tryDismissAllMessages(page)
await wait(2000)
await page.goto(baseURL)
this.bot.log(this.bot.isMobile, 'DASHBOARD-DATA', 'Provided page did not equal dashboard page, redirecting to dashboard page')
await this.goHome(this.bot.homePage)
}
let lastError: any = null
for (let attempt = 1; attempt <= 2; attempt++) {
try {
// Reload the page to get new data
await this.bot.homePage.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(this.bot.homePage)
} catch {/* ignore */}
} else {
break
}
}
if (attempt === 2 && lastError) throw lastError
await this.bot.utils.wait(1000)
}
}
await wait(5000)
log('GO-HOME', 'Visited homepage successfully')
const scriptContent = await this.bot.homePage.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) {
throw this.bot.log(this.bot.isMobile, 'GET-DASHBOARD-DATA', 'Dashboard data not found within script', 'error')
}
// Extract the dashboard object from the script content
const dashboardData = await this.bot.homePage.evaluate((scriptContent: string) => {
// Extract the dashboard object using regex
const regex = /var dashboard = (\{.*?\});/s
const match = regex.exec(scriptContent)
if (match && match[1]) {
return JSON.parse(match[1])
}
}, scriptContent)
if (!dashboardData) {
throw this.bot.log(this.bot.isMobile, 'GET-DASHBOARD-DATA', 'Unable to parse dashboard script', 'error')
}
return dashboardData
} catch (error) {
throw this.bot.log(this.bot.isMobile, 'GET-DASHBOARD-DATA', `Error fetching dashboard data: ${error}`, 'error')
}
} catch (error) {
console.error('An error occurred:', error)
return false
}
return true
}
/**
* Get search point counters
* @returns {Counters} Object of search counter data
*/
async getSearchPoints(): Promise<Counters> {
const dashboardData = await this.getDashboardData() // Always fetch newest data
export async function getDashboardData(page: Page): Promise<DashboardData> {
const dashboardURL = new URL(baseURL)
const currentURL = new URL(page.url())
// Should never happen since tasks are opened in a new tab!
if (currentURL.hostname !== dashboardURL.hostname) {
log('DASHBOARD-DATA', 'Provided page did not equal dashboard page, redirecting to dashboard page')
await goHome(page)
return dashboardData.userStatus.counters
}
// Reload the page to get new data
await page.reload({ waitUntil: 'networkidle2' })
/**
* Get total earnable points with web browser
* @returns {number} Total earnable points
*/
async getBrowserEarnablePoints(): Promise<EarnablePoints> {
try {
let desktopSearchPoints = 0
let mobileSearchPoints = 0
let dailySetPoints = 0
let morePromotionsPoints = 0
const scriptContent = await page.evaluate(() => {
const scripts = Array.from(document.querySelectorAll('script'))
const targetScript = scripts.find(script => script.innerText.includes('var dashboard'))
const data = await this.getDashboardData()
if (targetScript) {
return targetScript.innerText
} else {
throw log('GET-DASHBOARD-DATA', 'Script containing dashboard data not found', 'error')
// Desktop Search Points
if (data.userStatus.counters.pcSearch?.length) {
data.userStatus.counters.pcSearch.forEach(x => desktopSearchPoints += (x.pointProgressMax - x.pointProgress))
}
// Mobile Search Points
if (data.userStatus.counters.mobileSearch?.length) {
data.userStatus.counters.mobileSearch.forEach(x => mobileSearchPoints += (x.pointProgressMax - x.pointProgress))
}
// Daily Set
data.dailySetPromotions[this.bot.utils.getFormattedDate()]?.forEach(x => dailySetPoints += (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)
}
})
}
const totalEarnablePoints = desktopSearchPoints + mobileSearchPoints + dailySetPoints + morePromotionsPoints
return {
dailySetPoints,
morePromotionsPoints,
desktopSearchPoints,
mobileSearchPoints,
totalEarnablePoints
}
} catch (error) {
throw this.bot.log(this.bot.isMobile, 'GET-BROWSER-EARNABLE-POINTS', 'An error occurred:' + error, 'error')
}
})
}
// Extract the dashboard object from the script content
const dashboardData = await page.evaluate(scriptContent => {
// Extract the dashboard object using regex
const regex = /var dashboard = (\{.*?\});/s
const match = regex.exec(scriptContent)
/**
* Get total earnable points with mobile app
* @returns {number} Total earnable points
*/
async getAppEarnablePoints(accessToken: string) {
try {
const points = {
readToEarn: 0,
checkIn: 0,
totalEarnablePoints: 0
}
if (match && match[1]) {
return JSON.parse(match[1])
} else {
throw log('GET-DASHBOARD-DATA', 'Dashboard data not found within script', 'error')
const eligibleOffers = [
'ENUS_readarticle3_30points',
'Gamification_Sapphire_DailyCheckIn'
]
const data = await this.getDashboardData()
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?channel=SAAndroid&options=613',
method: 'GET',
headers: {
'Authorization': `Bearer ${accessToken}`,
'X-Rewards-Country': geoLocale,
'X-Rewards-Language': 'en'
}
}
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) {
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 (checkInDay < 6 && (new Date()).getDate() != (new Date(item.attributes.last_updated ?? '')).getDate()) {
points.checkIn = parseInt(item.attributes['day_' + (checkInDay + 1) + '_points'] ?? '')
}
break
}
}
points.totalEarnablePoints = points.readToEarn + points.checkIn
return points
} catch (error) {
throw this.bot.log(this.bot.isMobile, 'GET-APP-EARNABLE-POINTS', 'An error occurred:' + error, 'error')
}
}, scriptContent)
}
return dashboardData
}
/**
* Get current point amount
* @returns {number} Current total point amount
*/
async getCurrentPoints(): Promise<number> {
try {
const data = await this.getDashboardData()
export async function getQuizData(page: Page): Promise<QuizData> {
try {
const html = await page.content()
const $ = load(html)
return data.userStatus.availablePoints
} catch (error) {
throw this.bot.log(this.bot.isMobile, 'GET-CURRENT-POINTS', 'An error occurred:' + error, 'error')
}
}
const scriptContent = $('script').filter((index, element) => {
return $(element).text().includes('_w.rewardsQuizRenderInfo')
}).text()
/**
* Parse quiz data from provided page
* @param {Page} page Playwright page
* @returns {QuizData} Quiz data object
*/
async getQuizData(page: Page): Promise<QuizData> {
try {
const html = await page.content()
const $ = load(html)
if (scriptContent) {
const regex = /_w\.rewardsQuizRenderInfo\s*=\s*({.*?});/s
const match = regex.exec(scriptContent)
const scriptContent = $('script').filter((index: number, element: any) => {
return $(element).text().includes('_w.rewardsQuizRenderInfo')
}).text()
if (match && match[1]) {
const quizData = JSON.parse(match[1])
return quizData
if (scriptContent) {
const regex = /_w\.rewardsQuizRenderInfo\s*=\s*({.*?});/s
const match = regex.exec(scriptContent)
if (match && match[1]) {
const quizData = JSON.parse(match[1])
return quizData
} else {
throw this.bot.log(this.bot.isMobile, 'GET-QUIZ-DATA', 'Quiz data not found within script', 'error')
}
} else {
throw log('GET-QUIZ-DATA', 'Quiz data not found within script', 'error')
throw this.bot.log(this.bot.isMobile, 'GET-QUIZ-DATA', 'Script containing quiz data not found', 'error')
}
} else {
throw log('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')
}
} catch (error) {
throw log('GET-QUIZ-DATA', 'An error occurred:' + error, 'error')
}
}
async waitForQuizRefresh(page: Page): Promise<boolean> {
try {
await page.waitForSelector('span.rqMCredits', { state: 'visible', timeout: 10000 })
await this.bot.utils.wait(2000)
export async function getSearchPoints(page: Page): Promise<Counters> {
const dashboardData = await getDashboardData(page) // Always fetch newest data
return dashboardData.userStatus.counters
}
export async function getEarnablePoints(data: DashboardData, page: null | Page = null): Promise<number> {
try {
// Fetch new data if page is provided
if (page) {
data = await getDashboardData(page)
return true
} catch (error) {
this.bot.log(this.bot.isMobile, 'QUIZ-REFRESH', 'An error occurred:' + error, 'error')
return false
}
}
// These only include the points from tasks that the script can complete!
let totalEarnablePoints = 0
async checkQuizCompleted(page: Page): Promise<boolean> {
try {
await page.waitForSelector('#quizCompleteContainer', { state: 'visible', timeout: 2000 })
await this.bot.utils.wait(2000)
// Desktop Search Points
data.userStatus.counters.pcSearch.forEach(x => totalEarnablePoints += (x.pointProgressMax - x.pointProgress))
// Mobile Search Points
if (data.userStatus.counters.mobileSearch?.length) {
data.userStatus.counters.mobileSearch.forEach(x => totalEarnablePoints += (x.pointProgressMax - x.pointProgress))
return true
} catch (error) {
return false
}
// Daily Set
data.dailySetPromotions[getFormattedDate()]?.forEach(x => totalEarnablePoints += (x.pointProgressMax - x.pointProgress))
// More Promotions
data.morePromotions.forEach(x => {
// Only count points from supported activities
if (['quiz', 'urlreward'].includes(x.activityType)) {
totalEarnablePoints += (x.pointProgressMax - x.pointProgress)
}
})
return totalEarnablePoints
} catch (error) {
throw log('GET-EARNABLE-POINTS', 'An error occurred:' + error, 'error')
}
}
export async function getCurrentPoints(data: DashboardData, page: null | Page = null): Promise<number> {
try {
// Fetch new data if page is provided
if (page) {
data = await getDashboardData(page)
}
return data.userStatus.availablePoints
} catch (error) {
throw log('GET-CURRENT-POINTS', 'An error occurred:' + error, 'error')
}
}
export async function loadSesion(email: string): Promise<string> {
const sessionDir = path.join(__dirname, sessionPath, email)
try {
// Create session dir
if (!fs.existsSync(sessionDir)) {
await fs.promises.mkdir(sessionDir, { recursive: true })
}
return sessionDir
} catch (error) {
throw new Error(error as string)
}
}
export async function waitForQuizRefresh(page: Page): Promise<boolean> {
try {
await page.waitForSelector('#rqHeaderCredits', { visible: true, timeout: 5000 })
await wait(2000)
return true
} catch (error) {
log('QUIZ-REFRESH', 'An error occurred:' + error, 'error')
return false
}
}
export async function checkQuizCompleted(page: Page): Promise<boolean> {
try {
await page.waitForSelector('#quizCompleteContainer', { visible: true, timeout: 1000 })
await wait(2000)
return true
} catch (error) {
return false
}
}
export async function refreshCheerio(page: Page): Promise<CheerioAPI> {
const html = await page.content()
const $ = load(html)
return $
}
export async function getPunchCardActivity(page: Page, activity: PromotionalItem | MorePromotion): Promise<string> {
let selector = ''
try {
async loadInCheerio(page: Page): Promise<CheerioAPI> {
const html = await page.content()
const $ = load(html)
const element = $('.offer-cta').toArray().find(x => x.attribs.href?.includes(activity.offerId))
if (element) {
selector = `a[href*="${element.attribs.href}"]`
}
} catch (error) {
log('GET-PUNCHCARD-ACTIVITY', 'An error occurred:' + error, 'error')
return $
}
return selector
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: any) => x.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 {
// Save cookies
await saveSessionData(this.bot.config.sessionPath, browser, email, this.bot.isMobile)
await this.bot.utils.wait(2000)
// Close browser
await browser.close()
this.bot.log(this.bot.isMobile, 'CLOSE-BROWSER', 'Browser closed cleanly!')
} catch (error) {
throw this.bot.log(this.bot.isMobile, 'CLOSE-BROWSER', 'An error occurred:' + error, 'error')
}
}
}

View File

@@ -1,81 +1,132 @@
import { Page } from 'puppeteer'
import { Page } from 'rebrowser-playwright'
import { load } from 'cheerio'
import { wait } from './../util/Utils'
import { log } from './../util/Logger'
import { MicrosoftRewardsBot } from '../index'
export async function tryDismissAllMessages(page: Page): Promise<boolean> {
const buttons = [
{ 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' }
]
let result = false
export default class BrowserUtil {
private bot: MicrosoftRewardsBot
for (const button of buttons) {
constructor(bot: MicrosoftRewardsBot) {
this.bot = bot
}
async tryDismissAllMessages(page: Page): Promise<void> {
const buttons = [
{ selector: '#acceptButton', label: 'AcceptButton' },
{ 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: '//div[@id="cookieConsentContainer"]//button[contains(text(), "Accept")]', label: 'Accept Cookie Consent Container', isXPath: true },
{ selector: '#bnp_btn_accept', label: 'Bing Cookie Banner' },
{ selector: '#reward_pivot_earn', label: 'Reward Coupon Accept' }
]
for (const button of buttons) {
try {
const element = button.isXPath ? page.locator(`xpath=${button.selector}`) : page.locator(button.selector)
await element.first().click({ timeout: 500 })
await page.waitForTimeout(500)
this.bot.log(this.bot.isMobile, 'DISMISS-ALL-MESSAGES', `Dismissed: ${button.label}`)
} catch (error) {
// Silent fail
}
}
// Handle blocking Bing privacy overlay intercepting clicks (#bnp_overlay_wrapper)
try {
const element = await page.waitForSelector(button.selector, { visible: true, timeout: 1000 })
if (element) {
await element.click()
result = true
const overlay = await page.locator('#bnp_overlay_wrapper').first()
if (await overlay.isVisible({ timeout: 500 }).catch(()=>false)) {
// Try common dismiss buttons inside overlay
const rejectBtn = await page.locator('#bnp_btn_reject, button[aria-label*="Reject" i]').first()
const acceptBtn = await page.locator('#bnp_btn_accept').first()
if (await rejectBtn.isVisible().catch(()=>false)) {
await rejectBtn.click({ timeout: 500 }).catch(()=>{})
this.bot.log(this.bot.isMobile, 'DISMISS-ALL-MESSAGES', 'Dismissed: Bing Overlay Reject')
} else if (await acceptBtn.isVisible().catch(()=>false)) {
await acceptBtn.click({ timeout: 500 }).catch(()=>{})
this.bot.log(this.bot.isMobile, 'DISMISS-ALL-MESSAGES', 'Dismissed: Bing Overlay Accept (fallback)')
}
await page.waitForTimeout(300)
}
} catch { /* ignore */ }
}
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 getTabs(page: Page) {
try {
const browser = page.context()
const pages = browser.pages()
const homeTab = pages[1]
let homeTabURL: URL
if (!homeTab) {
throw this.bot.log(this.bot.isMobile, 'GET-TABS', 'Home tab could not be found!', 'error')
} else {
homeTabURL = new URL(homeTab.url())
if (homeTabURL.hostname !== 'rewards.bing.com') {
throw this.bot.log(this.bot.isMobile, 'GET-TABS', 'Reward page hostname is invalid: ' + homeTabURL.host, 'error')
}
}
const workerTab = pages[2]
if (!workerTab) {
throw this.bot.log(this.bot.isMobile, 'GET-TABS', 'Worker tab could not be found!', 'error')
}
return {
homeTab: homeTab,
workerTab: workerTab
}
} catch (error) {
continue
throw this.bot.log(this.bot.isMobile, 'GET-TABS', 'An error occurred:' + error, 'error')
}
}
return result
}
async reloadBadPage(page: Page): Promise<void> {
try {
const html = await page.content().catch(() => '')
const $ = load(html)
export async function tryDismissCookieBanner(page: Page): Promise<void> {
try {
await page.waitForSelector('#cookieConsentContainer', { timeout: 1000 })
const cookieBanner = await page.$('#cookieConsentContainer')
const isNetworkError = $('body.neterror').length
if (cookieBanner) {
const button = await cookieBanner.$('button')
if (button) {
await button.click()
await wait(2000)
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')
}
} catch (error) {
// Continue if element is not found or other error occurs
}
}
export async function tryDismissBingCookieBanner(page: Page): Promise<void> {
try {
await page.waitForSelector('#bnp_btn_accept', { timeout: 1000 })
const cookieBanner = await page.$('#bnp_btn_accept')
if (cookieBanner) {
await cookieBanner.click()
}
} catch (error) {
// Continue if element is not found or other error occurs
}
}
export async function getLatestTab(page: Page): Promise<Page> {
try {
await wait(500)
const browser = page.browser()
const pages = await browser.pages()
const newTab = pages[pages.length - 1]
if (newTab) {
return newTab
}
throw log('GET-NEW-TAB', 'Unable to get latest tab', 'error')
} catch (error) {
throw log('GET-NEW-TAB', 'An error occurred:' + error, 'error')
}
}

View File

@@ -2,22 +2,50 @@
"baseURL": "https://rewards.bing.com",
"sessionPath": "sessions",
"headless": false,
"runOnZeroPoints": true,
"parallel": false,
"runOnZeroPoints": false,
"clusters": 1,
"saveFingerprint": {
"mobile": false,
"desktop": false
},
"workers": {
"doDailySet": true,
"doMorePromotions": true,
"doPunchCards": true,
"doDesktopSearch": true,
"doMobileSearch": true
"doMobileSearch": true,
"doDailyCheckIn": true,
"doReadToEarn": true
},
"searchOnBingLocalQueries": false,
"globalTimeout": "30s",
"searchSettings": {
"useGeoLocaleQueries": false,
"scrollRandomResults": true,
"clickRandomResults": true
"clickRandomResults": true,
"searchDelay": {
"min": "3min",
"max": "5min"
},
"retryMobileSearchAmount": 2
},
"logExcludeFunc": [
"SEARCH-CLOSE-TABS"
],
"webhookLogExcludeFunc": [
"SEARCH-CLOSE-TABS"
],
"proxy": {
"proxyGoogleTrends": true,
"proxyBingTerms": true
},
"webhook": {
"enabled": false,
"url": ""
},
"conclusionWebhook": {
"enabled": false,
"url": ""
}
}

2
src/crontab.template Normal file
View File

@@ -0,0 +1,2 @@
# Run automation according to CRON_SCHEDULE; redirect both stdout & stderr to Docker logs
${CRON_SCHEDULE} TZ=${TZ} /bin/bash /usr/src/microsoft-rewards-script/src/run_daily.sh >> /proc/1/fd/1 2>&1

View File

@@ -0,0 +1,70 @@
import { Page } from 'rebrowser-playwright'
import { MicrosoftRewardsBot } from '../index'
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'
import { DashboardData, MorePromotion, PromotionalItem } from '../interface/DashboardData'
export default class Activities {
private bot: MicrosoftRewardsBot
constructor(bot: MicrosoftRewardsBot) {
this.bot = bot
}
doSearch = async (page: Page, data: DashboardData): Promise<void> => {
const search = new Search(this.bot)
await search.doSearch(page, data)
}
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)
}
doQuiz = async (page: Page): Promise<void> => {
const quiz = new Quiz(this.bot)
await quiz.doQuiz(page)
}
doUrlReward = async (page: Page): Promise<void> => {
const urlReward = new UrlReward(this.bot)
await urlReward.doUrlReward(page)
}
doSearchOnBing = async (page: Page, activity: MorePromotion | PromotionalItem): Promise<void> => {
const searchOnBing = new SearchOnBing(this.bot)
await searchOnBing.doSearchOnBing(page, activity)
}
doReadToEarn = async (accessToken: string, data: DashboardData): Promise<void> => {
const readToEarn = new ReadToEarn(this.bot)
await readToEarn.doReadToEarn(accessToken, data)
}
doDailyCheckIn = async (accessToken: string, data: DashboardData): Promise<void> => {
const dailyCheckIn = new DailyCheckIn(this.bot)
await dailyCheckIn.doDailyCheckIn(accessToken, data)
}
}

View File

@@ -1,125 +1,562 @@
import { Page } from 'puppeteer'
import type { Page } from 'playwright'
import readline from 'readline'
import * as crypto from 'crypto'
import { AxiosRequestConfig } from 'axios'
import { MicrosoftRewardsBot } from '../index'
import { saveSessionData } from '../util/Load'
import { OAuth } from '../interface/OAuth'
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
// Use as any to avoid strict typing issues with our minimal process shim
input: (process as any).stdin,
output: (process as any).stdout
})
import { tryDismissAllMessages, tryDismissBingCookieBanner } from '../browser/BrowserUtil'
import { wait } from '../util/Utils'
import { log } from '../util/Logger'
export class Login {
private bot: MicrosoftRewardsBot
private clientId: string = '0000000040170455'
private authBaseUrl: string = 'https://login.live.com/oauth20_authorize.srf'
private redirectUrl: string = 'https://login.live.com/oauth20_desktop.srf'
private tokenUrl: string = 'https://login.microsoftonline.com/consumers/oauth2/v2.0/token'
private scope: string = 'service::prod.rewardsplatform.microsoft.com::MBI_SSL'
// Flag to prevent spamming passkey logs after first handling
private passkeyHandled: boolean = false
export async function login(page: Page, email: string, password: string) {
constructor(bot: MicrosoftRewardsBot) {
this.bot = bot
}
try {
// Navigate to the Bing login page
await page.goto('https://login.live.com/')
async login(page: Page, email: string, password: string) {
const isLoggedIn = await page.waitForSelector('html[data-role-name="MeePortal"]', { timeout: 5000 }).then(() => true).catch(() => false)
try {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Starting login process!')
if (!isLoggedIn) {
const isLocked = await page.waitForSelector('.serviceAbusePageContainer', { visible: true, timeout: 5000 }).then(() => true).catch(() => false)
if (isLocked) {
log('LOGIN', 'This account has been locked!', 'error')
throw new Error('Account has been locked!')
// Navigate to the Bing login page
await page.goto('https://www.bing.com/rewards/dashboard')
// Disable FIDO support in login request
await page.route('**/GetCredentialType.srf*', (route: any) => {
const body = JSON.parse(route.request().postData() || '{}')
body.isFidoSupported = false
route.continue({ postData: JSON.stringify(body) })
})
await page.waitForLoadState('domcontentloaded').catch(() => { })
await this.bot.browser.utils.reloadBadPage(page)
// Check if account is locked
await this.checkAccountLocked(page)
const isLoggedIn = await page.waitForSelector('html[data-role-name="RewardsPortal"]', { timeout: 10000 }).then(() => true).catch(() => false)
if (!isLoggedIn) {
await this.execLogin(page, email, password)
this.bot.log(this.bot.isMobile, 'LOGIN', 'Logged into Microsoft successfully')
} else {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Already logged in')
// Check if account is locked
await this.checkAccountLocked(page)
}
await page.waitForSelector('#loginHeader', { visible: true, timeout: 10_000 })
// Check if logged in to bing
await this.checkBingLogin(page)
await execLogin(page, email, password)
log('LOGIN', 'Logged into Microsoft successfully')
} else {
log('LOGIN', 'Already logged in')
// Save session
await saveSessionData(this.bot.config.sessionPath, page.context(), email, this.bot.isMobile)
// We're done logging in
this.bot.log(this.bot.isMobile, 'LOGIN', 'Logged in successfully, saved login session!')
} catch (error) {
// Throw and don't continue
throw this.bot.log(this.bot.isMobile, 'LOGIN', 'An error occurred:' + error, 'error')
}
// Check if logged in to bing
await checkBingLogin(page)
// We're done logging in
log('LOGIN', 'Logged in successfully')
} catch (error) {
// Throw and don't continue
throw log('LOGIN', 'An error occurred:' + error, 'error')
}
}
async function execLogin(page: Page, email: string, password: string) {
await page.type('#i0116', email)
await page.click('#idSIButton9')
private async execLogin(page: Page, email: string, password: string) {
try {
await this.enterEmail(page, email)
await this.bot.utils.wait(2000)
await this.bot.browser.utils.reloadBadPage(page)
await this.bot.utils.wait(2000)
await this.enterPassword(page, password)
await this.bot.utils.wait(2000)
log('LOGIN', 'Email entered successfully')
// Check if account is locked
await this.checkAccountLocked(page)
try {
await page.waitForSelector('#i0118', { visible: true, timeout: 2000 })
await wait(2000)
await this.bot.browser.utils.reloadBadPage(page)
await this.checkLoggedIn(page)
} catch (error) {
this.bot.log(this.bot.isMobile, 'LOGIN', 'An error occurred: ' + error, 'error')
}
}
await page.type('#i0118', password)
await page.click('#idSIButton9')
private async enterEmail(page: Page, email: string) {
const emailInputSelector = 'input[type="email"]'
} catch (error) {
log('LOGIN', '2FA code required')
try {
// Wait for email field
const emailField = await page.waitForSelector(emailInputSelector, { state: 'visible', timeout: 2000 }).catch(() => null)
if (!emailField) {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Email field not found', 'warn')
return
}
await this.bot.utils.wait(1000)
// Check if email is prefilled
const emailPrefilled = await page.waitForSelector('#userDisplayName', { timeout: 5000 }).catch(() => null)
if (emailPrefilled) {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Email already prefilled by Microsoft')
} else {
// Else clear and fill email
await page.fill(emailInputSelector, '')
await this.bot.utils.wait(500)
await page.fill(emailInputSelector, email)
await this.bot.utils.wait(1000)
}
const nextButton = await page.waitForSelector('button[type="submit"]', { timeout: 2000 }).catch(() => null)
if (nextButton) {
await nextButton.click()
await this.bot.utils.wait(2000)
this.bot.log(this.bot.isMobile, 'LOGIN', 'Email entered successfully')
} else {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Next button not found after email entry', 'warn')
}
} catch (error) {
this.bot.log(this.bot.isMobile, 'LOGIN', `Email entry failed: ${error}`, 'error')
}
}
private async enterPassword(page: Page, password: string) {
const passwordInputSelector = 'input[type="password"]'
const skip2FASelector = '#idA_PWD_SwitchToPassword';
try {
const skip2FAButton = await page.waitForSelector(skip2FASelector, { timeout: 2000 }).catch(() => null)
if (skip2FAButton) {
await skip2FAButton.click()
await this.bot.utils.wait(2000)
this.bot.log(this.bot.isMobile, 'LOGIN', 'Skipped 2FA')
} else {
this.bot.log(this.bot.isMobile, 'LOGIN', 'No 2FA skip button found, proceeding with password entry')
}
const viewFooter = await page.waitForSelector('#view > div > span:nth-child(6)', { timeout: 2000 }).catch(() => null)
const passwordField1 = await page.waitForSelector(passwordInputSelector, { timeout: 5000 }).catch(() => null)
if (viewFooter && !passwordField1) {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Page "Get a code to sign in" found by "viewFooter"')
const otherWaysButton = await viewFooter.$('span[role="button"]')
if (otherWaysButton) {
await otherWaysButton.click()
await this.bot.utils.wait(5000)
const secondListItem = page.locator('[role="listitem"]').nth(1)
if (await secondListItem.isVisible()) {
await secondListItem.click()
}
}
}
// Wait for password field
const passwordField = await page.waitForSelector(passwordInputSelector, { state: 'visible', timeout: 5000 }).catch(() => null)
if (!passwordField) {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Password field not found, possibly 2FA required', 'warn')
await this.handle2FA(page)
return
}
await this.bot.utils.wait(1000)
// Clear and fill password
await page.fill(passwordInputSelector, '')
await this.bot.utils.wait(500)
await page.fill(passwordInputSelector, password)
await this.bot.utils.wait(1000)
const nextButton = await page.waitForSelector('button[type="submit"]', { timeout: 2000 }).catch(() => null)
if (nextButton) {
await nextButton.click()
await this.bot.utils.wait(2000)
this.bot.log(this.bot.isMobile, 'LOGIN', 'Password entered successfully')
} else {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Next button not found after password entry', 'warn')
}
} catch (error) {
this.bot.log(this.bot.isMobile, 'LOGIN', `Password entry failed: ${error}`, 'error')
await this.handle2FA(page)
}
}
private async handle2FA(page: Page) {
try {
const numberToPress = await this.get2FACode(page)
if (numberToPress) {
// Authenticator App verification
await this.authAppVerification(page, numberToPress)
} else {
// SMS verification
await this.authSMSVerification(page)
}
} catch (error) {
this.bot.log(this.bot.isMobile, 'LOGIN', `2FA handling failed: ${error}`)
}
}
private async get2FACode(page: Page): Promise<string | null> {
try {
const element = await page.waitForSelector('#displaySign, div[data-testid="displaySign"]>span', { state: 'visible', timeout: 2000 })
return await element.textContent()
} catch {
if (this.bot.config.parallel) {
this.bot.log(this.bot.isMobile, 'LOGIN', 'Script running in parallel, can only send 1 2FA request per account at a time!', 'log', 'yellow')
this.bot.log(this.bot.isMobile, 'LOGIN', 'Trying again in 60 seconds! Please wait...', 'log', 'yellow')
// eslint-disable-next-line no-constant-condition
while (true) {
const button = await page.waitForSelector('button[aria-describedby="pushNotificationsTitle errorDescription"]', { state: 'visible', timeout: 2000 }).catch(() => null)
if (button) {
await this.bot.utils.wait(60000)
await button.click()
continue
} else {
break
}
}
}
await page.click('button[aria-describedby="confirmSendTitle"]').catch(() => { })
await this.bot.utils.wait(2000)
const element = await page.waitForSelector('#displaySign, div[data-testid="displaySign"]>span', { state: 'visible', timeout: 2000 })
return await element.textContent()
}
}
private async authAppVerification(page: Page, numberToPress: string | null) {
// eslint-disable-next-line no-constant-condition
while (true) {
try {
this.bot.log(this.bot.isMobile, 'LOGIN', `Press the number ${numberToPress} on your Authenticator app to approve the login`)
this.bot.log(this.bot.isMobile, 'LOGIN', 'If you press the wrong number or the "DENY" button, try again in 60 seconds')
await page.waitForSelector('form[name="f1"]', { state: 'detached', timeout: 60000 })
this.bot.log(this.bot.isMobile, 'LOGIN', 'Login successfully approved!')
break
} catch {
this.bot.log(this.bot.isMobile, 'LOGIN', 'The code is expired. Trying to get a new code...')
// await page.click('button[aria-describedby="pushNotificationsTitle errorDescription"]')
const primaryButton = await page.waitForSelector('button[data-testid="primaryButton"]', { state: 'visible', timeout: 5000 }).catch(() => null)
if (primaryButton) {
await primaryButton.click()
}
numberToPress = await this.get2FACode(page)
}
}
}
private async authSMSVerification(page: Page) {
this.bot.log(this.bot.isMobile, 'LOGIN', 'SMS 2FA code required. Waiting for user input...')
const code = await new Promise<string>((resolve) => {
rl.question('Enter 2FA code:\n', (input) => {
rl.question('Enter 2FA code:\n', (input: string) => {
rl.close()
resolve(input)
})
})
await page.type('input[name="otc"]', code)
await page.fill('input[name="otc"]', code)
await page.keyboard.press('Enter')
} finally {
log('LOGIN', 'Password entered successfully')
this.bot.log(this.bot.isMobile, 'LOGIN', '2FA code entered successfully')
}
const currentURL = new URL(page.url())
async getMobileAccessToken(page: Page, email: string) {
const authorizeUrl = new URL(this.authBaseUrl)
while (currentURL.pathname !== '/' || currentURL.hostname !== 'account.microsoft.com') {
await tryDismissAllMessages(page)
currentURL.href = page.url()
}
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', crypto.randomBytes(16).toString('hex'))
authorizeUrl.searchParams.append('access_type', 'offline_access')
authorizeUrl.searchParams.append('login_hint', email)
// Wait for login to complete
await page.waitForSelector('html[data-role-name="MeePortal"]', { timeout: 10_000 })
}
// Disable FIDO for OAuth flow as well (reduces passkey prompts resurfacing)
await page.route('**/GetCredentialType.srf*', (route: any) => {
const body = JSON.parse(route.request().postData() || '{}')
body.isFidoSupported = false
route.continue({ postData: JSON.stringify(body) })
}).catch(()=>{})
async function checkBingLogin(page: Page): Promise<void> {
try {
log('LOGIN-BING', 'Verifying Bing login')
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')
await page.goto(authorizeUrl.href)
const maxIterations = 5
let currentUrl = new URL(page.url())
let code: string
for (let iteration = 1; iteration <= maxIterations; iteration++) {
const currentUrl = new URL(page.url())
if (currentUrl.hostname === 'www.bing.com' && currentUrl.pathname === '/') {
await wait(3000)
await tryDismissBingCookieBanner(page)
const loggedIn = await checkBingLoginStatus(page)
if (loggedIn) {
log('LOGIN-BING', 'Bing login verification passed!')
break
}
const authStart = Date.now()
this.bot.log(this.bot.isMobile, 'LOGIN-APP', 'Waiting for authorization...')
// eslint-disable-next-line no-constant-condition
while (true) {
// Attempt to dismiss passkey/passkey-like screens quickly (non-blocking)
await this.tryDismissPasskeyPrompt(page)
if (currentUrl.hostname === 'login.live.com' && currentUrl.pathname === '/oauth20_desktop.srf') {
code = currentUrl.searchParams.get('code')!
break
}
await wait(1000)
currentUrl = new URL(page.url())
// Shorter wait to react faster to passkey prompt
await this.bot.utils.wait(1000)
}
} catch (error) {
log('LOGIN-BING', 'An error occurred:' + error, 'error')
const body = new URLSearchParams()
body.append('grant_type', 'authorization_code')
body.append('client_id', this.clientId)
body.append('code', code)
body.append('redirect_uri', this.redirectUrl)
const tokenRequest: AxiosRequestConfig = {
url: this.tokenUrl,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: body.toString()
}
const tokenResponse = await this.bot.axios.request(tokenRequest)
const tokenData: OAuth = await tokenResponse.data
const authDuration = Date.now() - authStart
this.bot.log(this.bot.isMobile, 'LOGIN-APP', `Successfully authorized in ${Math.round(authDuration/1000)}s`)
return tokenData.access_token
}
// Utils
private async checkLoggedIn(page: Page) {
const targetHostname = 'rewards.bing.com'
const targetPathname = '/'
const start = Date.now()
const maxWaitMs = Number(process.env.LOGIN_MAX_WAIT_MS || 180000) // default 3 minutes
let guidanceLogged = false
// eslint-disable-next-line no-constant-condition
while (true) {
await this.dismissLoginMessages(page)
const currentURL = new URL(page.url())
if (currentURL.hostname === targetHostname && currentURL.pathname === targetPathname) {
break
}
// If we keep looping without prompts for too long, advise and fail fast
const elapsed = Date.now() - start
if (elapsed > maxWaitMs) {
if (!guidanceLogged) {
this.bot.log(this.bot.isMobile, 'LOGIN-GUIDE', 'Login taking too long without prompts.')
this.bot.log(this.bot.isMobile, 'LOGIN-GUIDE', 'Tip: Enable passwordless sign-in (Microsoft Authenticator "number match") or add a TOTP secret in accounts.json to auto-fill OTP.')
this.bot.log(this.bot.isMobile, 'LOGIN-GUIDE', 'You can also set LOGIN_MAX_WAIT_MS to increase this timeout if needed.')
guidanceLogged = true
}
throw this.bot.log(this.bot.isMobile, 'LOGIN-TIMEOUT', `Login timed out after ${Math.round(elapsed/1000)}s without completing`, 'error')
}
}
// Wait for login to complete
await page.waitForSelector('html[data-role-name="RewardsPortal"]', { timeout: 10000 })
this.bot.log(this.bot.isMobile, 'LOGIN', 'Successfully logged into the rewards portal')
}
private lastNoPromptLog: number = 0
private noPromptIterations: number = 0
private async dismissLoginMessages(page: Page) {
let didSomething = false
// PASSKEY / Windows Hello / Sign in faster
const passkeyVideo = await page.waitForSelector('[data-testid="biometricVideo"]', { timeout: 1000 }).catch(() => null)
if (passkeyVideo) {
const skipButton = await page.$('button[data-testid="secondaryButton"]')
if (skipButton) {
await skipButton.click().catch(()=>{})
if (!this.passkeyHandled) {
this.bot.log(this.bot.isMobile, 'LOGIN-PASSKEY', 'Passkey dialog detected (video heuristic) -> clicked "Skip for now"')
}
this.passkeyHandled = true
await page.waitForTimeout(300)
didSomething = true
}
}
if (!didSomething) {
const titleEl = await page.waitForSelector('[data-testid="title"]', { timeout: 800 }).catch(() => null)
const titleText = (titleEl ? (await titleEl.textContent()) : '')?.trim() || ''
const looksLikePasskey = /sign in faster|passkey|fingerprint|face|pin/i.test(titleText)
const secondaryBtn = await page.waitForSelector('button[data-testid="secondaryButton"]', { timeout: 500 }).catch(() => null)
const primaryBtn = await page.waitForSelector('button[data-testid="primaryButton"]', { timeout: 500 }).catch(() => null)
if (looksLikePasskey && secondaryBtn) {
await secondaryBtn.click().catch(()=>{})
if (!this.passkeyHandled) {
this.bot.log(this.bot.isMobile, 'LOGIN-PASSKEY', `Passkey dialog detected (title: "${titleText}") -> clicked secondary`)
}
this.passkeyHandled = true
await page.waitForTimeout(300)
didSomething = true
} else if (!didSomething && secondaryBtn && primaryBtn) {
const secText = (await secondaryBtn.textContent() || '').trim()
if (/skip for now/i.test(secText)) {
await secondaryBtn.click().catch(()=>{})
if (!this.passkeyHandled) {
this.bot.log(this.bot.isMobile, 'LOGIN-PASSKEY', 'Passkey dialog (pair heuristic) -> clicked secondary (Skip for now)')
}
this.passkeyHandled = true
await page.waitForTimeout(300)
didSomething = true
}
}
if (!didSomething) {
const skipByText = await page.locator('xpath=//button[contains(normalize-space(.), "Skip for now")]').first()
if (await skipByText.isVisible().catch(()=>false)) {
await skipByText.click().catch(()=>{})
if (!this.passkeyHandled) {
this.bot.log(this.bot.isMobile, 'LOGIN-PASSKEY', 'Passkey dialog (text fallback) -> clicked "Skip for now"')
}
this.passkeyHandled = true
await page.waitForTimeout(300)
didSomething = true
}
}
if (!didSomething) {
const closeBtn = await page.$('#close-button')
if (closeBtn) {
await closeBtn.click().catch(()=>{})
if (!this.passkeyHandled) {
this.bot.log(this.bot.isMobile, 'LOGIN-PASSKEY', 'Attempted close button on potential passkey modal')
}
this.passkeyHandled = true
await page.waitForTimeout(300)
}
}
}
// KMSI (Keep me signed in) prompt
const kmsi = await page.waitForSelector('[data-testid="kmsiVideo"]', { timeout: 800 }).catch(()=>null)
if (kmsi) {
const yesButton = await page.$('button[data-testid="primaryButton"]')
if (yesButton) {
await yesButton.click().catch(()=>{})
this.bot.log(this.bot.isMobile, 'LOGIN-KMSI', 'KMSI dialog detected -> accepted (Yes)')
await page.waitForTimeout(300)
didSomething = true
}
}
if (!didSomething) {
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})`)
// Reset counter if it grows large to keep number meaningful
if (this.noPromptIterations > 50) this.noPromptIterations = 0
}
} else {
// Reset counters after an interaction
this.noPromptIterations = 0
}
}
/** Lightweight passkey prompt dismissal used in mobile OAuth loop */
private async tryDismissPasskeyPrompt(page: Page) {
try {
// Fast existence checks with very small timeouts to avoid slowing the loop
const titleEl = await page.waitForSelector('[data-testid="title"]', { timeout: 500 }).catch(() => null)
const secondaryBtn = await page.waitForSelector('button[data-testid="secondaryButton"]', { timeout: 500 }).catch(() => null)
// Direct text locator fallback (sometimes data-testid changes)
const textSkip = secondaryBtn ? null : await page.locator('xpath=//button[contains(normalize-space(.), "Skip for now")]').first().isVisible().catch(()=>false)
if (secondaryBtn) {
// Heuristic: if title indicates passkey or both primary/secondary exist with typical text
let shouldClick = false
let titleText = ''
if (titleEl) {
titleText = (await titleEl.textContent() || '').trim()
if (/sign in faster|passkey|fingerprint|face|pin/i.test(titleText)) {
shouldClick = true
}
}
if (!shouldClick && textSkip) {
shouldClick = true
}
if (!shouldClick) {
// Fallback text probe on the secondary button itself
const btnText = (await secondaryBtn.textContent() || '').trim()
if (/skip for now/i.test(btnText)) {
shouldClick = true
}
}
if (shouldClick) {
await secondaryBtn.click().catch(() => { })
if (!this.passkeyHandled) {
this.bot.log(this.bot.isMobile, 'LOGIN-PASSKEY', `Passkey prompt (loop) -> clicked skip${titleText ? ` (title: ${titleText})` : ''}`)
}
this.passkeyHandled = true
await this.bot.utils.wait(500)
}
}
} catch { /* ignore minor errors */ }
}
private async checkBingLogin(page: Page): Promise<void> {
try {
this.bot.log(this.bot.isMobile, 'LOGIN-BING', 'Verifying Bing login')
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')
const maxIterations = 5
for (let iteration = 1; iteration <= maxIterations; iteration++) {
const currentUrl = new URL(page.url())
if (currentUrl.hostname === 'www.bing.com' && currentUrl.pathname === '/') {
await this.bot.browser.utils.tryDismissAllMessages(page)
const loggedIn = await this.checkBingLoginStatus(page)
// If mobile browser, skip this step
if (loggedIn || this.bot.isMobile) {
this.bot.log(this.bot.isMobile, 'LOGIN-BING', 'Bing login verification passed!')
break
}
}
await this.bot.utils.wait(1000)
}
} catch (error) {
this.bot.log(this.bot.isMobile, 'LOGIN-BING', 'An error occurred:' + error, 'error')
}
}
private async checkBingLoginStatus(page: Page): Promise<boolean> {
try {
await page.waitForSelector('#id_n', { timeout: 5000 })
return true
} catch (error) {
return false
}
}
private async checkAccountLocked(page: Page) {
await this.bot.utils.wait(2000)
const isLocked = await page.waitForSelector('#serviceAbuseLandingTitle', { state: 'visible', timeout: 1000 }).then(() => true).catch(() => false)
if (isLocked) {
throw this.bot.log(this.bot.isMobile, 'CHECK-LOCKED', 'This account has been locked! Remove the account from "accounts.json" and restart!', 'error')
}
}
}
async function checkBingLoginStatus(page: Page): Promise<boolean> {
try {
await page.waitForSelector('#id_n', { timeout: 5000 })
return true
} catch (error) {
return false
}
}

View File

@@ -1,173 +1,230 @@
import { Page } from 'puppeteer'
import { doPoll } from './activities/Poll'
import { doQuiz } from './activities/Quiz'
import { doUrlReward } from './activities/UrlReward'
import { doThisOrThat } from './activities/ThisOrThat'
import { doABC } from './activities/ABC'
import { getPunchCardActivity } from '../browser/BrowserFunc'
import { getLatestTab } from '../browser/BrowserUtil'
import { getFormattedDate, wait } from '../util/Utils'
import { log } from '../util/Logger'
import { Page } from 'rebrowser-playwright'
import { DashboardData, MorePromotion, PromotionalItem, PunchCard } from '../interface/DashboardData'
import { baseURL } from '../config.json'
import { MicrosoftRewardsBot } from '../index'
// Daily Set
export async function doDailySet(page: Page, data: DashboardData) {
export class Workers {
public bot: MicrosoftRewardsBot
const todayData = data.dailySetPromotions[getFormattedDate()]
const activitiesUncompleted = todayData?.filter(x => !x.complete && x.pointProgressMax > 0) ?? []
if (!activitiesUncompleted.length) {
log('DAILY-SET', 'All Daily Set" items have already been completed')
return
constructor(bot: MicrosoftRewardsBot) {
this.bot = bot
}
// Solve Activities
log('DAILY-SET', 'Started solving "Daily Set" items')
// Daily Set
async doDailySet(page: Page, data: DashboardData) {
const todayData = data.dailySetPromotions[this.bot.utils.getFormattedDate()]
await solveActivities(page, activitiesUncompleted)
const activitiesUncompleted = todayData?.filter(x => !x.complete && x.pointProgressMax > 0) ?? []
log('DAILY-SET', 'All "Daily Set" items have been completed')
}
// Punch Card
export async function doPunchCard(page: Page, data: DashboardData) {
const punchCardsUncompleted = data.punchCards?.filter(x => !x.parentPromotion.complete) ?? [] // Only return uncompleted punch cards
if (!punchCardsUncompleted.length) {
log('PUNCH-CARD', 'All "Punch Cards" have already been completed')
return
}
for (const punchCard of punchCardsUncompleted) {
const activitiesUncompleted = punchCard.childPromotions.filter(x => !x.complete) // Only return uncompleted activities
if (!activitiesUncompleted.length) {
this.bot.log(this.bot.isMobile, 'DAILY-SET', 'All Daily Set" items have already been completed')
return
}
// Solve Activities
log('PUNCH-CARD', `Started solving "Punch Card" items for punchcard: "${punchCard.parentPromotion.title}"`)
this.bot.log(this.bot.isMobile, 'DAILY-SET', 'Started solving "Daily Set" items')
const browser = page.browser()
page = await browser.newPage()
await this.solveActivities(page, activitiesUncompleted)
// Got to punch card index page in a new tab
await page.goto(punchCard.parentPromotion.destinationUrl, { referer: baseURL })
page = await this.bot.browser.utils.getLatestTab(page)
await solveActivities(page, activitiesUncompleted, punchCard)
// Always return to the homepage if not already
await this.bot.browser.func.goHome(page)
// Close the punch card index page
await page.close()
log('PUNCH-CARD', `All items for punchcard: "${punchCard.parentPromotion.title}" have been completed`)
this.bot.log(this.bot.isMobile, 'DAILY-SET', 'All "Daily Set" items have been completed')
}
log('PUNCH-CARD', 'All "Punch Card" items have been completed')
}
// Punch Card
async doPunchCard(page: Page, data: DashboardData) {
// More Promotions
export async function doMorePromotions(page: Page, data: DashboardData) {
const morePromotions = data.morePromotions
const punchCardsUncompleted = data.punchCards?.filter(x => x.parentPromotion && !x.parentPromotion.complete) ?? [] // Only return uncompleted punch cards
// 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)
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')
}
const activitiesUncompleted = morePromotions?.filter(x => !x.complete && x.pointProgressMax > 0) ?? []
// More Promotions
async doMorePromotions(page: Page, data: DashboardData) {
const morePromotions = data.morePromotions
if (!activitiesUncompleted.length) {
log('MORE-PROMOTIONS', 'All "More Promotion" items have already been completed')
return
// 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 Activities
log('MORE-PROMOTIONS', 'Started solving "More Promotions" item')
// Solve all the different types of activities
private async solveActivities(activityPage: Page, activities: PromotionalItem[] | MorePromotion[], punchCard?: PunchCard) {
const activityInitial = activityPage.url() // Homepage for Daily/More and Index for promotions
await solveActivities(page, activitiesUncompleted)
for (const activity of activities) {
try {
// Reselect the worker page
activityPage = await this.bot.browser.utils.getLatestTab(activityPage)
log('MORE-PROMOTIONS', 'All "More Promotion" items have been completed')
}
const pages = activityPage.context().pages()
if (pages.length > 3) {
await activityPage.close()
// Solve all the different types of activities
async function solveActivities(page: Page, activities: PromotionalItem[] | MorePromotion[], punchCard?: PunchCard) {
for (const activity of activities) {
try {
let selector = `[data-bi-id="${activity.offerId}"]`
if (punchCard) {
selector = await getPunchCardActivity(page, activity)
} else if (activity.name.toLowerCase().includes('membercenter')) {
// Promotion
if (activity.priority === 1) {
selector = '#promo-item'
} else {
selector = `[data-bi-id="${activity.name}"]`
activityPage = await this.bot.browser.utils.getLatestTab(activityPage)
}
await this.bot.utils.wait(1000)
if (activityPage.url() !== activityInitial) {
await activityPage.goto(activityInitial)
}
let selector = `[data-bi-id^="${activity.offerId}"] .pointLink:not(.contentContainer .pointLink)`
if (punchCard) {
selector = await this.bot.browser.func.getPunchCardActivity(activityPage, activity)
} else if (activity.name.toLowerCase().includes('membercenter') || activity.name.toLowerCase().includes('exploreonbing')) {
selector = `[data-bi-id^="${activity.name}"] .pointLink:not(.contentContainer .pointLink)`
}
// Wait for the new tab to fully load, ignore error.
/*
Due to common false timeout on this function, we're ignoring the error regardless, if it worked then it's faster,
if it didn't then it gave enough time for the page to load.
*/
await activityPage.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => { })
await this.bot.utils.wait(2000)
switch (activity.promotionType) {
// Quiz (Poll, Quiz or ABC)
case 'quiz':
switch (activity.pointProgressMax) {
// Poll or ABC (Usually 10 points)
case 10:
// Normal poll
if (activity.destinationUrl.toLowerCase().includes('pollscenarioid')) {
this.bot.log(this.bot.isMobile, 'ACTIVITY', `Found activity type: "Poll" title: "${activity.title}"`)
await activityPage.click(selector)
activityPage = await this.bot.browser.utils.getLatestTab(activityPage)
await this.bot.activities.doPoll(activityPage)
} else { // ABC
this.bot.log(this.bot.isMobile, 'ACTIVITY', `Found activity type: "ABC" title: "${activity.title}"`)
await activityPage.click(selector)
activityPage = await this.bot.browser.utils.getLatestTab(activityPage)
await this.bot.activities.doABC(activityPage)
}
break
// This Or That Quiz (Usually 50 points)
case 50:
this.bot.log(this.bot.isMobile, 'ACTIVITY', `Found activity type: "ThisOrThat" title: "${activity.title}"`)
await activityPage.click(selector)
activityPage = await this.bot.browser.utils.getLatestTab(activityPage)
await this.bot.activities.doThisOrThat(activityPage)
break
// Quizzes are usually 30-40 points
default:
this.bot.log(this.bot.isMobile, 'ACTIVITY', `Found activity type: "Quiz" title: "${activity.title}"`)
await activityPage.click(selector)
activityPage = await this.bot.browser.utils.getLatestTab(activityPage)
await this.bot.activities.doQuiz(activityPage)
break
}
break
// UrlReward (Visit)
case 'urlreward':
// Search on Bing are subtypes of "urlreward"
if (activity.name.toLowerCase().includes('exploreonbing')) {
this.bot.log(this.bot.isMobile, 'ACTIVITY', `Found activity type: "SearchOnBing" title: "${activity.title}"`)
await activityPage.click(selector)
activityPage = await this.bot.browser.utils.getLatestTab(activityPage)
await this.bot.activities.doSearchOnBing(activityPage, activity)
} else {
this.bot.log(this.bot.isMobile, 'ACTIVITY', `Found activity type: "UrlReward" title: "${activity.title}"`)
await activityPage.click(selector)
activityPage = await this.bot.browser.utils.getLatestTab(activityPage)
await this.bot.activities.doUrlReward(activityPage)
}
break
// Unsupported types
default:
this.bot.log(this.bot.isMobile, 'ACTIVITY', `Skipped activity "${activity.title}" | Reason: Unsupported type: "${activity.promotionType}"!`, 'warn')
break
}
// Cooldown
await this.bot.utils.wait(2000)
} catch (error) {
this.bot.log(this.bot.isMobile, 'ACTIVITY', 'An error occurred:' + error, 'error')
}
// Wait for element to load
await page.waitForSelector(selector, { timeout: 5000 })
// Click element, it will be opened in a new tab
await page.click(selector)
// Select the new activity page
const activityPage = await getLatestTab(page)
switch (activity.promotionType) {
// Quiz (Poll, Quiz or ABC)
case 'quiz':
switch (activity.pointProgressMax) {
// Poll or ABC (Usually 10 points)
case 10:
// Normal poll
if (activity.destinationUrl.toLowerCase().includes('pollscenarioid')) {
log('ACTIVITY', `Found activity type: "Poll" title: "${activity.title}"`)
await doPoll(activityPage)
} else { // ABC
log('ACTIVITY', `Found activity type: "ABC" title: "${activity.title}"`)
await doABC(activityPage)
}
break
// This Or That Quiz (Usually 50 points)
case 50:
log('ACTIVITY', `Found activity type: "ThisOrThat" title: "${activity.title}"`)
await doThisOrThat(activityPage)
break
// Quizzes are usually 30-40 points
default:
log('ACTIVITY', `Found activity type: "Quiz" title: "${activity.title}"`)
await doQuiz(activityPage)
break
}
break
// UrlReward (Visit)
case 'urlreward':
log('ACTIVITY', `Found activity type: "UrlReward" title: "${activity.title}"`)
await doUrlReward(activityPage)
break
// Misc, Usually UrlReward Type
default:
log('ACTIVITY', `Found activity type: "Misc" title: "${activity.title}"`)
await doUrlReward(activityPage)
break
}
// Cooldown
await wait(1500)
} catch (error) {
log('ACTIVITY', 'An error occurred:' + error, 'error')
}
}
}

View File

@@ -1,52 +1,52 @@
import { Page } from 'puppeteer'
import { Page } from 'rebrowser-playwright'
import { refreshCheerio } from '../../browser/BrowserFunc'
import { getLatestTab } from '../../browser/BrowserUtil'
import { log } from '../../util/Logger'
import { randomNumber, wait } from '../../util/Utils'
import { Workers } from '../Workers'
export async function doABC(page: Page) {
log('ABC', 'Trying to complete poll')
try {
await wait(2000)
let $ = await refreshCheerio(page)
export class ABC extends Workers {
// Don't loop more than 15 in case unable to solve, would lock otherwise
const maxIterations = 15
let i
for (i = 0; i < maxIterations && !$('span.rw_icon').length; i++) {
await page.waitForSelector('.wk_OptionClickClass', { visible: true, timeout: 5000 })
async doABC(page: Page) {
this.bot.log(this.bot.isMobile, 'ABC', 'Trying to complete poll')
const answers = $('.wk_OptionClickClass')
const answer = answers[randomNumber(0, 2)]?.attribs['id']
try {
let $ = await this.bot.browser.func.loadInCheerio(page)
await page.waitForSelector(`#${answer}`, { visible: true, timeout: 5000 })
// Don't loop more than 15 in case unable to solve, would lock otherwise
const maxIterations = 15
let i
for (i = 0; i < maxIterations && !$('span.rw_icon').length; i++) {
await page.waitForSelector('.wk_OptionClickClass', { state: 'visible', timeout: 10000 })
await wait(2000)
await page.click(`#${answer}`) // Click answer
const answers = $('.wk_OptionClickClass')
const answer = answers[this.bot.utils.randomNumber(0, 2)]?.attribs['id']
await wait(4000)
await page.waitForSelector('div.wk_button', { visible: true, timeout: 5000 })
await page.click('div.wk_button') // Click next question button
await page.waitForSelector(`#${answer}`, { state: 'visible', timeout: 10000 })
page = await getLatestTab(page)
$ = await refreshCheerio(page)
await wait(1000)
await this.bot.utils.wait(2000)
await page.click(`#${answer}`) // Click answer
await this.bot.utils.wait(4000)
await page.waitForSelector('div.wk_button', { state: 'visible', timeout: 10000 })
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(1000)
}
await this.bot.utils.wait(4000)
await page.close()
if (i === maxIterations) {
this.bot.log(this.bot.isMobile, 'ABC', 'Failed to solve quiz, exceeded max iterations of 15', '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')
}
await wait(4000)
await page.close()
if (i === maxIterations) {
log('ABC', 'Failed to solve quiz, exceeded max iterations of 15', 'warn')
} else {
log('ABC', 'Completed the ABC successfully')
}
} catch (error) {
await page.close()
log('ABC', 'An error occurred:' + error, 'error')
}
}
}

View File

@@ -0,0 +1,48 @@
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'
},
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

@@ -1,26 +1,29 @@
import { Page } from 'puppeteer'
import { Page } from 'rebrowser-playwright'
import { log } from '../../util/Logger'
import { randomNumber, wait } from '../../util/Utils'
import { Workers } from '../Workers'
export async function doPoll(page: Page) {
log('POLL', 'Trying to complete poll')
try {
const buttonId = `#btoption${Math.floor(randomNumber(0, 1))}`
export class Poll extends Workers {
await page.waitForNetworkIdle({ timeout: 5000 })
await page.waitForSelector(buttonId, { visible: true, timeout: 5000 })
await wait(2000)
async doPoll(page: Page) {
this.bot.log(this.bot.isMobile, 'POLL', 'Trying to complete poll')
await page.click(buttonId)
try {
const buttonId = `#btoption${Math.floor(this.bot.utils.randomNumber(0, 1))}`
await wait(4000)
await page.close()
await page.waitForSelector(buttonId, { state: 'visible', timeout: 10000 }).catch(() => { }) // We're gonna click regardless or not
await this.bot.utils.wait(2000)
log('POLL', 'Completed the poll successfully')
} catch (error) {
await page.close()
log('POLL', 'An error occurred:' + error, 'error')
await page.click(buttonId)
await this.bot.utils.wait(4000)
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

@@ -1,94 +1,92 @@
import { Page } from 'puppeteer'
import { Page } from 'rebrowser-playwright'
import { getQuizData, waitForQuizRefresh } from '../../browser/BrowserFunc'
import { wait } from '../../util/Utils'
import { log } from '../../util/Logger'
import { Workers } from '../Workers'
export async function doQuiz(page: Page) {
log('QUIZ', 'Trying to complete quiz')
try {
await page.waitForNetworkIdle({ timeout: 5000 })
await wait(2000)
export class Quiz extends Workers {
// Check if the quiz has been started or not
const quizNotStarted = await page.waitForSelector('#rqStartQuiz', { visible: true, timeout: 3000 }).then(() => true).catch(() => false)
if (quizNotStarted) {
await page.click('#rqStartQuiz')
} else {
log('QUIZ', 'Quiz has already been started, trying to finish it')
}
async doQuiz(page: Page) {
this.bot.log(this.bot.isMobile, 'QUIZ', 'Trying to complete quiz')
await wait(2000)
try {
// Check if the quiz has been started or not
const quizNotStarted = await page.waitForSelector('#rqStartQuiz', { state: 'visible', timeout: 2000 }).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')
}
let quizData = await getQuizData(page)
const questionsRemaining = quizData.maxQuestions - quizData.CorrectlyAnsweredQuestionCount // Amount of questions remaining
await this.bot.utils.wait(2000)
// All questions
for (let question = 0; question < questionsRemaining; question++) {
let quizData = await this.bot.browser.func.getQuizData(page)
const questionsRemaining = quizData.maxQuestions - quizData.CorrectlyAnsweredQuestionCount // Amount of questions remaining
if (quizData.numberOfOptions === 8) {
const answers: string[] = []
// All questions
for (let question = 0; question < questionsRemaining; question++) {
for (let i = 0; i < quizData.numberOfOptions; i++) {
const answerSelector = await page.waitForSelector(`#rqAnswerOption${i}`, { visible: true, timeout: 5000 })
const answerAttribute = await answerSelector?.evaluate(el => el.getAttribute('iscorrectoption'))
if (quizData.numberOfOptions === 8) {
const answers: string[] = []
if (answerAttribute && answerAttribute.toLowerCase() === 'true') {
answers.push(`#rqAnswerOption${i}`)
for (let i = 0; i < quizData.numberOfOptions; i++) {
const answerSelector = await page.waitForSelector(`#rqAnswerOption${i}`, { state: 'visible', timeout: 10000 })
const answerAttribute = await answerSelector?.evaluate((el: any) => el.getAttribute('iscorrectoption'))
if (answerAttribute && answerAttribute.toLowerCase() === 'true') {
answers.push(`#rqAnswerOption${i}`)
}
}
}
// Click the answers
for (const answer of answers) {
await page.waitForSelector(answer, { visible: true, timeout: 2000 })
// Click the answers
for (const answer of answers) {
await page.waitForSelector(answer, { state: 'visible', timeout: 2000 })
// Click the answer on page
await page.click(answer)
const refreshSuccess = await waitForQuizRefresh(page)
if (!refreshSuccess) {
await page.close()
log('QUIZ', 'An error occurred, refresh was unsuccessful', 'error')
return
}
}
// Other type quiz
} else if ([2, 3, 4].includes(quizData.numberOfOptions)) {
quizData = await getQuizData(page) // Refresh Quiz Data
const correctOption = quizData.correctAnswer
for (let i = 0; i < quizData.numberOfOptions; i++) {
const answerSelector = await page.waitForSelector(`#rqAnswerOption${i}`, { visible: true, timeout: 5000 })
const dataOption = await answerSelector?.evaluate(el => el.getAttribute('data-option'))
if (dataOption === correctOption) {
// Click the answer on page
await page.click(`#rqAnswerOption${i}`)
await page.click(answer)
const refreshSuccess = await waitForQuizRefresh(page)
const refreshSuccess = await this.bot.browser.func.waitForQuizRefresh(page)
if (!refreshSuccess) {
await page.close()
log('QUIZ', 'An error occurred, refresh was unsuccessful', 'error')
this.bot.log(this.bot.isMobile, 'QUIZ', 'An error occurred, refresh was unsuccessful', 'error')
return
}
}
}
await wait(2000)
// 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
for (let i = 0; i < quizData.numberOfOptions; i++) {
const answerSelector = await page.waitForSelector(`#rqAnswerOption${i}`, { state: 'visible', timeout: 10000 })
const dataOption = await answerSelector?.evaluate((el: any) => el.getAttribute('data-option'))
if (dataOption === correctOption) {
// Click the answer on page
await page.click(`#rqAnswerOption${i}`)
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
}
}
}
await this.bot.utils.wait(2000)
}
}
}
// Done with
await this.bot.utils.wait(2000)
await page.close()
// Done with
await wait(2000)
await page.close()
log('QUIZ', 'Completed the quiz successfully')
} catch (error) {
await page.close()
log('QUIZ', 'An error occurred:' + error, 'error')
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,73 @@
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'
},
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

@@ -1,331 +1,400 @@
import { Page } from 'puppeteer'
import axios from 'axios'
import { Page } from 'rebrowser-playwright'
import { platform } from 'os'
import { getLatestTab } from '../../browser/BrowserUtil'
import { getSearchPoints } from '../../browser/BrowserFunc'
import { log } from '../../util/Logger'
import { randomNumber, shuffleArray, wait } from '../../util/Utils'
import { Workers } from '../Workers'
import { searchSettings } from '../../config.json'
import { DashboardData, DashboardImpression } from '../../interface/DashboardData'
import { GoogleTrends } from '../../interface/GoogleDailyTrends'
import { Counters, DashboardData } from '../../interface/DashboardData'
import { GoogleSearch } from '../../interface/Search'
import { AxiosRequestConfig } from 'axios'
export async function doSearch(page: Page, data: DashboardData, mobile: boolean) {
log('SEARCH-BING', 'Starting bing searches')
type GoogleTrendsResponse = [
string,
[
string,
...null[],
[string, ...string[]]
][]
];
const mobileData = data.userStatus.counters?.mobileSearch ? data.userStatus.counters.mobileSearch[0] : null // Mobile searches
const edgeData = data.userStatus.counters.pcSearch[1] as DashboardImpression // Edge searches
const genericData = data.userStatus.counters.pcSearch[0] as DashboardImpression // Normal searches
export class Search extends Workers {
private bingHome = 'https://bing.com'
private searchPageURL = ''
let missingPoints = (mobile && mobileData) ?
(mobileData.pointProgressMax - mobileData.pointProgress) :
(edgeData.pointProgressMax - edgeData.pointProgress) + (genericData.pointProgressMax - genericData.pointProgress)
public async doSearch(page: Page, data: DashboardData) {
this.bot.log(this.bot.isMobile, 'SEARCH-BING', 'Starting Bing searches')
if (missingPoints == 0) {
log('SEARCH-BING', `Bing searches for ${mobile ? 'MOBILE' : 'DESKTOP'} have already been completed`)
return
}
page = await this.bot.browser.utils.getLatestTab(page)
// Generate search queries
let googleSearchQueries = await getGoogleTrends(data.userProfile.attributes.country, missingPoints)
googleSearchQueries = shuffleArray(googleSearchQueries)
let searchCounters: Counters = await this.bot.browser.func.getSearchPoints()
let missingPoints = this.calculatePoints(searchCounters)
// Deduplicate the search terms
googleSearchQueries = [...new Set(googleSearchQueries)]
// Open a new tab
const browser = page.browser()
const searchPage = await browser.newPage()
// Go to bing
await searchPage.goto('https://bing.com')
let maxLoop = 0 // If the loop hits 10 this when not gaining any points, we're assuming it's stuck. If it ddoesn't continue after 5 more searches with alternative queries, abort search
const queries: string[] = []
googleSearchQueries.forEach(x => 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
log('SEARCH-BING', `${missingPoints} Points Remaining | Query: ${query} | Mobile: ${mobile}`)
const newData = await bingSearch(page, searchPage, query)
const newMobileData = newData.mobileSearch ? newData.mobileSearch[0] : null // Mobile searches
const newEdgeData = newData.pcSearch[1] as DashboardImpression // Edge searches
const newGenericData = newData.pcSearch[0] as DashboardImpression // Normal searches
const newMissingPoints = (mobile && newMobileData) ?
(newMobileData.pointProgressMax - newMobileData.pointProgress) :
(newEdgeData.pointProgressMax - newEdgeData.pointProgress) + (newGenericData.pointProgressMax - newGenericData.pointProgress)
// If the new point amount is the same as before
if (newMissingPoints == missingPoints) {
maxLoop++ // Add to max loop
} else { // There has been a change in points
maxLoop = 0 // Reset the loop
if (missingPoints === 0) {
this.bot.log(this.bot.isMobile, 'SEARCH-BING', 'Bing searches have already been completed')
return
}
missingPoints = newMissingPoints
// Generate search queries
let googleSearchQueries = await this.getGoogleTrends(this.bot.config.searchSettings.useGeoLocaleQueries ? data.userProfile.attributes.country : 'US')
googleSearchQueries = this.bot.utils.shuffleArray(googleSearchQueries)
if (missingPoints == 0) {
break
// Deduplicate the search terms
googleSearchQueries = [...new Set(googleSearchQueries)]
// 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 maxLoop = 0 // If the loop hits 10 this when not gaining any points, we're assuming it's stuck. If it doesn't continue after 5 more searches with alternative queries, abort search
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) {
maxLoop++ // Add to max loop
} else { // There has been a change in points
maxLoop = 0 // Reset the loop
}
missingPoints = newMissingPoints
if (missingPoints === 0) {
break
}
// Only for mobile searches
if (maxLoop > 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 (maxLoop > 10) {
this.bot.log(this.bot.isMobile, 'SEARCH-BING', 'Search didn\'t gain point for 10 iterations aborting searches', 'warn')
maxLoop = 0 // Reset to 0 so we can retry with related searches below
break
}
}
// If we didn't gain points for 10 iterations, assume it's stuck
if (maxLoop > 10) {
log('SEARCH-BING', 'Search didn\'t gain point for 10 iterations aborting searches', 'warn')
maxLoop = 0 // Reset to 0 so we can retry with related searches 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) {
log('SEARCH-BING', `Search completed but we're missing ${missingPoints} points, generating extra searches`)
// 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
while (missingPoints > 0) {
const query = googleSearchQueries[i++] as GoogleSearch
let i = 0
while (missingPoints > 0) {
const query = googleSearchQueries[i++] as GoogleSearch
// Get related search terms to the Google search queries
const relatedTerms = await getRelatedTerms(query?.topic)
if (relatedTerms.length > 3) {
// Search for the first 2 related terms
for (const term of relatedTerms.slice(1, 3)) {
log('SEARCH-BING-EXTRA', `${missingPoints} Points Remaining | Query: ${term} | Mobile: ${mobile}`)
const newData = await bingSearch(page, searchPage, query.topic)
// 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}`)
const newMobileData = newData.mobileSearch ? newData.mobileSearch[0] : null // Mobile searches
const newEdgeData = newData.pcSearch[1] as DashboardImpression // Edge searches
const newGenericData = newData.pcSearch[0] as DashboardImpression // Normal searches
searchCounters = await this.bingSearch(page, term)
const newMissingPoints = this.calculatePoints(searchCounters)
const newMissingPoints = (mobile && newMobileData) ?
(newMobileData.pointProgressMax - newMobileData.pointProgress) :
(newEdgeData.pointProgressMax - newEdgeData.pointProgress) + (newGenericData.pointProgressMax - newGenericData.pointProgress)
// If the new point amount is the same as before
if (newMissingPoints == missingPoints) {
maxLoop++ // Add to max loop
} else { // There has been a change in points
maxLoop = 0 // Reset the loop
}
// If the new point amount is the same as before
if (newMissingPoints == missingPoints) {
maxLoop++ // Add to max loop
} else { // There has been a change in points
maxLoop = 0 // Reset the loop
}
missingPoints = newMissingPoints
missingPoints = newMissingPoints
// If we satisfied the searches
if (missingPoints === 0) {
break
}
// 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 (maxLoop > 5) {
log('SEARCH-BING-EXTRA', 'Search didn\'t gain point for 5 iterations aborting searches', 'warn')
return
// Try 5 more times, then we tried a total of 15 times, fair to say it's stuck
if (maxLoop > 5) {
this.bot.log(this.bot.isMobile, 'SEARCH-BING-EXTRA', 'Search didn\'t gain point for 5 iterations aborting searches', 'warn')
return
}
}
}
}
}
this.bot.log(this.bot.isMobile, 'SEARCH-BING', 'Completed searches')
}
log('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'
await searchPage.waitForSelector(searchBar, { state: 'visible', timeout: 10000 })
await searchPage.click(searchBar) // Focus on the textarea
await this.bot.utils.wait(500)
await searchPage.keyboard.down(platformControlKey)
await searchPage.keyboard.press('A')
await searchPage.keyboard.press('Backspace')
await searchPage.keyboard.up(platformControlKey)
await searchPage.keyboard.type(query)
await searchPage.keyboard.press('Enter')
await this.bot.utils.wait(3000)
// Bing.com in Chrome opens a new tab when searching
const resultPage = 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
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))))
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}`)
async function bingSearch(page: Page, searchPage: Page, query: string) {
// Try a max of 5 times
for (let i = 0; i < 5; i++) {
try {
const searchBar = '#sb_form_q'
await searchPage.waitForSelector(searchBar, { visible: true, timeout: 10_000 })
await searchPage.click(searchBar) // Focus on the textarea
await wait(500)
await searchPage.keyboard.down('Control')
await searchPage.keyboard.press('A')
await searchPage.keyboard.press('Backspace')
await searchPage.keyboard.up('Control')
await searchPage.keyboard.type(query)
await searchPage.keyboard.press('Enter')
if (searchSettings.scrollRandomResults) {
await wait(2000)
await randomScroll(searchPage)
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]"]]]`
}
if (searchSettings.clickRandomResults) {
await wait(2000)
await clickRandomLink(searchPage)
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')
}
await wait(Math.floor(randomNumber(10_000, 20_000)))
const mappedTrendsData = trendsData.map(query => [query[0], query[9]!.slice(1)])
if (mappedTrendsData.length < 90) {
this.bot.log(this.bot.isMobile, 'SEARCH-GOOGLE-TRENDS', 'Insufficient search queries, falling back to US', 'warn')
return this.getGoogleTrends()
}
return await getSearchPoints(page)
for (const [topic, relatedQueries] of mappedTrendsData) {
queryTerms.push({
topic: topic as string,
related: relatedQueries as string[]
})
}
} catch (error) {
if (i === 5) {
log('SEARCH-BING', 'Failed after 5 retries... An error occurred:' + error, 'error')
break
}
log('SEARCH-BING', 'Search failed, An error occurred:' + error, 'error')
log('SEARCH-BING', `Retrying search, attempt ${i}/5`, 'warn')
await wait(4000)
this.bot.log(this.bot.isMobile, 'SEARCH-GOOGLE-TRENDS', 'An error occurred:' + error, 'error')
}
return queryTerms
}
log('SEARCH-BING', 'Search failed after 5 retries, ending', 'error')
return await getSearchPoints(page)
}
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
}
}
}
async function getGoogleTrends(geoLocale: string, queryCount: number): Promise<GoogleSearch[]> {
const queryTerms: GoogleSearch[] = []
let i = 0
geoLocale = (searchSettings.useGeoLocaleQueries && geoLocale.length === 2) ? geoLocale.toUpperCase() : 'US'
log('SEARCH-GOOGLE-TRENDS', `Generating search queries, can take a while! | GeoLocale: ${geoLocale}`)
while (queryCount > queryTerms.length) {
i += 1
const date = new Date()
date.setDate(date.getDate() - i)
const formattedDate = formatDate(date)
return null
}
private async getRelatedTerms(term: string): Promise<string[]> {
try {
const request = {
url: `https://trends.google.com/trends/api/dailytrends?geo=${geoLocale}&hl=en&ed=${formattedDate}&ns=15`,
url: `https://api.bing.com/osjson.aspx?query=${term}`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
const response = await axios(request)
const response = await this.bot.axios.request(request, this.bot.config.proxy.proxyBingTerms)
const data: GoogleTrends = JSON.parse((await response.data).slice(5))
return response.data[1] as string[]
} catch (error) {
this.bot.log(this.bot.isMobile, 'SEARCH-BING-RELATED', 'An error occurred:' + error, 'error')
}
for (const topic of data.default.trendingSearchesDays[0]?.trendingSearches ?? []) {
queryTerms.push({
topic: topic.title.query.toLowerCase(),
related: topic.relatedQueries.map(x => x.query.toLocaleLowerCase())
})
}
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) {
log('SEARCH-GOOGLE-TRENDS', 'An error occurred:' + error, 'error')
this.bot.log(this.bot.isMobile, 'SEARCH-RANDOM-SCROLL', 'An error occurred:' + error, 'error')
}
}
return queryTerms
}
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
async function getRelatedTerms(term: string): Promise<string[]> {
try {
const request = {
url: `https://api.bing.com/osjson.aspx?query=${term}`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
// Only used if the browser is not the edge browser (continue on Edge popup)
await this.closeContinuePopup(page)
const response = await axios(request)
// Stay for 10 seconds for page to load and "visit"
await this.bot.utils.wait(10000)
return response.data[1] as string[]
} catch (error) {
log('SEARCH-BING-RELTATED', 'An error occurred:' + error, 'error')
}
return []
}
// 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)
function formatDate(date: Date): string {
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}${month}${day}`
}
async function randomScroll(page: Page) {
try {
// Press the arrow down key to scroll
for (let i = 0; i < randomNumber(5, 100); i++) {
await page.keyboard.press('ArrowDown')
}
} catch (error) {
log('SEARCH-RANDOM-SCROLL', 'An error occurred:' + error, 'error')
}
}
async function clickRandomLink(page: Page) {
try {
const searchListingURL = new URL(page.url()) // Get searchPage info before clicking
await page.click('#b_results .b_algo h2').catch(() => { }) // Since we don't really care if it did it or not
// Wait for website to load
await wait(3000)
// Will get current tab if no new one is created
let lastTab = await getLatestTab(page)
// Wait for the body of the new page to be loaded
await lastTab.waitForSelector('body', { timeout: 10_000 }).catch(() => { })
// Check if the tab is closed or not
if (!lastTab.isClosed()) {
let lastTabURL = new URL(lastTab.url()) // Get new tab info
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 !== searchListingURL.href && i < 5) {
// If hostname is still bing, (Bing images/news etc)
if (lastTabURL.hostname == searchListingURL.hostname) {
await lastTab.goBack()
while (lastTabURL.href !== this.searchPageURL && i < 5) {
lastTab = await getLatestTab(page) // Get last opened tab
await this.closeTabs(lastTab)
// If "goBack" didn't return to search listing (due to redirects)
if (lastTabURL.hostname !== searchListingURL.hostname) {
await lastTab.goto(searchListingURL.href)
}
} else { // No longer on bing, likely opened a new tab, close this tab
lastTab = await getLatestTab(page) // Get last opened tab
lastTabURL = new URL(lastTab.url())
const tabs = await (page.browser()).pages() // Get all tabs open
// If the browser has more than 3 tabs open, it has opened a new one, we need to close this one.
if (tabs.length > 3) {
// Make sure the page is still open!
if (!lastTab.isClosed()) {
await lastTab.close()
}
} else if (lastTabURL.href !== searchListingURL.href) {
await lastTab.goBack()
lastTab = await getLatestTab(page) // Get last opened tab
lastTabURL = new URL(lastTab.url())
// If "goBack" didn't return to search listing (due to redirects)
if (lastTabURL.hostname !== searchListingURL.hostname) {
await lastTab.goto(searchListingURL.href)
}
}
}
// 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++
}
lastTab = await getLatestTab(page) // Finally update the lastTab var again
i++
} catch (error) {
this.bot.log(this.bot.isMobile, 'SEARCH-RANDOM-CLICK', 'An error occurred:' + error, 'error')
}
} catch (error) {
log('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,91 @@
import type { Page } from 'playwright'
import * as fs from 'fs'
import path from 'path'
import { Workers } from '../Workers'
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(5000)
await this.bot.browser.utils.tryDismissAllMessages(page)
const query = await this.getSearchQuery(activity.title)
const searchBar = '#sb_form_q'
await page.waitForSelector(searchBar, { state: 'visible', timeout: 10000 })
await this.safeClick(page, searchBar)
await this.bot.utils.wait(500)
await page.keyboard.type(query)
await page.keyboard.press('Enter')
await this.bot.utils.wait(3000)
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 safeClick(page: Page, selector: string) {
try {
await page.click(selector, { timeout: 5000 })
} catch (e: any) {
const msg = (e?.message || '')
if (/Timeout.*click/i.test(msg) || /intercepts pointer events/i.test(msg)) {
// Try to dismiss overlays then retry once
await this.bot.browser.utils.tryDismissAllMessages(page)
await this.bot.utils.wait(500)
await page.click(selector, { timeout: 5000 })
} else {
throw e
}
}
}
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/v1/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

@@ -1,34 +1,47 @@
import { Page } from 'puppeteer'
import { Page } from 'rebrowser-playwright'
import { wait } from '../../util/Utils'
import { log } from '../../util/Logger'
import { getQuizData } from '../../browser/BrowserFunc'
import { Workers } from '../Workers'
export async function doThisOrThat(page: Page) {
log('THIS-OR-THAT', 'Trying to complete ThisOrThat')
try {
await page.waitForNetworkIdle({ timeout: 5000 })
await wait(2000)
export class ThisOrThat extends Workers {
// Check if the quiz has been started or not
const quizNotStarted = await page.waitForSelector('#rqStartQuiz', { visible: true, timeout: 3000 }).then(() => true).catch(() => false)
if (quizNotStarted) {
await page.click('#rqStartQuiz')
} else {
log('THIS-OR-THAT', 'ThisOrThat has already been started, trying to finish it')
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: 2000 }).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(2000)
// 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')
}
await wait(2000)
// Solving
const quizData = await getQuizData(page)
quizData // correctAnswer property is always null?
log('THIS-OR-THAT', 'Completed the ThisOrthat successfully')
} catch (error) {
await page.close()
log('THIS-OR-THAT', 'An error occurred:' + error, 'error')
}
}

View File

@@ -1,21 +1,23 @@
import { Page } from 'puppeteer'
import { Page } from 'rebrowser-playwright'
import { wait } from '../../util/Utils'
import { log } from '../../util/Logger'
import { Workers } from '../Workers'
export async function doUrlReward(page: Page) {
log('URL-REWARD', 'Trying to complete UrlReward')
try {
// After waiting, close the page
await page.waitForNetworkIdle({ timeout: 10_000 })
await wait(2000)
await page.close()
export class UrlReward extends Workers {
log('URL-REWARD', 'Completed the UrlReward successfully')
} catch (error) {
await page.close()
log('URL-REWARD', 'An error occurred:' + error, 'error')
async doUrlReward(page: Page) {
this.bot.log(this.bot.isMobile, 'URL-REWARD', 'Trying to complete UrlReward')
try {
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')
}
}
}

289
src/functions/queries.json Normal file
View File

@@ -0,0 +1,289 @@
[
{
"title": "Houses near you",
"queries": [
"Houses near me"
]
},
{
"title": "Feeling symptoms?",
"queries": [
"Rash on forearm",
"Stuffy nose",
"Tickling cough"
]
},
{
"title": "Get your shopping done faster",
"queries": [
"Buy PS5",
"Buy Xbox",
"Chair deals"
]
},
{
"title": "Translate anything",
"queries": [
"Translate welcome home to Korean",
"Translate welcome home to Japanese",
"Translate goodbye to Japanese"
]
},
{
"title": "Search the lyrics of a song",
"queries": [
"Debarge rhythm of the night lyrics"
]
},
{
"title": "Let's watch that movie again!",
"queries": [
"Alien movie",
"Aliens movie",
"Alien 3 movie",
"Predator movie"
]
},
{
"title": "Plan a quick getaway",
"queries": [
"Flights Amsterdam to Tokyo",
"Flights New York to Tokyo"
]
},
{
"title": "Discover open job roles",
"queries": [
"jobs at Microsoft",
"Microsoft Job Openings",
"Jobs near me",
"jobs at Boeing worked"
]
},
{
"title": "You can track your package",
"queries": [
"USPS tracking"
]
},
{
"title": "Find somewhere new to explore",
"queries": [
"Directions to Berlin",
"Directions to Tokyo",
"Directions to New York"
]
},
{
"title": "Too tired to cook tonight?",
"queries": [
"KFC near me",
"Burger King near me",
"McDonalds near me"
]
},
{
"title": "Quickly convert your money",
"queries": [
"convert 250 USD to yen",
"convert 500 USD to yen"
]
},
{
"title": "Learn to cook a new recipe",
"queries": [
"How to cook ratatouille",
"How to cook lasagna"
]
},
{
"title": "Find places to stay!",
"queries": [
"Hotels Berlin Germany",
"Hotels Amsterdam Netherlands"
]
},
{
"title": "How's the economy?",
"queries": [
"sp 500"
]
},
{
"title": "Who won?",
"queries": [
"braves score"
]
},
{
"title": "Gaming time",
"queries": [
"Overwatch video game",
"Call of duty video game"
]
},
{
"title": "Expand your vocabulary",
"queries": [
"definition definition"
]
},
{
"title": "What time is it?",
"queries": [
"Japan time",
"New York time"
]
},
{
"title": "Maisons près de chez vous",
"queries": [
"Maisons près de chez moi"
]
},
{
"title": "Vous ressentez des symptômes ?",
"queries": [
"Éruption cutanée sur l'avant-bras",
"Nez bouché",
"Toux chatouilleuse"
]
},
{
"title": "Faites vos achats plus vite",
"queries": [
"Acheter une PS5",
"Acheter une Xbox",
"Offres sur les chaises"
]
},
{
"title": "Traduisez tout !",
"queries": [
"Traduction bienvenue à la maison en coréen",
"Traduction bienvenue à la maison en japonais",
"Traduction au revoir en japonais"
]
},
{
"title": "Rechercher paroles de chanson",
"queries": [
"Paroles de Debarge rhythm of the night"
]
},
{
"title": "Et si nous regardions ce film une nouvelle fois?",
"queries": [
"Alien film",
"Film Aliens",
"Film Alien 3",
"Film Predator"
]
},
{
"title": "Planifiez une petite escapade",
"queries": [
"Vols Amsterdam-Tokyo",
"Vols New York-Tokyo"
]
},
{
"title": "Consulter postes à pourvoir",
"queries": [
"emplois chez Microsoft",
"Offres d'emploi Microsoft",
"Emplois près de chez moi",
"emplois chez Boeing"
]
},
{
"title": "Vous pouvez suivre votre colis",
"queries": [
"Suivi Chronopost"
]
},
{
"title": "Trouver un endroit à découvrir",
"queries": [
"Itinéraire vers Berlin",
"Itinéraire vers Tokyo",
"Itinéraire vers New York"
]
},
{
"title": "Trop fatigué pour cuisiner ce soir ?",
"queries": [
"KFC près de chez moi",
"Burger King près de chez moi",
"McDonalds près de chez moi"
]
},
{
"title": "Convertissez rapidement votre argent",
"queries": [
"convertir 250 EUR en yen",
"convertir 500 EUR en yen"
]
},
{
"title": "Apprenez à cuisiner une nouvelle recette",
"queries": [
"Comment faire cuire la ratatouille",
"Comment faire cuire les lasagnes"
]
},
{
"title": "Trouvez des emplacements pour rester!",
"queries": [
"Hôtels Berlin Allemagne",
"Hôtels Amsterdam Pays-Bas"
]
},
{
"title": "Comment se porte l'économie ?",
"queries": [
"CAC 40"
]
},
{
"title": "Qui a gagné ?",
"queries": [
"score du Paris Saint-Germain"
]
},
{
"title": "Temps de jeu",
"queries": [
"Jeu vidéo Overwatch",
"Jeu vidéo Call of Duty"
]
},
{
"title": "Enrichissez votre vocabulaire",
"queries": [
"definition definition"
]
},
{
"title": "Quelle heure est-il ?",
"queries": [
"Heure du Japon",
"Heure de New York"
]
},
{
"title": "Vérifier la météo",
"queries": [
"Météo de Paris",
"Météo de la France"
]
},
{
"title": "Tenez-vous informé des sujets d'actualité",
"queries": [
"Augmentation Impots",
"Mort célébrité"
]
}
]

View File

@@ -1,221 +1,548 @@
import cluster from 'cluster'
// Use Page type from playwright for typings; at runtime rebrowser-playwright extends playwright
import type { Page } from 'playwright'
import Browser from './browser/Browser'
import { getDashboardData, getEarnablePoints, goHome } from './browser/BrowserFunc'
import BrowserFunc from './browser/BrowserFunc'
import BrowserUtil from './browser/BrowserUtil'
import { log } from './util/Logger'
import { loadAccounts } from './util/Account'
import { chunkArray } from './util/Utils'
import Util from './util/Utils'
import { loadAccounts, loadConfig, saveSessionData } from './util/Load'
import { login } from './functions/Login'
import { doDailySet, doMorePromotions, doPunchCard } from './functions/Workers'
import { doSearch } from './functions/activities/Search'
import { Login } from './functions/Login'
import { Workers } from './functions/Workers'
import Activities from './functions/Activities'
import { Account } from './interface/Account'
import Axios from './util/Axios'
import fs from 'fs'
import path from 'path'
import { runOnZeroPoints, workers, clusters } from './config.json'
// Main bot class
class MicrosoftRewardsBot {
private activeWorkers: number = clusters
private collectedPoints: number = 0
private browserFactory: Browser = new Browser()
private accounts: Account[]
export class MicrosoftRewardsBot {
public log: typeof log
public config
public utils: Util
public activities: Activities = new Activities(this)
public browser: {
func: BrowserFunc,
utils: BrowserUtil
}
public isMobile: boolean
public homePage!: Page
private pointsCanCollect: number = 0
private pointsInitial: number = 0
private activeWorkers: number
private mobileRetryAttempts: number
private browserFactory: Browser = new Browser(this)
private accounts: Account[]
private workers: Workers
private login = new Login(this)
private accessToken: string = ''
// Summary collection (per process)
private accountSummaries: AccountSummary[] = []
//@ts-expect-error Will be initialized later
public axios: Axios
constructor(isMobile: boolean) {
this.isMobile = isMobile
this.log = log
constructor() {
this.accounts = []
this.utils = new Util()
this.workers = new Workers(this)
this.browser = {
func: new BrowserFunc(this),
utils: new BrowserUtil(this)
}
this.config = loadConfig()
this.activeWorkers = this.config.clusters
this.mobileRetryAttempts = 0
}
async initialize() {
this.accounts = await loadAccounts()
this.accounts = loadAccounts()
}
async run() {
log('MAIN', `Bot started with ${clusters} clusters`)
this.printBanner()
log('main', 'MAIN', `Bot started with ${this.config.clusters} clusters`)
// Only cluster when there's more than 1 cluster demanded
if (clusters > 1) {
if (this.config.clusters > 1) {
if (cluster.isPrimary) {
this.runMaster()
} else {
this.runWorker()
}
} else {
this.runTasks(this.accounts)
await this.runTasks(this.accounts)
}
}
private runMaster() {
log('MAIN-PRIMARY', 'Primary process started')
private printBanner() {
// Only print once (primary process or single cluster execution)
if (this.config.clusters > 1 && !cluster.isPrimary) return
try {
const pkgPath = path.join(__dirname, '../', 'package.json')
let version = 'unknown'
if (fs.existsSync(pkgPath)) {
const raw = fs.readFileSync(pkgPath, 'utf-8')
const pkg = JSON.parse(raw)
version = pkg.version || version
}
const banner = [
' __ __ _____ _____ _ ',
' | \/ |/ ____| | __ \\ | | ',
' | \ / | (___ ______| |__) |_____ ____ _ _ __ __| |___ ',
' | |\/| |\\___ \\______| _ // _ \\ \\ /\\ / / _` | \'__/ _` / __|',
' | | | |____) | | | \\ \\ __/ \\ V V / (_| | | | (_| \\__ \\',
' |_| |_|_____/ |_| \\_\\___| \\_/\\_/ \\__,_|_| \\__,_|___/',
'',
` Version: v${version}`,
''
].join('\n')
console.log(banner)
} catch { /* ignore banner errors */ }
}
const accountChunks = chunkArray(this.accounts, clusters)
// Return summaries (used when clusters==1)
public getSummaries() {
return this.accountSummaries
}
private runMaster() {
log('main', 'MAIN-PRIMARY', 'Primary process started')
const accountChunks = this.utils.chunkArray(this.accounts, this.config.clusters)
for (let i = 0; i < accountChunks.length; i++) {
const worker = cluster.fork()
const chunk = accountChunks[i]
worker.send({ chunk })
;(worker as any).send?.({ chunk })
// Collect summaries from workers
worker.on('message', (msg: any) => {
if (msg && msg.type === 'summary' && Array.isArray(msg.data)) {
this.accountSummaries.push(...msg.data)
}
})
}
cluster.on('exit', (worker, code) => {
cluster.on('exit', (worker: any, code: number) => {
this.activeWorkers -= 1
log('MAIN-WORKER', `Worker ${worker.process.pid} destroyed | Code: ${code} | Active workers: ${this.activeWorkers}`, 'warn')
log('main', 'MAIN-WORKER', `Worker ${worker.process.pid} destroyed | Code: ${code} | Active workers: ${this.activeWorkers}`, 'warn')
// Check if all workers have exited
if (this.activeWorkers === 0) {
log('MAIN-WORKER', 'All workers destroyed. Exiting main process!', 'warn')
process.exit(0)
// All workers done -> send conclusion (if enabled) then exit
this.sendConclusion(this.accountSummaries).finally(() => {
log('main', 'MAIN-WORKER', 'All workers destroyed. Exiting main process!', 'warn')
process.exit(0)
})
}
})
}
private runWorker() {
log('MAIN-WORKER', `Worker ${process.pid} spawned`)
log('main', 'MAIN-WORKER', `Worker ${process.pid} spawned`)
// Receive the chunk of accounts from the master
process.on('message', async ({ chunk }) => {
;(process as any).on('message', async ({ chunk }: { chunk: Account[] }) => {
await this.runTasks(chunk)
})
}
private async runTasks(accounts: Account[]) {
for (const account of accounts) {
log('MAIN-WORKER', `Started tasks for account ${account.email}`)
log('main', 'MAIN-WORKER', `Started tasks for account ${account.email}`)
// Desktop Searches, DailySet and More Promotions
await this.Desktop(account)
const accountStart = Date.now()
let desktopInitial = 0
let mobileInitial = 0
let desktopCollected = 0
let mobileCollected = 0
const errors: string[] = []
// If runOnZeroPoints is false and 0 points to earn, stop and try the next account
if (!runOnZeroPoints && this.collectedPoints === 0) {
continue
this.axios = new Axios(account.proxy)
const verbose = process.env.DEBUG_REWARDS_VERBOSE === '1'
const formatFullErr = (label: string, e: any) => {
const base = shortErr(e)
if (verbose && e instanceof Error) {
return `${label}:${base} :: ${e.stack?.split('\n').slice(0,4).join(' | ')}`
}
return `${label}:${base}`
}
// Mobile Searches
await this.Mobile(account)
if (this.config.parallel) {
const mobileInstance = new MicrosoftRewardsBot(true)
mobileInstance.axios = this.axios
// Run both and capture results with detailed logging
const desktopPromise = this.Desktop(account).catch(e => {
log(false, 'TASK', `Desktop flow failed early for ${account.email}: ${e instanceof Error ? e.message : e}`,'error')
errors.push(formatFullErr('desktop', e)); return null
})
const mobilePromise = mobileInstance.Mobile(account).catch(e => {
log(true, 'TASK', `Mobile flow failed early for ${account.email}: ${e instanceof Error ? e.message : e}`,'error')
errors.push(formatFullErr('mobile', e)); return null
})
const [desktopResult, mobileResult] = await Promise.all([desktopPromise, mobilePromise])
if (desktopResult) {
desktopInitial = desktopResult.initialPoints
desktopCollected = desktopResult.collectedPoints
}
if (mobileResult) {
mobileInitial = mobileResult.initialPoints
mobileCollected = mobileResult.collectedPoints
}
} else {
this.isMobile = false
const desktopResult = await this.Desktop(account).catch(e => {
log(false, 'TASK', `Desktop flow failed early for ${account.email}: ${e instanceof Error ? e.message : e}`,'error')
errors.push(formatFullErr('desktop', e)); return null
})
if (desktopResult) {
desktopInitial = desktopResult.initialPoints
desktopCollected = desktopResult.collectedPoints
}
log('MAIN-WORKER', `Completed tasks for account ${account.email}`)
this.isMobile = true
const mobileResult = await this.Mobile(account).catch(e => {
log(true, 'TASK', `Mobile flow failed early for ${account.email}: ${e instanceof Error ? e.message : e}`,'error')
errors.push(formatFullErr('mobile', e)); return null
})
if (mobileResult) {
mobileInitial = mobileResult.initialPoints
mobileCollected = mobileResult.collectedPoints
}
}
const accountEnd = Date.now()
const durationMs = accountEnd - accountStart
const totalCollected = desktopCollected + mobileCollected
const initialTotal = (desktopInitial || 0) + (mobileInitial || 0)
this.accountSummaries.push({
email: account.email,
durationMs,
desktopCollected,
mobileCollected,
totalCollected,
initialTotal,
endTotal: initialTotal + totalCollected,
errors
})
log('main', 'MAIN-WORKER', `Completed tasks for account ${account.email}`, 'log', 'green')
}
log('MAIN-PRIMARY', 'Completed tasks for ALL accounts')
log('MAIN-PRIMARY', 'All workers destroyed!')
process.exit(0)
log(this.isMobile, 'MAIN-PRIMARY', 'Completed tasks for ALL accounts', 'log', 'green')
// Extra diagnostic summary when verbose
if (process.env.DEBUG_REWARDS_VERBOSE === '1') {
for (const summary of this.accountSummaries) {
log('main','SUMMARY-DEBUG',`Account ${summary.email} collected D:${summary.desktopCollected} M:${summary.mobileCollected} TOTAL:${summary.totalCollected} ERRORS:${summary.errors.length ? summary.errors.join(';') : 'none'}`)
}
}
// If in worker mode (clusters>1) send summaries to primary
if (this.config.clusters > 1 && !cluster.isPrimary) {
if (process.send) {
process.send({ type: 'summary', data: this.accountSummaries })
}
} else {
// Single process mode -> build and send conclusion directly
await this.sendConclusion(this.accountSummaries)
}
process.exit()
}
// Desktop
async Desktop(account: Account) {
const browser = await this.browserFactory.createBrowser(account.email, account.proxy, false)
const page = await browser.newPage()
let pages = await browser.pages()
log(false,'FLOW','Desktop() invoked')
const browser = await this.browserFactory.createBrowser(account.proxy, account.email)
this.homePage = await browser.newPage()
// If for some reason the browser initializes with more than 2 pages, close these
while (pages.length > 2) {
await pages[0]?.close()
pages = await browser.pages()
}
log(this.isMobile, 'MAIN', 'Starting browser')
// Log into proxy
await page.authenticate({ username: account.proxy.username, password: account.proxy.password })
// Login into MS Rewards, then go to rewards homepage
await this.login.login(this.homePage, account.email, account.password)
log('MAIN', 'Starting DESKTOP browser')
await this.browser.func.goHome(this.homePage)
// Login into MS Rewards
await login(page, account.email, account.password)
const data = await this.browser.func.getDashboardData()
const wentHome = await goHome(page)
if (!wentHome) {
throw log('MAIN', 'Unable to get dashboard page', 'error')
}
this.pointsInitial = data.userStatus.availablePoints
const initial = this.pointsInitial
const data = await getDashboardData(page)
log('MAIN-POINTS', `Current point count: ${data.userStatus.availablePoints}`)
log(this.isMobile, 'MAIN-POINTS', `Current point count: ${this.pointsInitial}`)
const earnablePoints = await getEarnablePoints(data)
this.collectedPoints = earnablePoints
log('MAIN-POINTS', `You can earn ${earnablePoints} points today`)
const browserEnarablePoints = await this.browser.func.getBrowserEarnablePoints()
// Tally all the desktop points
this.pointsCanCollect = browserEnarablePoints.dailySetPoints +
browserEnarablePoints.desktopSearchPoints
+ browserEnarablePoints.morePromotionsPoints
log(this.isMobile, 'MAIN-POINTS', `You can earn ${this.pointsCanCollect} points today`)
// If runOnZeroPoints is false and 0 points to earn, don't continue
if (!runOnZeroPoints && this.collectedPoints === 0) {
log('MAIN', 'No points to earn and "runOnZeroPoints" is set to "false", stopping')
if (!this.config.runOnZeroPoints && this.pointsCanCollect === 0) {
log(this.isMobile, 'MAIN', 'No points to earn and "runOnZeroPoints" is set to "false", stopping!', 'log', 'yellow')
// Close desktop browser
return await browser.close()
await this.browser.func.closeBrowser(browser, account.email)
return
}
// Open a new tab to where the tasks are going to be completed
const workerPage = await browser.newPage()
// Go to homepage on worker page
await this.browser.func.goHome(workerPage)
// Complete daily set
if (workers.doDailySet) {
await doDailySet(page, data)
if (this.config.workers.doDailySet) {
await this.workers.doDailySet(workerPage, data)
}
// Complete more promotions
if (workers.doMorePromotions) {
await doMorePromotions(page, data)
if (this.config.workers.doMorePromotions) {
await this.workers.doMorePromotions(workerPage, data)
}
// Complete punch cards
if (workers.doPunchCards) {
await doPunchCard(page, data)
if (this.config.workers.doPunchCards) {
await this.workers.doPunchCard(workerPage, data)
}
// Do desktop searches
if (workers.doDesktopSearch) {
await doSearch(page, data, false)
if (this.config.workers.doDesktopSearch) {
await this.activities.doSearch(workerPage, data)
}
// Save cookies
await saveSessionData(this.config.sessionPath, browser, account.email, this.isMobile)
// Fetch points BEFORE closing (avoid page closed reload error)
const after = await this.browser.func.getCurrentPoints().catch(()=>initial)
// Close desktop browser
await browser.close()
await this.browser.func.closeBrowser(browser, account.email)
return {
initialPoints: initial,
collectedPoints: (after - initial) || 0
}
}
// Mobile
async Mobile(account: Account) {
const browser = await this.browserFactory.createBrowser(account.email, account.proxy, true)
const page = await browser.newPage()
let pages = await browser.pages()
log(true,'FLOW','Mobile() invoked')
const browser = await this.browserFactory.createBrowser(account.proxy, account.email)
this.homePage = await browser.newPage()
// If for some reason the browser initializes with more than 2 pages, close these
while (pages.length > 2) {
await pages[0]?.close()
pages = await browser.pages()
}
// Log into proxy
await page.authenticate({ username: account.proxy.username, password: account.proxy.password })
log(this.isMobile, 'MAIN', 'Starting browser')
log('MAIN', 'Starting MOBILE browser')
// Login into MS Rewards, then go to rewards homepage
await this.login.login(this.homePage, account.email, account.password)
this.accessToken = await this.login.getMobileAccessToken(this.homePage, account.email)
// Login into MS Rewards
await login(page, account.email, account.password)
await this.browser.func.goHome(this.homePage)
await goHome(page)
const data = await this.browser.func.getDashboardData()
const initialPoints = data.userStatus.availablePoints || this.pointsInitial || 0
const data = await getDashboardData(page)
const browserEnarablePoints = await this.browser.func.getBrowserEarnablePoints()
const appEarnablePoints = await this.browser.func.getAppEarnablePoints(this.accessToken)
// If no mobile searches data found, stop (Does not exist on new accounts)
if (!data.userStatus.counters.mobileSearch) {
log('MAIN', 'No mobile searches found, stopping')
this.pointsCanCollect = browserEnarablePoints.mobileSearchPoints + appEarnablePoints.totalEarnablePoints
log(this.isMobile, 'MAIN-POINTS', `You can earn ${this.pointsCanCollect} points today (Browser: ${browserEnarablePoints.mobileSearchPoints} points, App: ${appEarnablePoints.totalEarnablePoints} points)`)
// If runOnZeroPoints is false and 0 points to earn, don't continue
if (!this.config.runOnZeroPoints && this.pointsCanCollect === 0) {
log(this.isMobile, 'MAIN', 'No points to earn and "runOnZeroPoints" is set to "false", stopping!', 'log', 'yellow')
// Close mobile browser
return await browser.close()
await this.browser.func.closeBrowser(browser, account.email)
return {
initialPoints: initialPoints,
collectedPoints: 0
}
}
// Do daily check in
if (this.config.workers.doDailyCheckIn) {
await this.activities.doDailyCheckIn(this.accessToken, data)
}
// Do read to earn
if (this.config.workers.doReadToEarn) {
await this.activities.doReadToEarn(this.accessToken, data)
}
// Do mobile searches
if (workers.doMobileSearch) {
await doSearch(page, data, true)
if (this.config.workers.doMobileSearch) {
// If no mobile searches data found, stop (Does not always exist on new accounts)
if (data.userStatus.counters.mobileSearch) {
// Open a new tab to where the tasks are going to be completed
const workerPage = await browser.newPage()
// Go to homepage on worker page
await this.browser.func.goHome(workerPage)
await this.activities.doSearch(workerPage, data)
// Fetch current search points
const mobileSearchPoints = (await this.browser.func.getSearchPoints()).mobileSearch?.[0]
if (mobileSearchPoints && (mobileSearchPoints.pointProgressMax - mobileSearchPoints.pointProgress) > 0) {
// Increment retry count
this.mobileRetryAttempts++
}
// Exit if retries are exhausted
if (this.mobileRetryAttempts > this.config.searchSettings.retryMobileSearchAmount) {
log(this.isMobile, 'MAIN', `Max retry limit of ${this.config.searchSettings.retryMobileSearchAmount} reached. Exiting retry loop`, 'warn')
} else if (this.mobileRetryAttempts !== 0) {
log(this.isMobile, 'MAIN', `Attempt ${this.mobileRetryAttempts}/${this.config.searchSettings.retryMobileSearchAmount}: Unable to complete mobile searches, bad User-Agent? Increase search delay? Retrying...`, 'log', 'yellow')
// Close mobile browser
await this.browser.func.closeBrowser(browser, account.email)
// Create a new browser and try
await this.Mobile(account)
return
}
} else {
log(this.isMobile, 'MAIN', 'Unable to fetch search points, your account is most likely too "new" for this! Try again later!', 'warn')
}
}
// Fetch new points
const earnablePoints = await getEarnablePoints(data, page)
const afterPointAmount = await this.browser.func.getCurrentPoints()
// If the new earnable is 0, means we got all the points, else retract
this.collectedPoints = earnablePoints === 0 ? this.collectedPoints : (this.collectedPoints - earnablePoints)
log('MAIN-POINTS', `The script collected ${this.collectedPoints} points today`)
log(this.isMobile, 'MAIN-POINTS', `The script collected ${afterPointAmount - initialPoints} points today`)
// Close mobile browser
await browser.close()
await this.browser.func.closeBrowser(browser, account.email)
return {
initialPoints: initialPoints,
collectedPoints: (afterPointAmount - initialPoints) || 0
}
}
private async sendConclusion(summaries: AccountSummary[]) {
const { ConclusionWebhook } = await import('./util/ConclusionWebhook')
const cfg = this.config
if (!cfg.conclusionWebhook || !cfg.conclusionWebhook.enabled) return
const totalAccounts = summaries.length
if (totalAccounts === 0) return
let totalCollected = 0
let totalInitial = 0
let totalEnd = 0
let totalDuration = 0
let accountsWithErrors = 0
const accountFields: any[] = []
for (const s of summaries) {
totalCollected += s.totalCollected
totalInitial += s.initialTotal
totalEnd += s.endTotal
totalDuration += s.durationMs
if (s.errors.length) accountsWithErrors++
const statusEmoji = s.errors.length ? '⚠️' : '✅'
const diff = s.totalCollected
const duration = formatDuration(s.durationMs)
const valueLines: string[] = [
`Points: ${s.initialTotal}${s.endTotal} ( +${diff} )`,
`Breakdown: 🖥️ ${s.desktopCollected} | 📱 ${s.mobileCollected}`,
`Duration: ⏱️ ${duration}`
]
if (s.errors.length) {
valueLines.push(`Errors: ${s.errors.slice(0,2).join(' | ')}`)
}
accountFields.push({
name: `${statusEmoji} ${s.email}`.substring(0, 256),
value: valueLines.join('\n').substring(0, 1024),
inline: false
})
}
const avgDuration = totalDuration / totalAccounts
const embed = {
title: '🎯 Microsoft Rewards Summary',
description: `Processed **${totalAccounts}** account(s)${accountsWithErrors ? `${accountsWithErrors} with issues` : ''}`,
color: accountsWithErrors ? 0xFFAA00 : 0x32CD32,
fields: [
{
name: 'Global Totals',
value: [
`Total Points: ${totalInitial}${totalEnd} ( +${totalCollected} )`,
`Average Duration: ${formatDuration(avgDuration)}`,
`Cumulative Runtime: ${formatDuration(totalDuration)}`
].join('\n')
},
...accountFields
].slice(0, 25), // Discord max 25 fields
timestamp: new Date().toISOString(),
footer: {
text: 'Script conclusion webhook'
}
}
// Fallback plain text (rare) & embed send
const fallback = `Microsoft Rewards Summary\nAccounts: ${totalAccounts}\nTotal: ${totalInitial} -> ${totalEnd} (+${totalCollected})\nRuntime: ${formatDuration(totalDuration)}`
await ConclusionWebhook(cfg, fallback, { embeds: [embed] })
}
}
const bot = new MicrosoftRewardsBot()
interface AccountSummary {
email: string
durationMs: number
desktopCollected: number
mobileCollected: number
totalCollected: number
initialTotal: number
endTotal: number
errors: string[]
}
// Initialize accounts first and then start the bot
bot.initialize().then(() => {
bot.run()
function shortErr(e: any): string {
if (!e) return 'unknown'
if (e instanceof Error) return e.message.substring(0, 120)
const s = String(e)
return s.substring(0, 120)
}
function formatDuration(ms: number): string {
if (!ms || ms < 1000) return `${ms}ms`
const sec = Math.floor(ms / 1000)
const h = Math.floor(sec / 3600)
const m = Math.floor((sec % 3600) / 60)
const s = sec % 60
const parts: string[] = []
if (h) parts.push(`${h}h`)
if (m) parts.push(`${m}m`)
if (s) parts.push(`${s}s`)
return parts.join(' ') || `${ms}ms`
}
async function main() {
const rewardsBot = new MicrosoftRewardsBot(false)
try {
await rewardsBot.initialize()
await rewardsBot.run()
} catch (error) {
log(false, 'MAIN-ERROR', `Error running desktop bot: ${error}`, 'error')
}
}
// Start the bots
main().catch(error => {
log('main', 'MAIN-ERROR', `Error running bots: ${error}`, 'error')
process.exit(1)
})

View File

@@ -5,6 +5,7 @@ export interface Account {
}
export interface AccountProxy {
proxyAxios: boolean;
url: string;
port: number;
password: string;

View File

@@ -0,0 +1,226 @@
export interface AppUserData {
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;
}
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;
}
export interface GiveOrganization {
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;
}
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;
}
export interface GoalItemConfig {
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[];
}
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;
}
export interface ItemSnapshot {
name: string;
provider: string;
price: number;
attributes: GoalItemAttributes;
config: ItemSnapshotConfig;
}
export interface ItemSnapshotConfig {
amount: string;
countryCode: string;
currencyCode: string;
sku: string;
}
export interface Log {
time: Date;
from: From;
to: S;
reason: string;
}
export enum From {
Created = 'Created',
RiskApproved = 'RiskApproved',
RiskReview = 'RiskReview'
}
export enum S {
Cancelled = 'Cancelled',
RiskApproved = 'RiskApproved',
RiskReview = 'RiskReview',
Shipped = 'Shipped'
}
export interface Profile {
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;
}
export interface OfflineAttributes {
}
export interface Promotion {
name: string;
priority: number;
attributes: { [key: string]: string };
tags: Tag[];
}
export enum Tag {
AllowTrialUser = 'allow_trial_user',
ExcludeGivePcparent = 'exclude_give_pcparent',
ExcludeGlobalConfig = 'exclude_global_config',
ExcludeHidden = 'exclude_hidden',
LOCString = 'locString',
NonGlobalConfig = 'non_global_config'
}

56
src/interface/Config.ts Normal file
View File

@@ -0,0 +1,56 @@
export interface Config {
baseURL: string;
sessionPath: string;
headless: boolean;
parallel: boolean;
runOnZeroPoints: boolean;
clusters: number;
saveFingerprint: ConfigSaveFingerprint;
workers: ConfigWorkers;
searchOnBingLocalQueries: boolean;
globalTimeout: number | string;
searchSettings: ConfigSearchSettings;
logExcludeFunc: string[];
webhookLogExcludeFunc: string[];
proxy: ConfigProxy;
webhook: ConfigWebhook;
conclusionWebhook?: ConfigWebhook; // Optional secondary webhook for final summary
}
export interface ConfigSaveFingerprint {
mobile: boolean;
desktop: boolean;
}
export interface ConfigSearchSettings {
useGeoLocaleQueries: boolean;
scrollRandomResults: boolean;
clickRandomResults: boolean;
searchDelay: ConfigSearchDelay;
retryMobileSearchAmount: number;
}
export interface ConfigSearchDelay {
min: number | string;
max: number | string;
}
export interface ConfigWebhook {
enabled: boolean;
url: string;
}
export interface ConfigProxy {
proxyGoogleTrends: boolean;
proxyBingTerms: boolean;
}
export interface ConfigWorkers {
doDailySet: boolean;
doMorePromotions: boolean;
doPunchCards: boolean;
doDesktopSearch: boolean;
doMobileSearch: boolean;
doDailyCheckIn: boolean;
doReadToEarn: boolean;
}

View File

@@ -351,11 +351,13 @@ export interface MorePromotion {
legalText: string;
legalLinkText: string;
deviceType: string;
exclusiveLockedFeatureType: string;
exclusiveLockedFeatureStatus: string;
}
export interface PunchCard {
name: string;
parentPromotion: PromotionalItem;
parentPromotion?: PromotionalItem;
childPromotions: PromotionalItem[];
}

9
src/interface/OAuth.ts Normal file
View File

@@ -0,0 +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;
}

7
src/interface/Points.ts Normal file
View File

@@ -0,0 +1,7 @@
export interface EarnablePoints {
desktopSearchPoints: number
mobileSearchPoints: number
dailySetPoints: number
morePromotionsPoints: number
totalEarnablePoints: number
}

156
src/run_daily.sh Executable file
View File

@@ -0,0 +1,156 @@
#!/usr/bin/env bash
set -euo pipefail
export PATH="/usr/local/bin:/usr/bin:/bin"
export PLAYWRIGHT_BROWSERS_PATH=0
export TZ="${TZ:-UTC}"
cd /usr/src/microsoft-rewards-script
LOCKFILE=/tmp/run_daily.lock
# -------------------------------
# Function: Check and fix lockfile integrity
# -------------------------------
self_heal_lockfile() {
# If lockfile exists but is empty → remove it
if [ -f "$LOCKFILE" ]; then
local lock_content
lock_content=$(<"$LOCKFILE" || echo "")
if [[ -z "$lock_content" ]]; then
echo "[$(date)] [run_daily.sh] Found empty lockfile → removing."
rm -f "$LOCKFILE"
return
fi
# If lockfile contains non-numeric PID → remove it
if ! [[ "$lock_content" =~ ^[0-9]+$ ]]; then
echo "[$(date)] [run_daily.sh] Found corrupted lockfile content ('$lock_content') → removing."
rm -f "$LOCKFILE"
return
fi
# If lockfile contains PID but process is dead → remove it
if ! kill -0 "$lock_content" 2>/dev/null; then
echo "[$(date)] [run_daily.sh] Lockfile PID $lock_content is dead → removing stale lock."
rm -f "$LOCKFILE"
return
fi
fi
}
# -------------------------------
# Function: Acquire lock
# -------------------------------
acquire_lock() {
local max_attempts=5
local attempt=0
local timeout_hours=${STUCK_PROCESS_TIMEOUT_HOURS:-8}
local timeout_seconds=$((timeout_hours * 3600))
while [ $attempt -lt $max_attempts ]; do
# Try to create lock with current PID
if (set -C; echo "$$" > "$LOCKFILE") 2>/dev/null; then
echo "[$(date)] [run_daily.sh] Lock acquired successfully (PID: $$)"
return 0
fi
# Lock exists, validate it
if [ -f "$LOCKFILE" ]; then
local existing_pid
existing_pid=$(<"$LOCKFILE" || echo "")
echo "[$(date)] [run_daily.sh] Lock file exists with PID: '$existing_pid'"
# If lockfile content is invalid → delete and retry
if [[ -z "$existing_pid" || ! "$existing_pid" =~ ^[0-9]+$ ]]; then
echo "[$(date)] [run_daily.sh] Removing invalid lockfile → retrying..."
rm -f "$LOCKFILE"
continue
fi
# If process is dead → delete and retry
if ! kill -0 "$existing_pid" 2>/dev/null; then
echo "[$(date)] [run_daily.sh] Removing stale lock (dead PID: $existing_pid)"
rm -f "$LOCKFILE"
continue
fi
# Check process runtime → kill if exceeded timeout
local process_age
if process_age=$(ps -o etimes= -p "$existing_pid" 2>/dev/null | tr -d ' '); then
if [ "$process_age" -gt "$timeout_seconds" ]; then
echo "[$(date)] [run_daily.sh] Killing stuck process $existing_pid (${process_age}s > ${timeout_hours}h)"
kill -TERM "$existing_pid" 2>/dev/null || true
sleep 5
kill -KILL "$existing_pid" 2>/dev/null || true
rm -f "$LOCKFILE"
continue
fi
fi
fi
echo "[$(date)] [run_daily.sh] Lock held by PID $existing_pid, attempt $((attempt + 1))/$max_attempts"
sleep 2
((attempt++))
done
echo "[$(date)] [run_daily.sh] Could not acquire lock after $max_attempts attempts; exiting."
return 1
}
# -------------------------------
# Function: Release lock
# -------------------------------
release_lock() {
if [ -f "$LOCKFILE" ]; then
local lock_pid
lock_pid=$(<"$LOCKFILE")
if [ "$lock_pid" = "$$" ]; then
rm -f "$LOCKFILE"
echo "[$(date)] [run_daily.sh] Lock released (PID: $$)"
fi
fi
}
# Always release lock on exit — but only if we acquired it
trap 'release_lock' EXIT INT TERM
# -------------------------------
# MAIN EXECUTION FLOW
# -------------------------------
echo "[$(date)] [run_daily.sh] Current process PID: $$"
# Self-heal any broken or empty locks before proceeding
self_heal_lockfile
# Attempt to acquire the lock safely
if ! acquire_lock; then
exit 0
fi
# Random sleep between MIN and MAX to spread execution
MINWAIT=${MIN_SLEEP_MINUTES:-5}
MAXWAIT=${MAX_SLEEP_MINUTES:-50}
MINWAIT_SEC=$((MINWAIT*60))
MAXWAIT_SEC=$((MAXWAIT*60))
if [ "${SKIP_RANDOM_SLEEP:-false}" != "true" ]; then
SLEEPTIME=$(( MINWAIT_SEC + RANDOM % (MAXWAIT_SEC - MINWAIT_SEC) ))
echo "[$(date)] [run_daily.sh] Sleeping for $((SLEEPTIME/60)) minutes ($SLEEPTIME seconds)"
sleep "$SLEEPTIME"
else
echo "[$(date)] [run_daily.sh] Skipping random sleep"
fi
# Start the actual script
echo "[$(date)] [run_daily.sh] Starting script..."
if npm start; then
echo "[$(date)] [run_daily.sh] Script completed successfully."
else
echo "[$(date)] [run_daily.sh] ERROR: Script failed!" >&2
fi
echo "[$(date)] [run_daily.sh] Script finished"
# Lock is released automatically via trap

View File

@@ -1,22 +0,0 @@
import * as fs from 'fs'
import path from 'path'
import { Account } from '../interface/Account'
export async function loadAccounts(): Promise<Account[]> {
try {
let file = 'accounts.json'
// If dev mode, use dev account(s)
if (process.argv.includes('-dev')) {
file = 'accounts.dev.json'
}
const accountDir = path.join(__dirname, '../', file)
const accounts = fs.readFileSync(accountDir, 'utf-8')
return JSON.parse(accounts)
} catch (error) {
throw new Error(error as string)
}
}

49
src/util/Axios.ts Normal file
View File

@@ -0,0 +1,49 @@
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { HttpProxyAgent } from 'http-proxy-agent'
import { HttpsProxyAgent } from 'https-proxy-agent'
import { SocksProxyAgent } from 'socks-proxy-agent'
import { AccountProxy } from '../interface/Account'
class AxiosClient {
private instance: AxiosInstance
private account: AccountProxy
constructor(account: AccountProxy) {
this.account = account
this.instance = axios.create()
// 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
}
}
private getAgentForProxy(proxyConfig: AccountProxy): HttpProxyAgent<string> | HttpsProxyAgent<string> | SocksProxyAgent {
const { url, port } = proxyConfig
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'):
return new SocksProxyAgent(`${url}:${port}`)
default:
throw new Error(`Unsupported proxy protocol: ${url}`)
}
}
// Generic method to make any Axios request
public async request(config: AxiosRequestConfig, bypassProxy = false): Promise<AxiosResponse> {
if (bypassProxy) {
const bypassInstance = axios.create()
return bypassInstance.request(config)
}
return this.instance.request(config)
}
}
export default AxiosClient

View File

@@ -0,0 +1,32 @@
import axios from 'axios'
import { Config } from '../interface/Config'
interface ConclusionPayload {
content?: string
embeds?: any[]
}
/**
* Send a final structured summary to the dedicated conclusion webhook (if enabled),
* otherwise do nothing. Does NOT fallback to the normal logging webhook to avoid spam.
*/
export async function ConclusionWebhook(configData: Config, content: string, embed?: ConclusionPayload) {
const webhook = configData.conclusionWebhook
if (!webhook || !webhook.enabled || webhook.url.length < 10) return
const body: ConclusionPayload = embed?.embeds ? { embeds: embed.embeds } : { content }
if (content && !body.content && !body.embeds) body.content = content
const request = {
method: 'POST',
url: webhook.url,
headers: {
'Content-Type': 'application/json'
},
data: body
}
await axios(request).catch(() => { })
}

116
src/util/Load.ts Normal file
View File

@@ -0,0 +1,116 @@
import { BrowserContext, Cookie } from 'rebrowser-playwright'
import { BrowserFingerprintWithHeaders } from 'fingerprint-generator'
import fs from 'fs'
import path from 'path'
import { Account } from '../interface/Account'
import { Config, ConfigSaveFingerprint } from '../interface/Config'
let configCache: Config
export function loadAccounts(): Account[] {
try {
let file = 'accounts.json'
// If dev mode, use dev account(s)
if (process.argv.includes('-dev')) {
file = 'accounts.dev.json'
}
const accountDir = path.join(__dirname, '../', file)
const accounts = fs.readFileSync(accountDir, 'utf-8')
return JSON.parse(accounts)
} catch (error) {
throw new Error(error as string)
}
}
export function loadConfig(): Config {
try {
if (configCache) {
return configCache
}
const configDir = path.join(__dirname, '../', 'config.json')
const config = fs.readFileSync(configDir, 'utf-8')
const configData = JSON.parse(config)
configCache = configData // Set as cache
return configData
} catch (error) {
throw new Error(error as string)
}
}
export async function loadSessionData(sessionPath: string, email: string, isMobile: boolean, saveFingerprint: ConfigSaveFingerprint) {
try {
// Fetch cookie file
const cookieFile = path.join(__dirname, '../browser/', sessionPath, email, `${isMobile ? 'mobile_cookies' : 'desktop_cookies'}.json`)
let cookies: Cookie[] = []
if (fs.existsSync(cookieFile)) {
const cookiesData = await fs.promises.readFile(cookieFile, 'utf-8')
cookies = JSON.parse(cookiesData)
}
// Fetch fingerprint file
const fingerprintFile = path.join(__dirname, '../browser/', sessionPath, email, `${isMobile ? 'mobile_fingerpint' : 'desktop_fingerpint'}.json`)
let fingerprint!: BrowserFingerprintWithHeaders
if (((saveFingerprint.desktop && !isMobile) || (saveFingerprint.mobile && isMobile)) && fs.existsSync(fingerprintFile)) {
const fingerprintData = await fs.promises.readFile(fingerprintFile, '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, browser: BrowserContext, email: string, isMobile: boolean): Promise<string> {
try {
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 })
}
// 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) {
throw new Error(error as string)
}
}
export async function saveFingerprintData(sessionPath: string, email: string, isMobile: boolean, fingerpint: BrowserFingerprintWithHeaders): Promise<string> {
try {
// Fetch path
const sessionDir = path.join(__dirname, '../browser/', sessionPath, email)
// Create session dir
if (!fs.existsSync(sessionDir)) {
await fs.promises.mkdir(sessionDir, { recursive: true })
}
// Save fingerprint to a file
await fs.promises.writeFile(path.join(sessionDir, `${isMobile ? 'mobile_fingerpint' : 'desktop_fingerpint'}.json`), JSON.stringify(fingerpint))
return sessionDir
} catch (error) {
throw new Error(error as string)
}
}

View File

@@ -1,26 +1,45 @@
import chalk from 'chalk'
import { Webhook } from './Webhook'
import { loadConfig } from './Load'
export function log(title: string, message: string, type?: 'log' | 'warn' | 'error') {
const currentTime = new Date().toISOString()
let str = ''
export function log(isMobile: boolean | 'main', title: string, message: string, type: 'log' | 'warn' | 'error' = 'log', color?: keyof typeof chalk): void {
const configData = loadConfig()
if (configData.logExcludeFunc.some(x => x.toLowerCase() === title.toLowerCase())) {
return
}
const currentTime = new Date().toLocaleString()
const platformText = isMobile === 'main' ? 'MAIN' : isMobile ? 'MOBILE' : 'DESKTOP'
const chalkedPlatform = isMobile === 'main' ? chalk.bgCyan('MAIN') : isMobile ? chalk.bgBlue('MOBILE') : chalk.bgMagenta('DESKTOP')
// Clean string for the Webhook (no chalk)
const cleanStr = `[${currentTime}] [PID: ${process.pid}] [${type.toUpperCase()}] ${platformText} [${title}] ${message}`
// Send the clean string to the Webhook
if (!configData.webhookLogExcludeFunc.some(x => x.toLowerCase() === title.toLowerCase())) {
Webhook(configData, cleanStr)
}
// Formatted string with chalk for terminal logging
const str = `[${currentTime}] [PID: ${process.pid}] [${type.toUpperCase()}] ${chalkedPlatform} [${title}] ${message}`
const applyChalk = color && typeof chalk[color] === 'function' ? chalk[color] as (msg: string) => string : null
// Log based on the type
switch (type) {
case 'warn':
str = `[${currentTime}] [PID: ${process.pid}] [WARN] [${title}] ${message}`
console.warn(str)
applyChalk ? console.warn(applyChalk(str)) : console.warn(str)
break
case 'error':
str = `[${currentTime}] [PID: ${process.pid}] [ERROR] [${title}] ${message}`
console.error(str)
applyChalk ? console.error(applyChalk(str)) : console.error(str)
break
default:
str = `[${currentTime}] [PID: ${process.pid}] [LOG] [${title}] ${message}`
console.log(str)
applyChalk ? console.log(applyChalk(str)) : console.log(str)
break
}
if (str) Webhook(str)
}
}

View File

@@ -1,42 +1,45 @@
import axios from 'axios'
import { BrowserFingerprintWithHeaders } from 'fingerprint-generator'
import { log } from './Logger'
import { ChromeVersion, EdgeVersion } from '../interface/UserAgentUtil'
export async function getUserAgent(mobile: boolean) {
const system = getSystemComponents(mobile)
const app = await getAppComponents(mobile)
const NOT_A_BRAND_VERSION = '99'
const uaTemplate = mobile ?
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 = `${mobile ? Math.floor(Math.random() * 5) + 9 : Math.floor(Math.random() * 15) + 1}.0.0`
const platformVersion = `${isMobile ? Math.floor(Math.random() * 5) + 9 : Math.floor(Math.random() * 15) + 1}.0.0`
const uaMetadata = {
mobile,
platform: mobile ? 'Android' : 'Windows',
isMobile,
platform: isMobile ? 'Android' : 'Windows',
fullVersionList: [
{ brand: 'Not/A)Brand', version: '99.0.0.0' },
{ 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: '99' },
{ 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: mobile ? '' : 'x86',
bitness: mobile ? '' : '64',
architecture: isMobile ? '' : 'x86',
bitness: isMobile ? '' : '64',
model: ''
}
return { userAgent: uaTemplate, userAgentMetadata: uaMetadata }
}
export async function getChromeVersion(): Promise<string> {
export async function getChromeVersion(isMobile: boolean): Promise<string> {
try {
const request = {
url: 'https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions.json',
@@ -51,11 +54,11 @@ export async function getChromeVersion(): Promise<string> {
return data.channels.Stable.version
} catch (error) {
throw log('USERAGENT-CHROME-VERSION', 'An error occurred:' + error, 'error')
throw log(isMobile, 'USERAGENT-CHROME-VERSION', 'An error occurred:' + error, 'error')
}
}
export async function getEdgeVersions() {
export async function getEdgeVersions(isMobile: boolean) {
try {
const request = {
url: 'https://edgeupdates.microsoft.com/api/products',
@@ -75,13 +78,13 @@ export async function getEdgeVersions() {
} catch (error) {
throw log('USERAGENT-EDGE-VERSION', 'An error occurred:' + error, 'error')
throw log(isMobile, 'USERAGENT-EDGE-VERSION', 'An error occurred:' + error, 'error')
}
}
export function getSystemComponents(mobile: boolean): string {
const osId: string = mobile ? 'Linux' : 'Windows NT 10.0'
const uaPlatform: string = mobile ? 'Android 13' : 'Win64; x64'
const uaPlatform: string = mobile ? `Android 1${Math.floor(Math.random() * 5)}` : 'Win64; x64'
if (mobile) {
return `${uaPlatform}; ${osId}; K`
@@ -90,20 +93,51 @@ export function getSystemComponents(mobile: boolean): string {
return `${uaPlatform}; ${osId}`
}
export async function getAppComponents(mobile: boolean) {
const versions = await getEdgeVersions()
const edgeVersion = mobile ? versions.android : versions.windows as string
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()
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
}
}
export async function updateFingerprintUserAgent(fingerprint: BrowserFingerprintWithHeaders, isMobile: boolean): Promise<BrowserFingerprintWithHeaders> {
try {
const userAgentData = await getUserAgent(isMobile)
const componentData = await 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) {
throw log(isMobile, 'USER-AGENT-UPDATE', 'An error occurred:' + error, 'error')
}
}

View File

@@ -1,38 +1,50 @@
export async function wait(ms: number): Promise<void> {
return new Promise<void>((resolve) => {
setTimeout(resolve, ms)
})
}
import ms from 'ms'
export function getFormattedDate(ms = Date.now()): string {
const today = new Date(ms)
const month = String(today.getMonth() + 1).padStart(2, '0') // January is 0
const day = String(today.getDate()).padStart(2, '0')
const year = today.getFullYear()
export default class Util {
return `${month}/${day}/${year}`
}
export function shuffleArray<T>(array: T[]): T[] {
const shuffledArray = array.slice()
shuffledArray.sort(() => Math.random() - 0.5)
return shuffledArray
}
export function randomNumber(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min
}
export function chunkArray<T>(arr: T[], numChunks: number): T[][] {
const chunkSize = Math.ceil(arr.length / numChunks)
const chunks: T[][] = []
for (let i = 0; i < arr.length; i += chunkSize) {
const chunk = arr.slice(i, i + chunkSize)
chunks.push(chunk)
async wait(ms: number): Promise<void> {
return new Promise<void>((resolve) => {
setTimeout(resolve, ms)
})
}
getFormattedDate(ms = Date.now()): string {
const today = new Date(ms)
const month = String(today.getMonth() + 1).padStart(2, '0') // January is 0
const day = String(today.getDate()).padStart(2, '0')
const year = today.getFullYear()
return `${month}/${day}/${year}`
}
shuffleArray<T>(array: T[]): T[] {
return array.map(value => ({ value, sort: Math.random() }))
.sort((a, b) => a.sort - b.sort)
.map(({ value }) => value)
}
randomNumber(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min
}
chunkArray<T>(arr: T[], numChunks: number): T[][] {
const chunkSize = Math.ceil(arr.length / numChunks)
const chunks: T[][] = []
for (let i = 0; i < arr.length; i += chunkSize) {
const chunk = arr.slice(i, i + chunkSize)
chunks.push(chunk)
}
return chunks
}
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"')
}
return milisec
}
return chunks
}

View File

@@ -1,10 +1,13 @@
import axios from 'axios'
import { webhook } from '../config.json'
export async function Webhook(content: string) {
import { Config } from '../interface/Config'
export async function Webhook(configData: Config, content: string) {
const webhook = configData.webhook
if (!webhook.enabled || webhook.url.length < 10) return
const request = {
method: 'POST',
url: webhook.url,

View File

@@ -39,7 +39,10 @@
"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). */
"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.
// "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. */
@@ -64,7 +67,9 @@
},
"include": [
"src/**/*.ts",
"src/accounts.json"
"src/accounts.json",
"src/config.json",
"src/functions/queries.json"
],
"exclude": [
"node_modules"