mirror of
https://github.com/TheNetsky/Microsoft-Rewards-Script.git
synced 2026-01-11 10:56:17 +00:00
Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ee16f1fd10 | ||
|
|
0059192519 | ||
|
|
a36b7eaef5 | ||
|
|
59b9f25d2c | ||
|
|
e89b8c0c52 | ||
|
|
649cf28ad9 | ||
|
|
624f5a32e1 | ||
|
|
3b21f45fcc | ||
|
|
f857b3ad1a | ||
|
|
0b7088a7e6 | ||
|
|
64ffabcceb | ||
|
|
86f65b448d | ||
|
|
14492b27cb | ||
|
|
62d1a0a14b | ||
|
|
02160a07d9 | ||
|
|
b66114d4dd | ||
|
|
2e80266ad1 | ||
|
|
072e96dd53 | ||
|
|
eea4407454 | ||
|
|
ad2e0b8bb3 | ||
|
|
ad3b215dbc | ||
|
|
f51daf06d6 | ||
|
|
e7c27ac16e | ||
|
|
9f5601d44b |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,9 +1,9 @@
|
||||
sessions/
|
||||
dist/
|
||||
node_modules/
|
||||
package-lock.json
|
||||
accounts.json
|
||||
notes
|
||||
accounts.dev.json
|
||||
accounts.main.json
|
||||
.DS_Store
|
||||
.DS_Store
|
||||
.playwright-chromium-installed
|
||||
|
||||
136
Dockerfile
136
Dockerfile
@@ -1,47 +1,89 @@
|
||||
# Use an official Node.js runtime as a base image
|
||||
FROM node:18
|
||||
|
||||
# Set the working directory in the container
|
||||
WORKDIR /usr/src/microsoft-rewards-script
|
||||
|
||||
# Install necessary dependencies for Playwright and cron
|
||||
RUN apt-get update && apt-get install -y \
|
||||
jq \
|
||||
cron \
|
||||
gettext-base \
|
||||
xvfb \
|
||||
libgbm-dev \
|
||||
libnss3 \
|
||||
libasound2 \
|
||||
libxss1 \
|
||||
libatk-bridge2.0-0 \
|
||||
libgtk-3-0 \
|
||||
tzdata \
|
||||
wget \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Copy all files to the working directory
|
||||
COPY . .
|
||||
|
||||
# Install dependencies, set permissions, and build the script
|
||||
RUN npm install && \
|
||||
chmod -R 755 /usr/src/microsoft-rewards-script/node_modules && \
|
||||
npm run pre-build && \
|
||||
npm run build
|
||||
|
||||
# Copy cron file to cron directory
|
||||
COPY src/crontab.template /etc/cron.d/microsoft-rewards-cron.template
|
||||
|
||||
# Create the log file to be able to run tail
|
||||
RUN touch /var/log/cron.log
|
||||
|
||||
# Define the command to run your application with cron optionally
|
||||
CMD ["sh", "-c", "echo \"$TZ\" > /etc/timezone && \
|
||||
ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && \
|
||||
dpkg-reconfigure -f noninteractive tzdata && \
|
||||
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 && \
|
||||
cron -f & \
|
||||
([ \"$RUN_ON_START\" = \"true\" ] && npm start) && \
|
||||
tail -f /var/log/cron.log"]
|
||||
###############################################################################
|
||||
# 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
674
LICENSE
Normal 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>.
|
||||
384
README.md
384
README.md
@@ -1,119 +1,301 @@
|
||||
# Microsoft-Rewards-Script
|
||||
Automated Microsoft Rewards script, however this time using TypeScript, Cheerio and Playwright.
|
||||
[](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)
|
||||
|
||||
## Notes ##
|
||||
- If you end the script without closing the browser window first (only with headless as false), you'll be left with hanging chrome instances using resources. Use taskmanager to kill these or use the included `npm run kill-chrome-win` script. (Windows)
|
||||
- If you automate this script, set it to run at least 2 times a day to make sure it picked up all tasks, set `"runOnZeroPoints": false` so it doesn't run when no points are found.
|
||||
---
|
||||
|
||||
## Docker (Experimental) ##
|
||||
### **Before Starting**
|
||||
## Setup
|
||||
|
||||
- If you had previously built and run the script locally, **remove** the `/node_modules` and `/dist` folders from your `Microsoft-Rewards-Script` directory.
|
||||
- If you had used Docker with an older version of the script (e.g., 1.4), **remove** any persistently saved `config.json` and session folders. Old `accounts.json` files can be reused.
|
||||
**Requirements:** Node.js ≥ 20 and Git
|
||||
Works on Windows, Linux, macOS, and WSL.
|
||||
|
||||
### **Setup the Source Files**
|
||||
---
|
||||
|
||||
1. **Download the Source Code**
|
||||
### 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. **Update `accounts.json`**
|
||||
---
|
||||
|
||||
3. **Edit `config.json`,** ensuring the following values are set (other settings are up to your preference):
|
||||
### 2. Copy Configuration Files
|
||||
|
||||
```json
|
||||
"headless": true,
|
||||
"clusters": 1,
|
||||
**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
|
||||
```
|
||||
|
||||
### **Customize the `compose.yaml` File**
|
||||
2. Then start the script:
|
||||
```bash
|
||||
./run.sh
|
||||
```
|
||||
|
||||
A basic docker `compose.yaml` is provided. Follow these steps to configure and run the container:
|
||||
This will launch the script headlessly using `xvfb-run`.
|
||||
|
||||
1. **Set Your Timezone:** Adjust the `TZ` variable to ensure correct scheduling.
|
||||
2. **Configure Persistent Storage:**
|
||||
- Map `config.json` and `accounts.json` to retain settings and accounts.
|
||||
- (Optional) Use a persistent `sessions` folder to save login sessions.
|
||||
3. **Customize the Schedule:**
|
||||
- Modify `CRON_SCHEDULE` to set run times. Use [crontab.guru](https://crontab.guru) for help.
|
||||
- **Note:** The container adds 5–50 minutes of random variability to each scheduled start time.
|
||||
4. **(Optional) Run on Startup:**
|
||||
- Set `RUN_ON_START=true` to execute the script immediately when the container starts.
|
||||
5. **Start the Container:** Run `docker compose up -d` to build and launch.
|
||||
6. **Monitor Logs:** Use `docker logs microsoft-rewards-script` to view script execution and to retrieve 'passwordless' login codes.
|
||||
---
|
||||
|
||||
## Docker Setup
|
||||
|
||||
## Config ##
|
||||
| Setting | Description | Default |
|
||||
| :------------- |:-------------| :-----|
|
||||
| baseURL | MS Rewards page | `https://rewards.bing.com` |
|
||||
| sessionPath | Path to where you want sessions/fingerprints to be stored | `sessions` (In ./browser/sessions) |
|
||||
| headless | If the browser window should be visible be ran in the background | `false` (Browser is visible) |
|
||||
| parallel | If you want mobile and desktop tasks to run parallel or sequential| `true` |
|
||||
| runOnZeroPoints | Run the rest of the script if 0 points can be earned | `false` (Will not run on 0 points) |
|
||||
| clusters | Amount of instances ran on launch, 1 per account | `1` (Will run 1 account at the time) |
|
||||
| saveFingerprint.mobile | Re-use the same fingerprint each time | `false` (Will generate a new fingerprint each time) |
|
||||
| saveFingerprint.desktop | Re-use the same fingerprint each time | `false` (Will generate a new fingerprint each time) |
|
||||
| workers.doDailySet | Complete daily set items | `true` |
|
||||
| workers.doMorePromotions | Complete promotional items | `true` |
|
||||
| workers.doPunchCards | Complete punchcards | `true` |
|
||||
| workers.doDesktopSearch | Complete daily desktop searches | `true` |
|
||||
| workers.doMobileSearch | Complete daily mobile searches | `true` |
|
||||
| workers.doDailyCheckIn | Complete daily check-in activity | `true` |
|
||||
| workers.doReadToEarn | Complete read to earn activity | `true` |
|
||||
| searchOnBingLocalQueries | Complete the activity "search on Bing" using the `queries.json` or fetched from this repo | `false` (Will fetch from this repo) |
|
||||
| globalTimeout | The length before the action gets timeout | `30s` |
|
||||
| searchSettings.useGeoLocaleQueries | Generate search queries based on your geo-location | `false` (Uses EN-US generated queries) |
|
||||
| searchSettings.scrollRandomResults | Scroll randomly in search results | `true` |
|
||||
| searchSettings.clickRandomResults | Visit random website from search result| `true` |
|
||||
| searchSettings.searchDelay | Minimum and maximum time in milliseconds between search queries | `min: 3min` `max: 5min` |
|
||||
| searchSettings.retryMobileSearchAmount | Keep retrying mobile searches for specified amount | `2` |
|
||||
| logExcludeFunc | Functions to exclude out of the logs and webhooks | `SEARCH-CLOSE-TABS` |
|
||||
| webhookLogExcludeFunc | Functions to exclude out of the webhooks log | `SEARCH-CLOSE-TABS` |
|
||||
| proxy.proxyGoogleTrends | Enable or disable proxying the request via set proxy | `true` (will be proxied) |
|
||||
| proxy.proxyBingTerms | Enable or disable proxying the request via set proxy | `true` (will be proxied) |
|
||||
| webhook.enabled | Enable or disable your set webhook | `false` |
|
||||
| webhook.url | Your Discord webhook URL | `null` |
|
||||
### 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`.
|
||||
|
||||
## Features ##
|
||||
- [x] Multi-Account Support
|
||||
- [x] Session Storing
|
||||
- [x] 2FA Support
|
||||
- [x] Passwordless 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
|
||||
- [x] Solving This Or That Quiz (Random)
|
||||
- [x] Solving ABC Quiz
|
||||
- [x] Completing Daily Check In
|
||||
- [x] Completing Read To Earn
|
||||
- [x] Clustering Support
|
||||
- [x] Proxy Support
|
||||
- [x] Docker Support (experimental)
|
||||
- [x] Automatic scheduling (via Docker)
|
||||
---
|
||||
|
||||
## 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!
|
||||
### 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 5–50 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: 5–50 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.
|
||||
|
||||
43
compose.yaml
43
compose.yaml
@@ -3,13 +3,40 @@ services:
|
||||
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:
|
||||
### Replace "/path/to/" with the actual path to where you want to save the files on your local machine.
|
||||
- /path/to/accounts.json:/usr/src/microsoft-rewards-script/dist/accounts.json
|
||||
- /path/to/config.json:/usr/src/microsoft-rewards-script/dist/config.json
|
||||
- /path/to/sessions:/usr/src/microsoft-rewards-script/dist/browser/sessions # Optional, saves your login session
|
||||
- ./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:
|
||||
- NODE_ENV=production
|
||||
- CRON_SCHEDULE=0 7,15,20 * * * # Customize your schedule, use crontab.guru for formatting
|
||||
- RUN_ON_START=true # Runs the script on container startup
|
||||
- TZ=America/Toronto # Set your timezone for proper scheduling
|
||||
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
50
entrypoint.sh
Executable 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
61
flake.lock
generated
Normal 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
40
flake.nix
Normal 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
3126
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -27,6 +27,7 @@
|
||||
"author": "Netsky",
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.14.11",
|
||||
"@types/ms": "^0.7.34",
|
||||
"@typescript-eslint/eslint-plugin": "^7.17.0",
|
||||
"eslint": "^8.57.0",
|
||||
@@ -43,8 +44,8 @@
|
||||
"http-proxy-agent": "^7.0.2",
|
||||
"https-proxy-agent": "^7.0.6",
|
||||
"ms": "^2.1.3",
|
||||
"playwright": "1.47.2",
|
||||
"rebrowser-playwright": "1.47.2",
|
||||
"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
3
run.sh
Executable file
@@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
nix develop --command bash -c "xvfb-run npm run start"
|
||||
@@ -25,19 +25,40 @@ class Browser {
|
||||
}
|
||||
|
||||
async createBrowser(proxy: AccountProxy, email: string): Promise<BrowserContext> {
|
||||
const 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'
|
||||
]
|
||||
})
|
||||
// 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)
|
||||
|
||||
|
||||
@@ -92,9 +92,32 @@ export default class BrowserFunc {
|
||||
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)
|
||||
}
|
||||
|
||||
// Reload the page to get new data
|
||||
await this.bot.homePage.reload({ waitUntil: 'domcontentloaded' })
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
const scriptContent = await this.bot.homePage.evaluate(() => {
|
||||
const scripts = Array.from(document.querySelectorAll('script'))
|
||||
@@ -108,7 +131,7 @@ export default class BrowserFunc {
|
||||
}
|
||||
|
||||
// Extract the dashboard object from the script content
|
||||
const dashboardData = await this.bot.homePage.evaluate(scriptContent => {
|
||||
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)
|
||||
@@ -272,7 +295,7 @@ export default class BrowserFunc {
|
||||
const html = await page.content()
|
||||
const $ = load(html)
|
||||
|
||||
const scriptContent = $('script').filter((index, element) => {
|
||||
const scriptContent = $('script').filter((index: number, element: any) => {
|
||||
return $(element).text().includes('_w.rewardsQuizRenderInfo')
|
||||
}).text()
|
||||
|
||||
@@ -332,7 +355,7 @@ export default class BrowserFunc {
|
||||
const html = await page.content()
|
||||
const $ = load(html)
|
||||
|
||||
const element = $('.offer-cta').toArray().find(x => x.attribs.href?.includes(activity.offerId))
|
||||
const element = $('.offer-cta').toArray().find((x: any) => x.attribs.href?.includes(activity.offerId))
|
||||
if (element) {
|
||||
selector = `a[href*="${element.attribs.href}"]`
|
||||
}
|
||||
|
||||
@@ -13,7 +13,6 @@ export default class BrowserUtil {
|
||||
|
||||
async tryDismissAllMessages(page: Page): Promise<void> {
|
||||
const buttons = [
|
||||
{ selector: 'button[type="submit"]', label: 'Submit Button' },
|
||||
{ selector: '#acceptButton', label: 'AcceptButton' },
|
||||
{ selector: '.ext-secondary.ext-button', label: '"Skip for now" Button' },
|
||||
{ selector: '#iLandingViewAction', label: 'iLandingViewAction' },
|
||||
@@ -41,6 +40,24 @@ export default class BrowserUtil {
|
||||
// Silent fail
|
||||
}
|
||||
}
|
||||
|
||||
// Handle blocking Bing privacy overlay intercepting clicks (#bnp_overlay_wrapper)
|
||||
try {
|
||||
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> {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"baseURL": "https://rewards.bing.com",
|
||||
"sessionPath": "sessions",
|
||||
"headless": false,
|
||||
"parallel": true,
|
||||
"parallel": false,
|
||||
"runOnZeroPoints": false,
|
||||
"clusters": 1,
|
||||
"saveFingerprint": {
|
||||
@@ -43,5 +43,9 @@
|
||||
"webhook": {
|
||||
"enabled": false,
|
||||
"url": ""
|
||||
},
|
||||
"conclusionWebhook": {
|
||||
"enabled": false,
|
||||
"url": ""
|
||||
}
|
||||
}
|
||||
@@ -1 +1,2 @@
|
||||
${CRON_SCHEDULE} TZ=${TZ} /bin/bash /usr/src/microsoft-rewards-script/src/run_daily.sh >> /proc/1/fd/1 2>> /proc/1/fd/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
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Page } from 'rebrowser-playwright'
|
||||
import type { Page } from 'playwright'
|
||||
import readline from 'readline'
|
||||
import * as crypto from 'crypto'
|
||||
import { AxiosRequestConfig } from 'axios'
|
||||
@@ -10,8 +10,9 @@ 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
|
||||
})
|
||||
|
||||
export class Login {
|
||||
@@ -21,6 +22,8 @@ export class Login {
|
||||
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
|
||||
|
||||
constructor(bot: MicrosoftRewardsBot) {
|
||||
this.bot = bot
|
||||
@@ -29,8 +32,17 @@ export class Login {
|
||||
async login(page: Page, email: string, password: string) {
|
||||
|
||||
try {
|
||||
this.bot.log(this.bot.isMobile, 'LOGIN', 'Starting login process!')
|
||||
|
||||
// Navigate to the Bing login page
|
||||
await page.goto('https://rewards.bing.com/signin')
|
||||
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(() => { })
|
||||
|
||||
@@ -126,8 +138,33 @@ export class Login {
|
||||
|
||||
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) {
|
||||
@@ -159,12 +196,11 @@ export class Login {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private async handle2FA(page: Page) {
|
||||
try {
|
||||
const numberToPress = await this.get2FACode(page)
|
||||
if (numberToPress) {
|
||||
// Authentictor App verification
|
||||
// Authenticator App verification
|
||||
await this.authAppVerification(page, numberToPress)
|
||||
} else {
|
||||
// SMS verification
|
||||
@@ -177,7 +213,7 @@ export class Login {
|
||||
|
||||
private async get2FACode(page: Page): Promise<string | null> {
|
||||
try {
|
||||
const element = await page.waitForSelector('#displaySign', { state: 'visible', timeout: 2000 })
|
||||
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) {
|
||||
@@ -200,7 +236,7 @@ export class Login {
|
||||
|
||||
await page.click('button[aria-describedby="confirmSendTitle"]').catch(() => { })
|
||||
await this.bot.utils.wait(2000)
|
||||
const element = await page.waitForSelector('#displaySign', { state: 'visible', timeout: 2000 })
|
||||
const element = await page.waitForSelector('#displaySign, div[data-testid="displaySign"]>span', { state: 'visible', timeout: 2000 })
|
||||
return await element.textContent()
|
||||
}
|
||||
}
|
||||
@@ -212,13 +248,17 @@ export class Login {
|
||||
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('#i0281', { state: 'detached', timeout: 60000 })
|
||||
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"]')
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -228,7 +268,7 @@ export class Login {
|
||||
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)
|
||||
})
|
||||
@@ -239,17 +279,97 @@ export class Login {
|
||||
this.bot.log(this.bot.isMobile, 'LOGIN', '2FA code entered successfully')
|
||||
}
|
||||
|
||||
async getMobileAccessToken(page: Page, email: string) {
|
||||
const authorizeUrl = new URL(this.authBaseUrl)
|
||||
|
||||
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)
|
||||
|
||||
// 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(()=>{})
|
||||
|
||||
await page.goto(authorizeUrl.href)
|
||||
|
||||
let currentUrl = new URL(page.url())
|
||||
let code: string
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
currentUrl = new URL(page.url())
|
||||
// Shorter wait to react faster to passkey prompt
|
||||
await this.bot.utils.wait(1000)
|
||||
}
|
||||
|
||||
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.bot.browser.utils.tryDismissAllMessages(page)
|
||||
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
|
||||
@@ -257,6 +377,143 @@ export class Login {
|
||||
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')
|
||||
@@ -295,56 +552,6 @@ export class Login {
|
||||
}
|
||||
}
|
||||
|
||||
async getMobileAccessToken(page: Page, email: string) {
|
||||
const authorizeUrl = new URL(this.authBaseUrl)
|
||||
|
||||
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)
|
||||
|
||||
await page.goto(authorizeUrl.href)
|
||||
|
||||
let currentUrl = new URL(page.url())
|
||||
let code: string
|
||||
|
||||
this.bot.log(this.bot.isMobile, 'LOGIN-APP', 'Waiting for authorization...')
|
||||
// eslint-disable-next-line no-constant-condition
|
||||
while (true) {
|
||||
if (currentUrl.hostname === 'login.live.com' && currentUrl.pathname === '/oauth20_desktop.srf') {
|
||||
code = currentUrl.searchParams.get('code')!
|
||||
break
|
||||
}
|
||||
|
||||
currentUrl = new URL(page.url())
|
||||
await this.bot.utils.wait(5000)
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
this.bot.log(this.bot.isMobile, 'LOGIN-APP', 'Successfully authorized')
|
||||
return tokenData.access_token
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -352,4 +559,4 @@ export class Login {
|
||||
throw this.bot.log(this.bot.isMobile, 'CHECK-LOCKED', 'This account has been locked! Remove the account from "accounts.json" and restart!', 'error')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ export class Quiz extends Workers {
|
||||
|
||||
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 => el.getAttribute('iscorrectoption'))
|
||||
const answerAttribute = await answerSelector?.evaluate((el: any) => el.getAttribute('iscorrectoption'))
|
||||
|
||||
if (answerAttribute && answerAttribute.toLowerCase() === 'true') {
|
||||
answers.push(`#rqAnswerOption${i}`)
|
||||
@@ -60,7 +60,7 @@ export class Quiz extends Workers {
|
||||
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 => el.getAttribute('data-option'))
|
||||
const dataOption = await answerSelector?.evaluate((el: any) => el.getAttribute('data-option'))
|
||||
|
||||
if (dataOption === correctOption) {
|
||||
// Click the answer on page
|
||||
|
||||
@@ -295,7 +295,7 @@ export class Search extends Workers {
|
||||
const totalHeight = await page.evaluate(() => document.body.scrollHeight)
|
||||
const randomScrollPosition = Math.floor(Math.random() * (totalHeight - viewportHeight))
|
||||
|
||||
await page.evaluate((scrollPos) => {
|
||||
await page.evaluate((scrollPos: number) => {
|
||||
window.scrollTo(0, scrollPos)
|
||||
}, randomScrollPosition)
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Page } from 'rebrowser-playwright'
|
||||
import type { Page } from 'playwright'
|
||||
import * as fs from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
@@ -21,7 +21,7 @@ export class SearchOnBing extends Workers {
|
||||
|
||||
const searchBar = '#sb_form_q'
|
||||
await page.waitForSelector(searchBar, { state: 'visible', timeout: 10000 })
|
||||
await page.click(searchBar)
|
||||
await this.safeClick(page, searchBar)
|
||||
await this.bot.utils.wait(500)
|
||||
await page.keyboard.type(query)
|
||||
await page.keyboard.press('Enter')
|
||||
@@ -36,6 +36,22 @@ export class SearchOnBing extends Workers {
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -52,7 +68,7 @@ export class SearchOnBing extends Workers {
|
||||
// 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/main/src/functions/queries.json'
|
||||
url: 'https://raw.githubusercontent.com/TheNetsky/Microsoft-Rewards-Script/refs/heads/v1/src/functions/queries.json'
|
||||
})
|
||||
queries = response.data
|
||||
}
|
||||
@@ -72,4 +88,4 @@ export class SearchOnBing extends Workers {
|
||||
private normalizeString(string: string): string {
|
||||
return string.normalize('NFD').trim().toLowerCase().replace(/[^\x20-\x7E]/g, '').replace(/[?!]/g, '')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
279
src/index.ts
279
src/index.ts
@@ -1,5 +1,6 @@
|
||||
import cluster from 'cluster'
|
||||
import { Page } from 'rebrowser-playwright'
|
||||
// Use Page type from playwright for typings; at runtime rebrowser-playwright extends playwright
|
||||
import type { Page } from 'playwright'
|
||||
|
||||
import Browser from './browser/Browser'
|
||||
import BrowserFunc from './browser/BrowserFunc'
|
||||
@@ -15,6 +16,8 @@ import Activities from './functions/Activities'
|
||||
|
||||
import { Account } from './interface/Account'
|
||||
import Axios from './util/Axios'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
|
||||
// Main bot class
|
||||
@@ -41,6 +44,9 @@ export class MicrosoftRewardsBot {
|
||||
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
|
||||
|
||||
@@ -65,6 +71,7 @@ export class MicrosoftRewardsBot {
|
||||
}
|
||||
|
||||
async run() {
|
||||
this.printBanner()
|
||||
log('main', 'MAIN', `Bot started with ${this.config.clusters} clusters`)
|
||||
|
||||
// Only cluster when there's more than 1 cluster demanded
|
||||
@@ -79,6 +86,37 @@ export class MicrosoftRewardsBot {
|
||||
}
|
||||
}
|
||||
|
||||
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 */ }
|
||||
}
|
||||
|
||||
// Return summaries (used when clusters==1)
|
||||
public getSummaries() {
|
||||
return this.accountSummaries
|
||||
}
|
||||
|
||||
private runMaster() {
|
||||
log('main', 'MAIN-PRIMARY', 'Primary process started')
|
||||
|
||||
@@ -87,18 +125,27 @@ export class MicrosoftRewardsBot {
|
||||
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', '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', '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)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -106,7 +153,7 @@ export class MicrosoftRewardsBot {
|
||||
private runWorker() {
|
||||
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)
|
||||
})
|
||||
}
|
||||
@@ -115,34 +162,106 @@ export class MicrosoftRewardsBot {
|
||||
for (const account of accounts) {
|
||||
log('main', 'MAIN-WORKER', `Started tasks for account ${account.email}`)
|
||||
|
||||
this.axios = new Axios(account.proxy)
|
||||
if (this.config.parallel) {
|
||||
await Promise.all([
|
||||
this.Desktop(account),
|
||||
(() => {
|
||||
const mobileInstance = new MicrosoftRewardsBot(true)
|
||||
mobileInstance.axios = this.axios
|
||||
const accountStart = Date.now()
|
||||
let desktopInitial = 0
|
||||
let mobileInitial = 0
|
||||
let desktopCollected = 0
|
||||
let mobileCollected = 0
|
||||
const errors: string[] = []
|
||||
|
||||
return mobileInstance.Mobile(account)
|
||||
})()
|
||||
])
|
||||
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}`
|
||||
}
|
||||
|
||||
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
|
||||
await this.Desktop(account)
|
||||
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
|
||||
}
|
||||
|
||||
this.isMobile = true
|
||||
await this.Mobile(account)
|
||||
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(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) {
|
||||
log(false,'FLOW','Desktop() invoked')
|
||||
const browser = await this.browserFactory.createBrowser(account.proxy, account.email)
|
||||
this.homePage = await browser.newPage()
|
||||
|
||||
@@ -155,7 +274,8 @@ export class MicrosoftRewardsBot {
|
||||
|
||||
const data = await this.browser.func.getDashboardData()
|
||||
|
||||
this.pointsInitial = data.userStatus.availablePoints
|
||||
this.pointsInitial = data.userStatus.availablePoints
|
||||
const initial = this.pointsInitial
|
||||
|
||||
log(this.isMobile, 'MAIN-POINTS', `Current point count: ${this.pointsInitial}`)
|
||||
|
||||
@@ -206,13 +326,19 @@ export class MicrosoftRewardsBot {
|
||||
// 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 this.browser.func.closeBrowser(browser, account.email)
|
||||
return
|
||||
return {
|
||||
initialPoints: initial,
|
||||
collectedPoints: (after - initial) || 0
|
||||
}
|
||||
}
|
||||
|
||||
// Mobile
|
||||
async Mobile(account: Account) {
|
||||
log(true,'FLOW','Mobile() invoked')
|
||||
const browser = await this.browserFactory.createBrowser(account.proxy, account.email)
|
||||
this.homePage = await browser.newPage()
|
||||
|
||||
@@ -224,7 +350,8 @@ export class MicrosoftRewardsBot {
|
||||
|
||||
await this.browser.func.goHome(this.homePage)
|
||||
|
||||
const data = await this.browser.func.getDashboardData()
|
||||
const data = await this.browser.func.getDashboardData()
|
||||
const initialPoints = data.userStatus.availablePoints || this.pointsInitial || 0
|
||||
|
||||
const browserEnarablePoints = await this.browser.func.getBrowserEarnablePoints()
|
||||
const appEarnablePoints = await this.browser.func.getAppEarnablePoints(this.accessToken)
|
||||
@@ -239,9 +366,11 @@ export class MicrosoftRewardsBot {
|
||||
|
||||
// Close mobile browser
|
||||
await this.browser.func.closeBrowser(browser, account.email)
|
||||
return
|
||||
return {
|
||||
initialPoints: initialPoints,
|
||||
collectedPoints: 0
|
||||
}
|
||||
}
|
||||
|
||||
// Do daily check in
|
||||
if (this.config.workers.doDailyCheckIn) {
|
||||
await this.activities.doDailyCheckIn(this.accessToken, data)
|
||||
@@ -292,13 +421,113 @@ export class MicrosoftRewardsBot {
|
||||
|
||||
const afterPointAmount = await this.browser.func.getCurrentPoints()
|
||||
|
||||
log(this.isMobile, 'MAIN-POINTS', `The script collected ${afterPointAmount - this.pointsInitial} points today`)
|
||||
log(this.isMobile, 'MAIN-POINTS', `The script collected ${afterPointAmount - initialPoints} points today`)
|
||||
|
||||
// Close mobile browser
|
||||
await this.browser.func.closeBrowser(browser, account.email)
|
||||
return
|
||||
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] })
|
||||
}
|
||||
}
|
||||
|
||||
interface AccountSummary {
|
||||
email: string
|
||||
durationMs: number
|
||||
desktopCollected: number
|
||||
mobileCollected: number
|
||||
totalCollected: number
|
||||
initialTotal: number
|
||||
endTotal: number
|
||||
errors: string[]
|
||||
}
|
||||
|
||||
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() {
|
||||
|
||||
@@ -14,6 +14,7 @@ export interface Config {
|
||||
webhookLogExcludeFunc: string[];
|
||||
proxy: ConfigProxy;
|
||||
webhook: ConfigWebhook;
|
||||
conclusionWebhook?: ConfigWebhook; // Optional secondary webhook for final summary
|
||||
}
|
||||
|
||||
export interface ConfigSaveFingerprint {
|
||||
|
||||
168
src/run_daily.sh
Normal file → Executable file
168
src/run_daily.sh
Normal file → Executable file
@@ -1,32 +1,156 @@
|
||||
#!/bin/bash
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Set up environment variables
|
||||
export PATH=$PATH:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin
|
||||
export PATH="/usr/local/bin:/usr/bin:/bin"
|
||||
export PLAYWRIGHT_BROWSERS_PATH=0
|
||||
export TZ="${TZ:-UTC}"
|
||||
|
||||
# Ensure TZ is set
|
||||
export TZ=${TZ}
|
||||
|
||||
# Change directory to the application directory
|
||||
cd /usr/src/microsoft-rewards-script
|
||||
|
||||
# Define the minimum and maximum wait times in seconds
|
||||
MINWAIT=$((5*60)) # 5 minutes
|
||||
MAXWAIT=$((50*60)) # 50 minutes
|
||||
LOCKFILE=/tmp/run_daily.lock
|
||||
|
||||
# Calculate a random sleep time within the specified range
|
||||
SLEEPTIME=$((MINWAIT + RANDOM % (MAXWAIT - MINWAIT)))
|
||||
# -------------------------------
|
||||
# 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 "")
|
||||
|
||||
# Convert the sleep time to minutes for logging
|
||||
SLEEP_MINUTES=$((SLEEPTIME / 60))
|
||||
if [[ -z "$lock_content" ]]; then
|
||||
echo "[$(date)] [run_daily.sh] Found empty lockfile → removing."
|
||||
rm -f "$LOCKFILE"
|
||||
return
|
||||
fi
|
||||
|
||||
# Log the sleep duration
|
||||
echo "Sleeping for $SLEEP_MINUTES minutes ($SLEEPTIME seconds)..."
|
||||
# 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
|
||||
|
||||
# Sleep for the calculated time
|
||||
sleep $SLEEPTIME
|
||||
# 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
|
||||
}
|
||||
|
||||
# Log the start of the script
|
||||
echo "Starting script..."
|
||||
# -------------------------------
|
||||
# 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))
|
||||
|
||||
# Execute the Node.js script directly
|
||||
npm run start
|
||||
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
|
||||
|
||||
32
src/util/ConclusionWebhook.ts
Normal file
32
src/util/ConclusionWebhook.ts
Normal 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(() => { })
|
||||
}
|
||||
@@ -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. */
|
||||
|
||||
Reference in New Issue
Block a user