CheatSpecter 0.3.0

Browser-based real-time modding tool for offline single-player games on a
jailbroken PS5, served by a payload on the console.

- Value search, memory and code views, find what writes to a value
- Cheats as patches, held values, injected code, calls and scripts
- .cspector cheat files, saved on the PS5 or on your device
- Community tables in JSON, SHN and MC4 from three repositories
- Game library with names, logos and sizes; start a game from the browser
- MCP server for assistants
This commit is contained in:
Tiago Valente committed 2026-10-10 10:16:57 -07:00
commit 252ccd2e4c
87 files changed
+21452

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
node_modules/
dist/
.DS_Store
*.log
payload/build/
payload/*.elf
mcp/build/
mcp/*.mcpb
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+213
View File
@@ -0,0 +1,213 @@
# CheatSpecter
A real-time modding tool for jailbroken PS5 consoles that runs in a web
browser. Open it on a Mac, Windows or Linux machine, or on your phone, and it
talks to the [ps5debug-NG](https://github.com/Pharaoh2k/ps5debug-NG) payload
running on the console.
For single-player games you own. There is nothing here for online play.
## What it does
For people who just want cheats:
- **Find the console.** Consoles running the debugger are discovered on the
network; no IP typing unless discovery is blocked.
- **See what is running.** Name, icon, title ID and version of the game on
screen.
- **Your game library.** Every installed game with its platform (PS5 or PS4)
and size, and a Start button that boots it from the page.
- **Cheats as switches.** Matching cheat tables are looked up online for the
running game and shown as toggles. Before a cheat is switched on, the bytes
in the game's memory are compared with what the table expects; a cheat for
the wrong build is left off instead of corrupting the game.
- **Import** table files: CheatSpecter's own `.cspecter` format and the
community JSON, SHN and MC4 formats.
- **Save your own cheats** to the PS5 or to the device you are on. On the PS5
they are kept as `/data/cheatspecter/cheats/<title id>-<version>.cspecter`
and load by themselves whenever that game is running, from any device.
The library, game names and icons, starting games and saving to the PS5 need
the CheatSpecter payload on the console (`payload/cheatspecter.elf`), because
the debugger cannot do those things. Everything else works with ps5debug-NG
alone.
For people who make them:
- **Find a value**, known or unknown ("a bar with no number"), narrow it down
as it changes, edit it, hold it. "Auto" searches the common number types at
once when you do not know how the game stores it.
- **Find what writes to it.** A hardware watchpoint lists the instructions
that touch a value, and one click turns "the instruction that lowers my
ammo" into a saved cheat.
- **Memory view**: live hex, the selected bytes read as every number type,
follow pointers, write values or raw bytes.
- **Code view**: disassembly, byte-pattern search, and per-instruction actions
(disable it, hook it, follow a call, copy a signature).
- **Make it survive restarts**: a pointer-path search from the game's
executable to a value on the heap.
- **Your own table**, with five kinds of entry: byte patches (located by
signature so they survive game updates, and able to change several places
under one switch), held values, injected assembly
through a code cave, calls to the game's own functions, and scripts
(JavaScript with a small API for reading, writing, calling and switching
other entries). Export it to share, or as a GoldHEN table where the format
allows.
The maker features need ps5debug-NG specifically; with the original ps5debug
the table switches still work.
**What has run on a real PS5** (firmware 13.60, ps5debug-NG 1.3.2): finding
the running game, its name and icon, the game library, loading community
tables, known-value searches, watchpoints, byte patches located by offset and
by pattern, and saving and auto-loading `.cspecter` files on the console.
**Only tested against the built-in mock console so far:** injected code,
function calls, scripts, the pointer-path search, unknown-value searches,
starting a game from the library, and PS4 titles.
## Things that can crash a game
These come from how debugging a live process works, not from bugs to be fixed
later. The app says so at the point of use; they are collected here.
- **Tracing** attaches a debugger to the game. If the browser tab is closed
mid-trace, the console detaches without disarming the watchpoint and the
game may die at the next hit. Press Stop first.
- **Injected code** is written while the game keeps running. Switch a hook on
at a quiet moment. A hook replaces at least five bytes; if that spans
several instructions and the game jumps into the middle of them, it crashes.
- **Function calls** borrow a game thread. The function must return within
about two seconds, and one that returns -1 is retried by the console up to
seven times.
- **Scripts and imported entries that run code** are held for review before
first use. Read them. Only use tables from people you trust.
## Run it
Double-click **Start CheatSpecter.command** (macOS) or **Start
CheatSpecter.bat** (Windows). It installs on first run, starts the bridge and
opens the browser. Needs [Node.js](https://nodejs.org) 20.19 or newer.
From a terminal:
```sh
npm install
npm start # real console
npm run demo # adds a pretend PS5 so you can click around without one
```
Tracing ("what writes to this") makes the console connect back to this
computer on TCP port 755, so the firewall has to let that in; macOS will ask
the first time. `npm run demo` uses a different port and is for the pretend
console only.
The start-up message lists the address to open from a phone on the same Wi-Fi.
On the PS5, load ps5debug-NG first (etaHEN can start it from its toolbox). It
shows a "loaded" notification when ready.
## How it fits together
```
Browser (any device) Computer PS5
┌──────────────────────┐ ┌──────────────────┐ ┌──────────────────────┐
│ web app │ │ bridge/server.mjs│ │ ps5debug-NG │
│ protocol client │◄─►│ WebSocket ⇄ TCP │◄─►│ TCP 744 │
│ scanner, cheats │ WS│ serves the app │TCP│ │
└──────────┬───────────┘ └──────────────────┘ └──────────────────────┘
│ HTTPS
▼
cheat table collections (GitHub)
```
Browsers cannot open raw TCP sockets, so something has to relay. There are two
ways to run that relay, and the web app is identical in both:
- **On a computer** (`bridge/server.mjs`), as drawn above. This is what the
launcher starts, and what has been exercised most.
- **On the console itself** (`payload/`). A small ELF serves the app and
relays to the debugger locally, so nothing is installed anywhere and any
device just opens `http://<PS5 IP>:8744`. See `payload/README.md`.
Cheat tables are fetched by the browser, so the console itself never needs
internet access.
| Path | What it is |
| --- | --- |
| `src/lib/ps5debug.ts` | The debugger's wire protocol |
| `src/lib/scanner.ts` | Known-value, unknown-value and Auto scans |
| `mcp/server.ts` | The same library as MCP tools for Claude |
| `src/lib/cheats.ts` | Community cheat tables: parsing, state detection, applying |
| `src/lib/table.ts` | CheatSpecter's own table format and the runner that applies it |
| `src/lib/locations.ts` | Signatures, offsets and pointer paths, resolved to addresses |
| `src/lib/tracer.ts` | "What writes to this address" |
| `src/lib/pointerscan.ts` | Pointer-path search |
| `src/lib/script.ts` | The script API and its sandbox |
| `src/lib/x86.ts` | Disassembly, relocation and signatures (iced-x86, in a worker) |
| `src/lib/catalog.ts` | Online table lookup and offline cache |
| `src/ui/` | The interface (React, Tailwind) |
| `src/components/` | shadcn/ui and [Kibo UI](https://www.kibo-ui.com) components, added with the shadcn CLI |
| `bridge/server.mjs` | WebSocket-to-TCP relay, discovery, static files |
| `payload/` | The on-console ELF: the same relay in C, with the app embedded |
| `mock/mock-ps5.mjs` | Pretend console with a tiny simulated game |
| `cheats/` | Drop table files here to have them offered alongside the online ones |
| `test/` | End-to-end tests: client → bridge → mock |
## Development
```sh
npm run dev # Vite with hot reload + bridge + demo console
npm test # needs Node 22.18+ (the tests import the TypeScript directly)
npm run typecheck
```
## Where cheat tables come from
Tables are read at runtime from these community collections, in their original
location. Nothing from them is copied into this repository.
- [etaHEN PS5 Cheats](https://github.com/etaHEN/PS5_Cheats)
- [GoldHEN Cheat Repository](https://github.com/GoldHEN/GoldHEN_Cheat_Repository)
- [HEN Cheats Collection](https://github.com/TeeKay87/HEN-Cheats-Collection)
All three formats they publish are read: JSON, SHN and MC4. When a repository
has the same table in several formats, the JSON one is used.
## Using it from Claude (MCP)
`npm run mcp` builds `mcp/cheatspecter-<version>.mcpb`, a desktop extension
for the Claude app. Open the file to install it and enter the PS5's address
when asked. Claude then has tools to see what is running, search and read
memory, find the code that changes a value, disassemble, and save cheats to
the same `.cspecter` file the web app loads. It runs on your computer and
talks to the payload on the console; nothing is installed on the PS5.
To run it by hand instead: `CHEATSPECTER_HOST=<ps5 address> node mcp/build/server/index.mjs`
speaks MCP over stdin/stdout.
## The .cspecter format
A `.cspecter` file is minified JSON:
```json
{"format":"cheatspecter","formatVersion":1,
"game":{"name":"…","titleId":"PPSA07391","version":"01.009.000"},
"cheats":[{"name":"Infinite ammo","type":"patch","at":{"kind":"module","offset":"0x2040"},"on":"909090","off":"FF4B28"}]}
```
`type` is one of `patch`, `value`, `inject`, `call` or `script`. A patch can
carry `"more": [{"at": …, "on": "…", "off": "…"}]` for further places changed by
the same switch. A formatted copy loads the same as a minified one.
## Safety notes
- The bridge only relays to private network addresses on the debugger's port,
and only accepts WebSocket connections from the page it served.
- Anyone on your network can reach the debugger directly on port 744 anyway;
the bridge does not make that better or worse. Use a network you trust.
## License
GPL-3.0-only, matching ps5debug-NG, whose protocol this implements and whose
handler logic the mock console follows.
+15
View File
@@ -0,0 +1,15 @@
@echo off
rem Double-click to start CheatSpecter on Windows.
cd /d "%~dp0"
where node >nul 2>nul
if errorlevel 1 (
echo CheatSpecter needs Node.js. Install it from https://nodejs.org and open this again.
pause
exit /b 1
)
if not exist node_modules (
echo First run: installing, about a minute...
call npm install || (pause & exit /b 1)
)
call npm start -- --open
pause
+21
View File
@@ -0,0 +1,21 @@
#!/bin/bash
# Double-click to start CheatSpecter on macOS. Add "demo" to try it without a console:
# ./Start\ CheatSpecter.command demo
cd "$(dirname "$0")" || exit 1
if ! command -v node >/dev/null 2>&1; then
echo "CheatSpecter needs Node.js. Install it from https://nodejs.org and open this again."
read -r -p "Press Return to close."
exit 1
fi
if [ ! -d node_modules ]; then
echo "First run: installing (about a minute)..."
npm install || { read -r -p "Install failed. Press Return to close."; exit 1; }
fi
if [ "$1" = "demo" ]; then
npm run demo -- --open
else
npm start -- --open
fi
+96
View File
@@ -0,0 +1,96 @@
// The demo console's game library: what the on-console payload would answer
// for /api/library and /api/appmeta/..., so the library screen can be tried
// without a PS5. Also used by the tests as a source of well-formed files.
/** Builds a PS4 param.sfo from string and number entries. */
export function buildSfo(entries) {
const keys = Object.keys(entries).sort();
const enc = new TextEncoder();
const rows = keys.map((key) => {
const value = entries[key];
if (typeof value === 'number') {
const data = new Uint8Array(4);
new DataView(data.buffer).setUint32(0, value, true);
return { key, fmt: 0x0404, data, len: 4, max: 4 };
}
const text = enc.encode(value);
const max = (text.length + 1 + 3) & ~3;
const data = new Uint8Array(max);
data.set(text);
return { key, fmt: 0x0204, data, len: text.length + 1, max };
});
const keyBytes = rows.map((r) => enc.encode(r.key + '\0'));
const keyTableStart = 20 + 16 * rows.length;
const keyTableSize = keyBytes.reduce((n, k) => n + k.length, 0);
const dataStart = (keyTableStart + keyTableSize + 3) & ~3;
const out = new Uint8Array(dataStart + rows.reduce((n, r) => n + r.max, 0));
const view = new DataView(out.buffer);
out.set([0x00, 0x50, 0x53, 0x46]);
view.setUint32(4, 0x0101, true);
view.setUint32(8, keyTableStart, true);
view.setUint32(12, dataStart, true);
view.setUint32(16, rows.length, true);
let keyOff = 0;
let dataOff = 0;
rows.forEach((r, i) => {
const at = 20 + 16 * i;
view.setUint16(at, keyOff, true);
view.setUint16(at + 2, r.fmt, true);
view.setUint32(at + 4, r.len, true);
view.setUint32(at + 8, r.max, true);
view.setUint32(at + 12, dataOff, true);
out.set(keyBytes[i], keyTableStart + keyOff);
out.set(r.data, dataStart + dataOff);
keyOff += keyBytes[i].length;
dataOff += r.max;
});
return out;
}
export function buildParamJson(titleId, name, version) {
return JSON.stringify({
titleId,
contentId: `IV9999-${titleId}_00-0000000000000000`,
contentVersion: version,
localizedParameters: { defaultLanguage: 'en-US', 'en-US': { titleName: name } },
});
}
const GIB = 1024 ** 3;
export const DEMO_TITLES = [
{ id: 'PPSA99999', meta: 'json', name: 'Specter Run', version: '01.000.000', size: 41.6 * GIB, path: '/user/app/PPSA99999' },
{ id: 'PPSA20417', meta: 'json', name: 'Neon Circuit: Midnight Tour', version: '01.012.000', size: 87.3 * GIB, path: '/user/app/PPSA20417' },
{ id: 'PPSA31082', meta: 'json', name: 'Hollow Harbor', version: '01.004.000', size: 23.9 * GIB, path: '/mnt/ext0/user/app/PPSA31082' },
{ id: 'CUSA58230', meta: 'sfo', name: 'Pellet Kingdom Remastered', version: '01.07', size: 12.2 * GIB, path: '/user/app/CUSA58230' },
{ id: 'CUSA60944', meta: 'sfo', name: 'Lantern Road', version: '01.00', size: 0, path: '' },
];
/** Answers a library request the way the payload would. Returns null for "not found". */
export function demoLibraryResponse(pathname) {
if (pathname === '/api/library') {
const titles = DEMO_TITLES.map(({ id, meta, size, path }) => ({ id, meta, size: Math.round(size), path }));
return { type: 'application/json; charset=utf-8', body: JSON.stringify({ titles }) };
}
const m = /^\/api\/appmeta\/([A-Z]{4}\d{5})\/(param\.json|param\.sfo|icon0\.png)$/.exec(pathname);
const title = m && DEMO_TITLES.find((t) => t.id === m[1]);
if (!title) return null;
if (m[2] === 'icon0.png') {
// A stand-in for the game's icon: its initials on a tile. Browsers go by the content type, not the name.
const initials = title.name.split(/\s+/).slice(0, 2).map((w) => w[0]).join('').toUpperCase();
const hue = [...title.id].reduce((n, c) => n + c.charCodeAt(0), 0) % 360;
const svg =
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><rect width="512" height="512" fill="hsl(${hue} 55% 22%)"/>` +
`<circle cx="256" cy="256" r="150" fill="hsl(${hue} 70% 45%)"/>` +
`<text x="256" y="300" font-family="system-ui,sans-serif" font-size="130" font-weight="700" text-anchor="middle" fill="#fff">${initials}</text></svg>`;
return { type: 'image/svg+xml', body: svg };
}
if (m[2] === 'param.json' && title.meta === 'json') {
return { type: 'application/json; charset=utf-8', body: buildParamJson(title.id, title.name, title.version) };
}
if (m[2] === 'param.sfo' && title.meta === 'sfo') {
const sfo = buildSfo({ TITLE: title.name, TITLE_ID: title.id, APP_VER: title.version, CATEGORY: 'gd', PARENTAL_LEVEL: 1 });
return { type: 'application/octet-stream', body: Buffer.from(sfo) };
}
return null;
}
+558
View File
@@ -0,0 +1,558 @@
// CheatSpecter dev bridge.
//
// Browsers cannot open raw TCP sockets, and the PS5 debugger only speaks raw
// TCP. This small server sits between them on a computer: it serves the web
// app and relays a WebSocket to the debugger's TCP port, byte for byte.
//
// The on-console payload will replace this with the same three things:
// GET / the web app
// GET /api/info { mode, version }
// WS /ws binary frames <-> debugger TCP stream
// WS /events debugger stop reports (the console connects back to us
// on TCP 755 when a debugger attaches; those bytes are
// forwarded here)
//
// Extras that only make sense on a computer: LAN discovery, a local cheats
// folder, and a built-in demo console (--demo).
//
// node bridge/server.mjs [--demo] [--open] [--port 8744]
import http from 'node:http';
import net from 'node:net';
import dgram from 'node:dgram';
import os from 'node:os';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { spawn } from 'node:child_process';
import { WebSocketServer } from 'ws';
import { DEMO_TITLES, demoLibraryResponse } from './demo-library.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const DIST = path.join(ROOT, 'dist');
const CHEATS_DIR = path.join(ROOT, 'cheats');
const TABLE_MAX = 4 << 20;
const VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version;
const DEBUGGER_PORT = 744;
const DISCOVERY_PORT = 1010;
const EVENT_PORT = 755;
/** Where the CheatSpecter payload on the console answers. */
const DEFAULT_PAYLOAD_PORT = 8744;
const DISCOVERY_MAGIC = Buffer.from([0xaa, 0xaa, 0xff, 0xff]); // 0xFFFFAAAA little-endian
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.svg': 'image/svg+xml',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.ico': 'image/x-icon',
'.webmanifest': 'application/manifest+json',
'.wasm': 'application/wasm',
};
// ---- which addresses the bridge will relay to --------------------------------
/**
* The bridge only relays to consoles on the local network. Without this it
* would be an open proxy for anything that can reach it.
*/
export function isPrivateAddress(host) {
if (net.isIPv4(host)) {
const [a, b] = host.split('.').map(Number);
return a === 10 || a === 127 || (a === 192 && b === 168) || (a === 172 && b >= 16 && b <= 31) || (a === 169 && b === 254);
}
return false;
}
/**
* A page from another site must not be able to drive the bridge, so the
* WebSocket is only accepted from the app this server itself served.
*/
function sameOrigin(req) {
const origin = req.headers.origin;
if (!origin) return true; // not a browser (tests, scripts on this machine)
try {
return new URL(origin).host === req.headers.host;
} catch {
return false;
}
}
// ---- discovery ---------------------------------------------------------------
function broadcastAddresses() {
const out = new Set(['255.255.255.255']);
for (const list of Object.values(os.networkInterfaces())) {
for (const i of list ?? []) {
if (i.family !== 'IPv4' || i.internal) continue;
const ip = i.address.split('.').map(Number);
const mask = i.netmask.split('.').map(Number);
out.add(ip.map((octet, n) => (octet | (~mask[n] & 0xff)) & 0xff).join('.'));
}
}
return [...out];
}
/** Asks the LAN "is there a debugger here?" and collects whoever echoes. */
function discover(extraProbes, waitMs = 900) {
return new Promise((resolve) => {
const found = new Map();
const sock = dgram.createSocket({ type: 'udp4', reuseAddr: true });
const finish = () => {
try {
sock.close();
} catch {
// already closed
}
resolve([...found.values()]);
};
sock.on('error', finish);
sock.on('message', (msg, rinfo) => {
if (msg.length !== 4 || !msg.equals(DISCOVERY_MAGIC)) return;
const probe = extraProbes.find((p) => p.udpPort === rinfo.port && p.host === rinfo.address);
if (probe) found.set(`${probe.host}:${probe.port}`, { host: probe.host, port: probe.port, label: probe.label });
else if (rinfo.port === DISCOVERY_PORT) found.set(rinfo.address, { host: rinfo.address, port: DEBUGGER_PORT, label: 'PS5' });
});
sock.bind(0, () => {
try {
sock.setBroadcast(true);
} catch {
// some platforms refuse; unicast probes still work
}
for (const addr of broadcastAddresses()) sock.send(DISCOVERY_MAGIC, DISCOVERY_PORT, addr, () => {});
for (const p of extraProbes) sock.send(DISCOVERY_MAGIC, p.udpPort, p.host, () => {});
setTimeout(finish, waitMs);
});
});
}
// ---- http --------------------------------------------------------------------
function sendJson(res, code, body) {
const data = JSON.stringify(body);
res.writeHead(code, { 'content-type': MIME['.json'], 'cache-control': 'no-store' });
res.end(data);
}
function serveFile(res, file, cache = 'no-cache') {
fs.readFile(file, (err, data) => {
if (err) {
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
res.end('Not found');
return;
}
res.writeHead(200, {
'content-type': MIME[path.extname(file).toLowerCase()] ?? 'application/octet-stream',
'cache-control': cache,
});
res.end(data);
});
}
/** Resolves a URL path inside a folder, refusing anything that escapes it. */
function safeJoin(base, urlPath) {
let rel;
try {
rel = decodeURIComponent(urlPath);
} catch {
return null;
}
const full = path.resolve(base, '.' + path.posix.normalize('/' + rel));
return full === base || full.startsWith(base + path.sep) ? full : null;
}
/** Community tables dropped into the cheats/ folder: JSON, SHN or MC4. */
const LOCAL_TABLE_RE = /\.(json|shn|mc4)$/i;
function localCheatIndex() {
let files = [];
try {
files = fs.readdirSync(CHEATS_DIR).filter((f) => LOCAL_TABLE_RE.test(f));
} catch {
return '';
}
const lines = [];
for (const f of files) {
let name = '';
try {
name = String(JSON.parse(fs.readFileSync(path.join(CHEATS_DIR, f), 'utf8').replace(/^/, '')).name ?? '');
} catch {
// listed anyway; the app reports the parse error when it is opened
}
lines.push(`${f}=${name}`);
}
return lines.join('\n');
}
/**
* @param {object} [opts]
* @param {number} [opts.port]
* @param {string} [opts.host]
* @param {{host:string, port:number, udpPort:number, label:string}|null} [opts.demo]
* @param {number|null} [opts.eventPort] where consoles connect back with debugger events (default 755, null = off)
*/
export function startBridge(opts = {}) {
const demo = opts.demo ?? null;
const PAYLOAD_PORT = opts.payloadPort ?? DEFAULT_PAYLOAD_PORT;
/** The demo console's saved cheat files, kept only while the bridge runs. */
const demoTables = new Map();
const allowed = (host, port) =>
(isPrivateAddress(host) && port === DEBUGGER_PORT) || (demo && host === demo.host && port === demo.port);
// ---- debugger events ----
// On attach the console opens a TCP connection back to the machine that sent
// the attach, always to port 755. Whatever arrives is passed to the browsers
// that asked for events from that console.
const eventPort = opts.eventPort === undefined ? EVENT_PORT : opts.eventPort;
const eventSubs = new Map(); // console address -> Set<WebSocket>
let eventsError = eventPort === null ? 'Debugger events are turned off' : null;
const eventServer = net.createServer((sock) => {
const from = (sock.remoteAddress ?? '').replace(/^::ffff:/, '');
sock.on('error', () => {});
sock.on('data', (chunk) => {
for (const ws of eventSubs.get(from) ?? []) {
if (ws.readyState === ws.OPEN) ws.send(chunk, { binary: true });
}
});
// The console closes this when the session ends (detach, game exit, error).
sock.on('close', () => {
for (const ws of eventSubs.get(from) ?? []) {
if (ws.readyState === ws.OPEN) ws.close(4005, 'The console ended the debugging session');
}
});
});
const eventsReady = new Promise((resolve) => {
if (eventPort === null) return resolve();
eventServer.once('error', (err) => {
eventsError =
err.code === 'EADDRINUSE'
? `Port ${eventPort} is in use by another program (another debugger tool?)`
: err.code === 'EACCES'
? `This system does not let CheatSpecter listen on port ${eventPort} without administrator rights`
: `Could not listen on port ${eventPort} (${err.code})`;
resolve();
});
eventServer.listen(eventPort, '0.0.0.0', () => resolve());
});
/**
* The game library, game names, "start this game" and the cheat files saved
* on the PS5 are all handled by the CheatSpecter payload on the console (the
* debugger can do none of them), so these requests are passed on to it.
*/
async function consoleApi(req, res, url) {
const p = url.pathname;
const host = url.searchParams.get('host') ?? '';
const launching = p.startsWith('/api/launch/');
const table = /^\/api\/tables\/([A-Z]{4}\d{5})(?:\/([0-9A-Za-z][0-9A-Za-z.]{0,15}))?$/.exec(p);
const saving = !!table && !!table[2] && req.method === 'PUT';
const methodOk = launching ? req.method === 'POST' : saving || req.method === 'GET';
if (!methodOk || !sameOrigin(req)) {
res.writeHead(sameOrigin(req) ? 405 : 403);
res.end();
return;
}
let body;
if (saving) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > TABLE_MAX) {
res.writeHead(413);
res.end();
return;
}
chunks.push(chunk);
}
body = Buffer.concat(chunks);
}
if (demo && host === demo.host) {
if (launching) {
const known = DEMO_TITLES.some((t) => p === `/api/launch/${t.id}`);
const running = p === '/api/launch/PPSA99999';
sendJson(res, running ? 200 : known ? 500 : 404, running
? { ok: true }
: { ok: false, error: known ? 'The demo console only has one game it can actually run' : 'That game is not on this console' });
return;
}
if (table) {
const [, tid, version] = table;
if (!version) {
const versions = [...demoTables.keys()].filter((k) => k.startsWith(`${tid}-`)).map((k) => k.slice(10));
sendJson(res, 200, { folder: '/data/cheatspecter/cheats', versions });
} else if (saving) {
demoTables.set(`${tid}-${version}`, body);
res.writeHead(204);
res.end();
} else if (demoTables.has(`${tid}-${version}`)) {
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
res.end(demoTables.get(`${tid}-${version}`));
} else {
res.writeHead(404);
res.end();
}
return;
}
const answer = demoLibraryResponse(p);
if (!answer) {
res.writeHead(404);
res.end();
return;
}
res.writeHead(200, { 'content-type': answer.type, 'cache-control': 'no-store' });
res.end(answer.body);
return;
}
if (!isPrivateAddress(host) || !(table || /^\/api\/(library|appmeta\/[A-Z]{4}\d{5}\/[a-z0-9.]+|launch\/[A-Z]{4}\d{5})$/.test(p))) {
res.writeHead(400);
res.end();
return;
}
try {
const upstream = await fetch(`http://${host}:${PAYLOAD_PORT}${p}`, {
method: req.method,
body,
signal: AbortSignal.timeout(launching ? 30_000 : 20_000),
});
const answer = Buffer.from(await upstream.arrayBuffer());
res.writeHead(upstream.status, {
'content-type': upstream.headers.get('content-type') ?? 'application/octet-stream',
'cache-control': upstream.headers.get('cache-control') ?? 'no-store',
'x-content-type-options': 'nosniff',
});
res.end(answer);
} catch {
// Nothing answering on the payload's port: it has not been loaded on this console.
sendJson(res, 502, { ok: false, error: 'payload-missing' });
}
}
const server = http.createServer((req, res) => {
const url = new URL(req.url ?? '/', 'http://localhost');
const p = url.pathname;
if (p.startsWith('/api/tables/') || p === '/api/library' || p.startsWith('/api/appmeta/') || p.startsWith('/api/launch/')) {
void consoleApi(req, res, url);
return;
}
if (req.method !== 'GET' && req.method !== 'HEAD') {
res.writeHead(405);
res.end();
return;
}
if (p === '/api/info') {
sendJson(res, 200, {
mode: 'bridge',
version: VERSION,
events: eventsError === null,
...(demo ? { demo: { host: demo.host, port: demo.port, label: demo.label } } : {}),
});
return;
}
if (p === '/api/discover') {
discover(demo ? [demo] : []).then((list) => sendJson(res, 200, list));
return;
}
if (p === '/api/local-cheats') {
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
res.end(localCheatIndex());
return;
}
if (p.startsWith('/local-cheats/')) {
const file = safeJoin(CHEATS_DIR, p.slice('/local-cheats/'.length));
if (!file || !LOCAL_TABLE_RE.test(file)) {
res.writeHead(404);
res.end();
return;
}
serveFile(res, file, 'no-store');
return;
}
const file = safeJoin(DIST, p === '/' ? 'index.html' : p.slice(1));
if (!file) {
res.writeHead(404);
res.end();
return;
}
if (!fs.existsSync(DIST)) {
res.writeHead(503, { 'content-type': 'text/plain; charset=utf-8' });
res.end('The web app has not been built yet. Run "npm run build" (or "npm start", which does it for you).');
return;
}
// Hashed asset names never change content, so they can be cached hard.
serveFile(res, file, p.startsWith('/assets/') ? 'public, max-age=31536000, immutable' : 'no-cache');
});
const wss = new WebSocketServer({ noServer: true, perMessageDeflate: false });
server.on('upgrade', (req, socket, head) => {
const url = new URL(req.url ?? '/', 'http://localhost');
if ((url.pathname !== '/ws' && url.pathname !== '/events') || !sameOrigin(req)) {
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
socket.destroy();
return;
}
wss.handleUpgrade(req, socket, head, (ws) => (url.pathname === '/ws' ? relay(ws, url) : subscribe(ws, url)));
});
function subscribe(ws, url) {
const host = url.searchParams.get('host') ?? '';
if (!isPrivateAddress(host)) {
ws.close(4003, 'That address is not a console on your local network');
return;
}
if (eventsError) {
ws.close(4004, eventsError);
return;
}
if (!eventSubs.has(host)) eventSubs.set(host, new Set());
eventSubs.get(host).add(ws);
ws.on('close', () => eventSubs.get(host)?.delete(ws));
ws.on('error', () => {});
}
function relay(ws, url) {
const host = url.searchParams.get('host') ?? '';
const port = Number(url.searchParams.get('port') ?? DEBUGGER_PORT);
if (!allowed(host, port)) {
ws.close(4003, 'That address is not a console on your local network');
return;
}
const tcp = net.connect({ host, port });
tcp.setNoDelay(true);
let open = false;
const pending = [];
const timer = setTimeout(() => {
if (!open) tcp.destroy(new Error('timeout'));
}, 5000);
tcp.on('connect', () => {
open = true;
clearTimeout(timer);
for (const chunk of pending) tcp.write(chunk);
pending.length = 0;
});
tcp.on('data', (chunk) => {
if (ws.readyState !== ws.OPEN) return;
ws.send(chunk, { binary: true });
// Slow browser, fast console: stop reading until the socket drains.
if (ws.bufferedAmount > 8 * 1024 * 1024) {
tcp.pause();
const resume = () => {
if (ws.readyState !== ws.OPEN) return;
if (ws.bufferedAmount < 1024 * 1024) tcp.resume();
else setTimeout(resume, 20);
};
setTimeout(resume, 20);
}
});
tcp.on('error', (err) => {
clearTimeout(timer);
const reason = !open
? err.code === 'ECONNREFUSED'
? 'The console refused the connection. Is the ps5debug payload loaded?'
: 'Could not reach the console. Check that it is on and on the same network.'
: 'Lost the connection to the console';
if (ws.readyState === ws.OPEN || ws.readyState === ws.CONNECTING) ws.close(4001, reason);
});
tcp.on('close', () => {
clearTimeout(timer);
if (ws.readyState === ws.OPEN) ws.close(4002, 'The console closed the connection');
});
ws.on('message', (data, isBinary) => {
if (!isBinary) return;
if (open) tcp.write(data);
else pending.push(data);
});
ws.on('close', () => tcp.destroy());
ws.on('error', () => tcp.destroy());
}
const ready = eventsReady.then(
() =>
new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(opts.port ?? 8744, opts.host ?? '0.0.0.0', () => resolve(server.address().port));
}),
);
return {
ready,
server,
close() {
for (const c of wss.clients) c.terminate();
server.closeAllConnections?.();
if (eventServer.listening) eventServer.close();
return new Promise((resolve) => server.close(() => resolve()));
},
};
}
// ---- command line ------------------------------------------------------------
function lanAddresses() {
const out = [];
for (const list of Object.values(os.networkInterfaces())) {
for (const i of list ?? []) if (i.family === 'IPv4' && !i.internal) out.push(i.address);
}
return out;
}
function openBrowser(url) {
const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
try {
spawn(cmd, args, { stdio: 'ignore', detached: true }).on('error', () => {}).unref();
} catch {
// the URL is printed either way
}
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const args = process.argv.slice(2);
const flag = (name) => args.includes(name);
const portArg = args.indexOf('--port');
const port = portArg >= 0 ? Number(args[portArg + 1]) : Number(process.env.PORT ?? 8744);
let demo = null;
// In demo mode nothing real will connect back, so use an unprivileged port
// that works on every system.
const DEMO_EVENT_PORT = 17755;
if (flag('--demo')) {
const { startMock, MOCK_TCP_PORT, MOCK_UDP_PORT } = await import('../mock/mock-ps5.mjs');
// A real console takes a while to scan; the pause makes the demo show progress too.
const mock = startMock({ scanDelayMs: 250, eventPort: DEMO_EVENT_PORT });
await mock.ready;
demo = { host: '127.0.0.1', port: MOCK_TCP_PORT, udpPort: MOCK_UDP_PORT, label: 'Demo console' };
}
const bridge = startBridge({ port, demo, eventPort: demo ? DEMO_EVENT_PORT : EVENT_PORT });
bridge.ready
.then((actual) => {
const local = `http://localhost:${actual}`;
console.log(`\n CheatSpecter ${VERSION}${demo ? ' (demo console running)' : ''}\n`);
console.log(` On this computer: ${local}`);
for (const ip of lanAddresses()) console.log(` Phone or tablet: http://${ip}:${actual}`);
console.log('\n Leave this window open while you use it. Close it to stop.\n');
if (flag('--open')) openBrowser(local);
})
.catch((err) => {
if (err.code === 'EADDRINUSE') {
console.error(`\n Port ${port} is already in use. CheatSpecter may already be running: http://localhost:${port}\n`);
if (flag('--open')) openBrowser(`http://localhost:${port}`);
} else {
console.error(err);
}
process.exit(1);
});
}
+41
View File
@@ -0,0 +1,41 @@
{
"name": "Specter Test Game",
"id": "PPSA99999",
"version": "01.000.000",
"process": "eboot.bin",
"mods": [
{
"name": "Infinite Health",
"description": "Health stops draining.",
"type": "checkbox",
"memory": [
{ "offset": "1000", "on": "909090909090", "off": "898190030000" }
]
},
{
"name": "Infinite Ammo",
"description": "Shots no longer use ammo.",
"type": "checkbox",
"memory": [
{ "offset": "2040", "on": "909090", "off": "FF4B28" }
]
},
{
"name": "Free Purchases",
"description": "Gold is not spent.",
"type": "checkbox",
"memory": [
{ "offset": "30A0", "on": "90909090", "off": "F30F5CC1" }
]
},
{
"name": "Wrong Build Example",
"description": "Deliberately does not match the demo game, to show what a version mismatch looks like.",
"type": "checkbox",
"memory": [
{ "offset": "5000", "on": "9090", "off": "74AB" }
]
}
],
"credits": ["CheatSpecter demo"]
}
+22
View File
@@ -0,0 +1,22 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/styles.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide",
"registries": { "@kibo-ui": "https://www.kibo-ui.com/r/{name}.json" }
}
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en" class="dark">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#070707" />
<meta name="color-scheme" content="dark" />
<title>CheatSpecter</title>
<link rel="icon" type="image/svg+xml" href="./ghost.svg" />
<link rel="apple-touch-icon" href="./ghost.svg" />
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+792
View File
@@ -0,0 +1,792 @@
// CheatSpecter as an MCP server.
//
// Runs on a computer, talks to the CheatSpecter payload on a PS5 over the
// local network, and offers the workbench as tools: see what is running,
// read and write memory, search for values, find what code touches a value,
// disassemble, and keep the user's cheat file up to date.
//
// It is the same library the web app uses, so anything found here ends up in
// the same .cspecter file the app loads.
//
// The protocol (JSON-RPC over stdin/stdout, one message per line) is small
// enough to speak directly, which keeps this free of dependencies.
import { createRequire } from 'node:module';
import readline from 'node:readline';
import { bytesToHex, hexToBytes } from '../src/lib/bytes.ts';
import { parseParamJson, parseParamSfo, formatSize } from '../src/lib/library.ts';
import { createGameContext, findPattern, resolveLocation } from '../src/lib/locations.ts';
import type { GameContext } from '../src/lib/locations.ts';
import type { MapEntry } from '../src/lib/ps5debug.ts';
import { PROT } from '../src/lib/ps5debug.ts';
import { AutoScan, COMPARE_KINDS, ScanSession, VALUE_KINDS, compareKind, decodeValue, encodeValue, scannableRegions, valueKind } from '../src/lib/scanner.ts';
import type { Scan, ScanRegion } from '../src/lib/scanner.ts';
import { Session, formatFirmware } from '../src/lib/session.ts';
import type { Game } from '../src/lib/session.ts';
import { TableRunner, describeEntry, emptyTable, isAction, newId, parseOwnTable, saveFileText } from '../src/lib/table.ts';
import type { Entry, OwnTable } from '../src/lib/table.ts';
import { fileVersion, pickVersion, tableFileName } from '../src/lib/tablestore.ts';
import { Tracer } from '../src/lib/tracer.ts';
import { asAsync, createX86, signatureFromCode } from '../src/lib/x86.ts';
declare const __VERSION__: string;
const VERSION = typeof __VERSION__ === 'string' ? __VERSION__ : 'dev';
const PAYLOAD_PORT = Number(process.env.CHEATSPECTER_PORT ?? 8744);
const log = (...args: unknown[]) => process.stderr.write(`[cheatspecter] ${args.join(' ')}\n`);
// The app's transport uses the browser's WebSocket. Newer Node versions have
// one built in; older ones get the same thing from the `ws` package.
if (typeof (globalThis as { WebSocket?: unknown }).WebSocket !== 'function') {
const ws = (await import('ws' as string)) as { WebSocket: unknown };
(globalThis as { WebSocket?: unknown }).WebSocket = ws.WebSocket;
}
const require = createRequire(import.meta.url);
const x86 = createX86(require('iced-x86'));
// ---- the console ---------------------------------------------------------------
class ToolError extends Error {}
let host = (process.env.CHEATSPECTER_HOST ?? '').trim();
let session: Session | null = null;
interface GameState {
game: Game;
name: string;
ctx: GameContext;
runner: TableRunner;
scan: Scan | null;
table: OwnTable | null;
}
let state: GameState | null = null;
function base(): string {
if (!host) {
throw new ToolError(
'No PS5 address is set. Call console_status with "host" set to the console\'s IP address (it is in the notification the CheatSpecter payload shows when it starts, e.g. 192.168.1.50).',
);
}
return `http://${host}:${PAYLOAD_PORT}`;
}
async function http(path: string, init?: RequestInit): Promise<Response> {
try {
return await fetch(base() + path, { ...init, signal: AbortSignal.timeout(30_000) });
} catch (e) {
if (e instanceof ToolError) throw e;
throw new ToolError(`The CheatSpecter payload at ${host}:${PAYLOAD_PORT} did not answer. Is the PS5 on, and is cheatspecter.elf loaded?`);
}
}
async function connect(): Promise<Session> {
if (session) return session;
const url = `${base().replace(/^http/, 'ws')}/ws`;
try {
const s = await Session.connect(null, url);
s.onLost = (reason) => {
log('connection lost:', reason);
if (session === s) {
session = null;
state = null;
}
};
session = s;
return s;
} catch (e) {
throw new ToolError(
`Could not reach the debugger through the payload at ${host}:${PAYLOAD_PORT} (${e instanceof Error ? e.message : String(e)}). Both ps5debug-NG and cheatspecter.elf need to be loaded on the PS5.`,
);
}
}
async function titleName(titleId: string): Promise<string> {
try {
const json = await http(`/api/appmeta/${titleId}/param.json`);
if (json.ok) return parseParamJson(await json.text())?.name ?? '';
const sfo = await http(`/api/appmeta/${titleId}/param.sfo`);
if (sfo.ok) return parseParamSfo(new Uint8Array(await sfo.arrayBuffer()))?.name ?? '';
} catch {
// The name is a nicety.
}
return '';
}
/** The running game, with everything tied to it. Rebuilt when another game (or another launch) is found. */
async function current(): Promise<GameState> {
const s = await connect();
const game = await s.currentGame();
if (!game) {
state = null;
throw new ToolError('No game is running on the PS5. Start one (launch_game can do it) and try again.');
}
if (state && state.game.pid === game.pid && state.game.titleId === game.titleId) return state;
const ctx = createGameContext({
pid: game.pid,
dbg: () => session!.main,
scanDbg: () => session!.scan,
x86: asAsync(x86),
// An assembler error ends the connection it was sent on, so each one gets its own.
assemble: async (at, text) => {
const dbg = await session!.openDebugger();
try {
return await dbg.assemble(at, text);
} finally {
if (!dbg.closed) dbg.close();
}
},
});
state = { game, name: await titleName(game.titleId), ctx, runner: new TableRunner(ctx), scan: null, table: null };
return state;
}
// ---- addresses and values --------------------------------------------------------
const hexAddr = (a: bigint) => '0x' + a.toString(16).toUpperCase();
interface Module {
name: string;
start: bigint;
end: bigint;
}
function modules(maps: MapEntry[]): Module[] {
const byName = new Map<string, Module>();
for (const m of maps) {
if (!m.name || m.name === '(aux)') continue;
const have = byName.get(m.name);
if (!have) byName.set(m.name, { name: m.name, start: m.start, end: m.end });
else {
if (m.start < have.start) have.start = m.start;
if (m.end > have.end) have.end = m.end;
}
}
return [...byName.values()].sort((a, b) => (a.start < b.start ? -1 : 1));
}
/** "0x1234", "1234", or "module+0x1234" ("game" is the game's own executable). */
async function address(st: GameState, text: unknown): Promise<bigint> {
if (typeof text !== 'string' || !text.trim()) throw new ToolError('An address is needed, e.g. "0x880012340" or "game+0x1A2B".');
const t = text.trim();
const plus = t.lastIndexOf('+');
const num = (h: string) => {
const clean = h.trim().replace(/^0x/i, '');
if (!/^[0-9a-f]+$/i.test(clean)) throw new ToolError(`"${h}" is not a hex number`);
return BigInt('0x' + clean);
};
if (plus < 0) return num(t);
const name = t.slice(0, plus).trim().toLowerCase();
const offset = num(t.slice(plus + 1));
if (name === 'game' || name === 'eboot' || name === 'eboot.bin') return (await resolveLocation(st.ctx, { kind: 'module', offset: '0' })) + offset;
const all = modules(await st.ctx.maps());
const found = all.find((m) => m.name.toLowerCase() === name) ?? all.find((m) => m.name.toLowerCase().startsWith(name));
if (!found) throw new ToolError(`No module called "${name}" is loaded. list_modules shows the names.`);
return found.start + offset;
}
/** An address the way a reader wants it: raw, plus which module it is in. */
async function where(st: GameState, a: bigint): Promise<string> {
const m = modules(await st.ctx.maps()).find((x) => a >= x.start && a < x.end);
return m ? `${hexAddr(a)} (${m.name}+0x${(a - m.start).toString(16).toUpperCase()})` : hexAddr(a);
}
function int(value: unknown, fallback: number, min: number, max: number): number {
const n = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : fallback;
if (!Number.isFinite(n)) return fallback;
return Math.max(min, Math.min(max, Math.floor(n)));
}
const str = (v: unknown): string => (typeof v === 'string' ? v : v === undefined || v === null ? '' : String(v));
// ---- long jobs -----------------------------------------------------------------
//
// A search over a big game takes longer than a tool call is allowed to. Long
// work runs in the background; the call waits a while and, if it is not done,
// says so, and scan_status picks the result up later.
interface Job {
what: string;
progress: string;
done: boolean;
result?: string;
error?: string;
promise: Promise<void>;
}
let job: Job | null = null;
const WAIT_MS = 40_000;
async function runJob(what: string, work: (progress: (text: string) => void) => Promise<string>): Promise<string> {
if (job && !job.done) throw new ToolError(`Still busy with: ${job.what} (${job.progress}). Call scan_status to wait for it.`);
const mine: Job = { what, progress: 'starting', done: false, promise: Promise.resolve() };
mine.promise = work((text) => (mine.progress = text)).then(
(result) => {
mine.result = result;
mine.done = true;
},
(e) => {
mine.error = e instanceof Error ? e.message : String(e);
mine.done = true;
},
);
job = mine;
return waitJob();
}
async function waitJob(): Promise<string> {
const mine = job;
if (!mine) return 'Nothing is running.';
await Promise.race([mine.promise, new Promise((r) => setTimeout(r, WAIT_MS))]);
if (!mine.done) return `Still running: ${mine.what} (${mine.progress}). Call scan_status to get the result.`;
if (job === mine) job = null;
if (mine.error !== undefined) throw new ToolError(mine.error);
return mine.result ?? '';
}
// ---- cheat files ---------------------------------------------------------------
async function loadTable(st: GameState, refresh = false): Promise<OwnTable> {
if (st.table && !refresh) return st.table;
const previous = st.table;
const list = await http(`/api/tables/${st.game.titleId}`);
const versions = list.ok ? (((await list.json()) as { versions?: string[] }).versions ?? []) : [];
const version = pickVersion(versions, st.game.version);
let table = emptyTable(st.game.titleId, st.game.version, st.name);
if (version) {
const res = await http(`/api/tables/${st.game.titleId}/${version}`);
if (res.ok) table = parseOwnTable(await res.text(), { own: true });
}
table = { ...table, titleId: st.game.titleId, version: st.game.version, name: table.name || st.name };
// The file does not record identities, so a cheat read again is matched to the one
// already known by name. That keeps track of which ones this session switched on.
for (const entry of table.entries) {
const known = previous?.entries.find((e) => e.name === entry.name);
if (known) entry.id = known.id;
}
st.table = table;
await st.runner.adopt(table.entries).catch(() => false);
return table;
}
async function saveTable(st: GameState, table: OwnTable): Promise<void> {
const res = await http(`/api/tables/${table.titleId}/${fileVersion(table.version)}`, {
method: 'PUT',
headers: { 'content-type': 'application/json' },
body: saveFileText(table),
});
if (!res.ok) throw new ToolError(`The console could not save the cheat file (HTTP ${res.status}).`);
st.table = table;
}
function findEntry(table: OwnTable, name: unknown): Entry {
const wanted = str(name).trim().toLowerCase();
const entry = table.entries.find((e) => e.name.toLowerCase() === wanted) ?? table.entries.find((e) => e.id === str(name));
if (!entry) throw new ToolError(`There is no cheat called "${str(name)}". list_cheats shows what exists.`);
return entry;
}
const CHEAT_FORMAT = `A cheat is a JSON object with "name", "type" and, optionally, "note".
Locations ("at") are one of:
{"kind":"signature","pattern":"45 8B 65 48 ?? 8D","offset":8} a byte pattern in the code plus a distance past it; survives restarts and most updates. Do not include the bytes the patch changes in the pattern.
{"kind":"module","offset":"0x3E5AB37"} an offset into the game's own executable (not other modules)
{"kind":"pointer","base":"0x2F4A10","offsets":["0x8","0x340"]} a pointer path starting in the game's executable
{"kind":"address","address":"0x880012340"} a raw address, valid only until the game restarts
Types:
patch {"at":…, "on":"909090", "off":"FF4B28", "more":[{"at":…,"on":"…","off":"…"}]} bytes to write and the originals; "more" adds further places to the same switch
value {"at":…, "valueType":"u32", "value":"9999", "freeze":true} set a value, or hold it there
inject {"at":…, "code":"mov dword ptr [rbx+0x390], 100", "placement":"before"} run assembly at a point in the code ("before", "after" or "replace" the instructions there)
call {"fn":…, "args":["0x1","2"]} call a function in the game
script {"code":"await cs.write(await cs.pointer('game+10100', 0x340), 'u32', 100);"} a small program`;
// ---- tools ---------------------------------------------------------------------
type Args = Record<string, unknown>;
interface Tool {
name: string;
description: string;
inputSchema: { type: 'object'; properties: Record<string, unknown>; required?: string[] };
run: (args: Args) => Promise<string>;
}
const S = (description: string, extra: Record<string, unknown> = {}) => ({ type: 'string', description, ...extra });
const N = (description: string) => ({ type: 'number', description });
const B = (description: string) => ({ type: 'boolean', description });
const ADDR = 'Hex address, or "module+offset" such as "game+0x1A2B" or "Il2CppUserAssemblies.prx+0x76769D".';
function describeHits(st: GameState, scan: Scan, hits: { address: bigint; value: Uint8Array; kind?: { id: string } }[]): string {
if (hits.length === 0) return '';
return hits
.map((h) => {
const kind = h.kind ? valueKind(h.kind.id) : scan.kind;
return `${hexAddr(h.address)} ${decodeValue(kind, h.value)}${scan instanceof AutoScan ? ` (${kind.id})` : ''}`;
})
.join('\n');
}
async function scanSummary(st: GameState, limit = 20): Promise<string> {
const scan = st.scan;
if (!scan) return 'No search is open.';
const n = scan.matches;
const dropped = scan instanceof AutoScan && scan.dropped.length ? `\nLeft out: ${scan.dropped.map((d) => `${d.kind.id} (${d.reason})`).join(', ')}` : '';
if (n === 0) return `0 matches after pass ${scan.passes}. The search is over; start a new one.${dropped}`;
const shown = n <= 500 ? describeHits(st, scan, await scan.hits(limit)) : '';
return `${n.toLocaleString('en-US')} matches after pass ${scan.passes}.${dropped}${shown ? `\nFirst ${Math.min(n, limit)} (address, value at the last pass):\n${shown}` : n > 500 ? '\nToo many to list; change the value in the game and narrow with scan_next.' : ''}`;
}
const tools: Tool[] = [
{
name: 'console_status',
description:
'Connects to the PS5 and reports what is running: debugger, firmware, the game on screen (name, title ID, version, process ID). Call this first. Pass "host" once to set or change the console\'s IP address.',
inputSchema: { type: 'object', properties: { host: S("The PS5's IP address, e.g. 192.168.1.50. Only needed the first time or when it changes.") } },
run: async (a) => {
const wanted = str(a.host).trim();
if (wanted && wanted !== host) {
if (!/^[a-z0-9.-]+$/i.test(wanted)) throw new ToolError('That does not look like an address.');
session?.close();
session = null;
state = null;
host = wanted;
}
const info = await http('/api/info');
const payload = info.ok ? ((await info.json()) as { version?: string }) : {};
const s = await connect();
const lines = [
`PS5 at ${host}: firmware ${s.firmware ? formatFirmware(s.firmware) : 'unknown'}, ${s.branding.brand || 'debugger (no name reported)'}`,
`CheatSpecter payload ${payload.version ?? 'unknown'}, MCP server ${VERSION}`,
];
const game = await s.currentGame();
if (!game) lines.push('No game is running.');
else {
const st = await current();
const table = await loadTable(st).catch(() => null);
lines.push(`Running: ${st.name || game.titleId} (${game.titleId}, version ${game.version || 'unknown'}, pid ${game.pid})`);
lines.push(table && table.entries.length ? `Cheat file ${tableFileName(game.titleId, game.version)}: ${table.entries.length} cheats (list_cheats)` : 'No cheats saved for this game yet.');
}
return lines.join('\n');
},
},
{
name: 'list_games',
description: 'Lists the games installed on the PS5 with name, platform (PS5 or PS4), size and title ID.',
inputSchema: { type: 'object', properties: {} },
run: async () => {
const res = await http('/api/library');
if (!res.ok) throw new ToolError(`The payload could not list the library (HTTP ${res.status}).`);
const { titles } = (await res.json()) as { titles: { id: string; meta: string; size: number; partial?: boolean; path: string }[] };
const rows = [];
for (const t of titles) {
const size = formatSize(t.size);
rows.push(`${t.id} ${t.meta === 'sfo' ? 'PS4' : 'PS5'} ${(size ? (t.partial ? 'over ' : '') + size : 'size unknown').padStart(12)} ${(await titleName(t.id)) || '(no name)'}`);
}
return rows.length ? rows.join('\n') : 'The console did not report any installed games.';
},
},
{
name: 'launch_game',
description: 'Starts a game on the PS5 by title ID. This closes whatever game is running, losing anything it has not saved, so confirm with the user first if a game is running.',
inputSchema: { type: 'object', properties: { title_id: S('e.g. PPSA07391') }, required: ['title_id'] },
run: async (a) => {
const id = str(a.title_id).trim().toUpperCase();
if (!/^[A-Z]{4}\d{5}$/.test(id)) throw new ToolError('A title ID looks like PPSA07391.');
const res = await http(`/api/launch/${id}`, { method: 'POST' });
const doc = (await res.json().catch(() => ({}))) as { ok?: boolean; error?: string; code?: string };
if (!res.ok || !doc.ok) throw new ToolError(`${doc.error ?? `The console did not start it (HTTP ${res.status})`}${doc.code ? ` (${doc.code})` : ''}`);
state = null;
return `Asked the PS5 to start ${id}. It takes a few seconds; console_status shows when it is running.`;
},
},
{
name: 'list_modules',
description: "Lists the running game's loaded modules (its executable and libraries) with their address ranges, and how much writable memory there is.",
inputSchema: { type: 'object', properties: {} },
run: async () => {
const st = await current();
const maps = await st.ctx.maps(true);
const writable = scannableRegions(maps).reduce((n, r) => n + r.length, 0);
// Code modules only: the map also names hundreds of stacks and shared-memory blocks nobody patches.
const code = modules(maps).filter((m) => /^executable$|\.(s?prx|elf|self|bin)$/i.test(m.name));
const rows = code.map((m) => `${hexAddr(m.start).padEnd(14)} ${formatSize(Number(m.end - m.start)).padStart(9)} ${m.name}`);
return `${rows.join('\n')}\n\nWritable memory a search covers: ${formatSize(writable)}`;
},
},
{
name: 'read_memory',
description: 'Reads memory from the running game. Returns a hex dump, or decoded values when "as" is a type.',
inputSchema: {
type: 'object',
properties: {
address: S(ADDR),
length: N('Bytes to read (default 64, at most 4096). With "as", the number of values instead.'),
as: S('Decode as this type instead of a hex dump.', { enum: VALUE_KINDS.map((k) => k.id) }),
},
required: ['address'],
},
run: async (a) => {
const st = await current();
const at = await address(st, a.address);
if (a.as) {
const kind = valueKind(str(a.as));
const count = int(a.length, 1, 1, 512);
const bytes = await st.ctx.dbg().read(st.game.pid, at, count * kind.size);
const rows = [];
for (let i = 0; i < count; i++) rows.push(`${hexAddr(at + BigInt(i * kind.size))} ${decodeValue(kind, bytes.subarray(i * kind.size, (i + 1) * kind.size))}`);
return rows.join('\n');
}
const bytes = await st.ctx.dbg().read(st.game.pid, at, int(a.length, 64, 1, 4096));
const rows = [];
for (let i = 0; i < bytes.length; i += 16) {
const line = bytes.subarray(i, i + 16);
const text = [...line].map((b) => (b >= 0x20 && b < 0x7f ? String.fromCharCode(b) : '.')).join('');
rows.push(`${hexAddr(at + BigInt(i)).padEnd(14)} ${bytesToHex(line, ' ').padEnd(47)} ${text}`);
}
return rows.join('\n');
},
},
{
name: 'write_memory',
description: 'Writes to the running game\'s memory: either raw bytes ("hex") or a typed value ("value" with "type"). Code can be patched this way too. Read the bytes first so they can be put back.',
inputSchema: {
type: 'object',
properties: {
address: S(ADDR),
hex: S('Bytes to write, e.g. "90 90 90".'),
value: S('A value to write, e.g. "9999" or "0.5".'),
type: S('The type of "value".', { enum: VALUE_KINDS.map((k) => k.id) }),
},
required: ['address'],
},
run: async (a) => {
const st = await current();
const at = await address(st, a.address);
const bytes = a.hex ? hexToBytes(str(a.hex)) : a.value !== undefined ? encodeValue(valueKind(str(a.type) || 'u32'), str(a.value)) : null;
if (!bytes || bytes.length === 0) throw new ToolError('Give either "hex" or "value" (with "type").');
const before = await st.ctx.dbg().read(st.game.pid, at, bytes.length);
await st.ctx.dbg().write(st.game.pid, at, bytes);
const after = await st.ctx.dbg().read(st.game.pid, at, bytes.length);
return `${hexAddr(at)}: was ${bytesToHex(before, ' ')}, now ${bytesToHex(after, ' ')}${bytesToHex(after) === bytesToHex(bytes) ? '' : ' (the write did not stick)'}`;
},
},
{
name: 'scan_start',
description:
'Starts a search of the game\'s writable memory for a value. Follow with scan_next after the value changes in the game, until few matches remain. Type "auto" tries 4 bytes, float and double at once. A big game takes over a minute; if the answer is "still running", call scan_status.',
inputSchema: {
type: 'object',
properties: {
type: S('Value type.', { enum: ['auto', ...VALUE_KINDS.map((k) => k.id)] }),
compare: S('How to compare (default "exact").', { enum: COMPARE_KINDS.filter((c) => c.first && c.id !== 'unknown').map((c) => c.id) }),
value: S('The value, e.g. "1137". For "between", the lower bound.'),
value2: S('Upper bound for "between".'),
min: S('Only search addresses at or above this (hex).'),
max: S('Only search addresses below this (hex).'),
},
required: ['type', 'value'],
},
run: async (a) => {
const st = await current();
const cmp = compareKind(str(a.compare) || 'exact');
if (!cmp.first || cmp.id === 'unknown') throw new ToolError('A first search needs a value: exact, bigger, smaller or between.');
let regions: ScanRegion[] = scannableRegions(await st.ctx.maps(true));
if (a.min) regions = regions.filter((r) => r.start >= BigInt(str(a.min).startsWith('0x') ? str(a.min) : '0x' + str(a.min)));
if (a.max) regions = regions.filter((r) => r.start < BigInt(str(a.max).startsWith('0x') ? str(a.max) : '0x' + str(a.max)));
if (regions.length === 0) throw new ToolError('There is no writable memory in that range.');
const total = regions.reduce((n, r) => n + r.length, 0);
await st.scan?.end().catch(() => undefined);
st.scan = null;
let scan: Scan;
let encoded: Uint8Array = new Uint8Array(0);
if (str(a.type) === 'auto') {
const all = new AutoScan(() => session!.scan, st.game.pid);
all.input(str(a.value), str(a.value2));
scan = all;
} else {
const kind = valueKind(str(a.type));
const one = encodeValue(kind, str(a.value));
encoded = cmp.inputs === 2 ? Uint8Array.from([...one, ...encodeValue(kind, str(a.value2))]) : one;
scan = new ScanSession(() => session!.scan, st.game.pid, kind);
}
return runJob(`searching ${formatSize(total)}`, async (progress) => {
await scan.first(regions, cmp, encoded, (p) => progress(`${Math.round(p.fraction * 100)}%, ${p.matches.toLocaleString('en-US')} matches so far${p.detail ? ' ' + p.detail : ''}`));
st.scan = scan;
return scanSummary(st);
});
},
},
{
name: 'scan_next',
description:
'Narrows the open search. Use "exact" with the new value, or increased / decreased / changed / unchanged when only the direction is known. Running "unchanged" while nothing happens in the game clears out values that move by themselves.',
inputSchema: {
type: 'object',
properties: {
compare: S('How the value compares now.', { enum: COMPARE_KINDS.filter((c) => c.id !== 'unknown').map((c) => c.id) }),
value: S('The value now, for exact / bigger / smaller / between.'),
value2: S('Upper bound for "between".'),
},
required: ['compare'],
},
run: async (a) => {
const st = await current();
const scan = st.scan;
if (!scan) throw new ToolError('No search is open. Start one with scan_start.');
const cmp = compareKind(str(a.compare));
let encoded: Uint8Array = new Uint8Array(0);
if (scan instanceof AutoScan) scan.input(str(a.value), str(a.value2));
else if (cmp.inputs > 0) {
const one = encodeValue(scan.kind, str(a.value));
encoded = cmp.inputs === 2 ? Uint8Array.from([...one, ...encodeValue(scan.kind, str(a.value2))]) : one;
} else encoded = new Uint8Array(scan.kind.size);
return runJob(`checking ${scan.matches.toLocaleString('en-US')} candidates`, async (progress) => {
await scan.next(cmp, encoded, (p) => progress(`${Math.round(p.fraction * 100)}%`));
return scanSummary(st);
});
},
},
{
name: 'scan_status',
description: 'Waits for a search that was still running and returns its result, or shows the open search\'s matches with their current values.',
inputSchema: { type: 'object', properties: { limit: N('How many matches to list (default 20, at most 200).') } },
run: async (a) => {
if (job) return waitJob();
const st = await current();
const scan = st.scan;
if (!scan) return 'No search is open.';
const limit = int(a.limit, 20, 1, 200);
const hits = await scan.hits(limit);
const rows = [];
for (const h of hits) {
const kind = h.kind ?? scan.kind;
const now = await st.ctx.dbg().read(st.game.pid, h.address, kind.size);
rows.push(`${hexAddr(h.address)} was ${decodeValue(kind, h.value)} now ${decodeValue(kind, now)}${scan instanceof AutoScan ? ` (${kind.id})` : ''}`);
}
return `${scan.matches.toLocaleString('en-US')} matches after pass ${scan.passes}.\n${rows.join('\n')}`;
},
},
{
name: 'watch',
description:
'Finds the code that touches a value: sets a hardware watchpoint for a few seconds and reports each instruction that wrote to (or read) the address, with registers. The user has to make the value change in the game while this runs. The game hitches briefly on each hit.',
inputSchema: {
type: 'object',
properties: {
address: S(ADDR),
size: N('Bytes to watch: 1, 2, 4 or 8 (default 4).'),
kind: S('"write" (default) or "readwrite".', { enum: ['write', 'readwrite'] }),
seconds: N('How long to watch (default 20, at most 35).'),
max_hits: N('Stop after this many hits (default 40). Keep it low for values that change constantly.'),
},
required: ['address'],
},
run: async (a) => {
const st = await current();
const at = await address(st, a.address);
const size = int(a.size, 4, 1, 8);
if (![1, 2, 4, 8].includes(size)) throw new ToolError('Size must be 1, 2, 4 or 8.');
const seconds = int(a.seconds, 20, 1, 35);
const tracer = new Tracer(st.ctx, { openDebugger: () => session!.openDebugger(), openEvents: () => session!.openEvents() });
tracer.maxHits = int(a.max_hits, 40, 1, 400);
let ended: string | undefined;
let finished = false;
await tracer.start(at, size as 1 | 2 | 4 | 8, str(a.kind) === 'readwrite' ? 'readwrite' : 'write', (_hits, why) => {
if (why !== undefined || !tracer.running) {
ended = why;
finished = true;
}
});
const until = Date.now() + seconds * 1000;
while (!finished && Date.now() < until && tracer.total < tracer.maxHits) await new Promise((r) => setTimeout(r, 150));
await tracer.stop().catch(() => undefined);
const hits = tracer.list();
if (hits.length === 0) return `Nothing touched ${hexAddr(at)} in ${seconds} seconds.${ended ? ' ' + ended : ''} The value has to change in the game while this runs.`;
const out = [`${tracer.total} hits from ${hits.length} place${hits.length === 1 ? '' : 's'} in the code:`];
for (const h of hits) {
const insn = h.insn;
out.push('');
out.push(`${insn ? await where(st, insn.address) : `before ${await where(st, h.rip)}`} x${h.count}`);
if (insn) out.push(` ${bytesToHex(insn.bytes, ' ')} ${insn.text}`);
out.push(` ${Object.entries(h.regs).filter(([k]) => !['rflags', 'cs', 'ss', 'err', 'trapno', 'fs', 'gs', 'es', 'ds'].includes(k)).map(([k, v]) => `${k}=${(v as bigint).toString(16)}`).join(' ')}`);
}
if (ended) out.push('', ended);
return out.join('\n');
},
},
{
name: 'disassemble',
description: 'Disassembles code in the running game (x86-64, Intel syntax). Also suggests a byte pattern that locates the first instruction, for use in a cheat.',
inputSchema: { type: 'object', properties: { address: S(ADDR), count: N('Instructions to show (default 24, at most 200).') }, required: ['address'] },
run: async (a) => {
const st = await current();
const at = await address(st, a.address);
const count = int(a.count, 24, 1, 200);
const bytes = await st.ctx.dbg().read(st.game.pid, at, Math.min(4096, count * 15));
const insns = x86.disassemble(bytes, at, count);
const rows = insns.map((i) => `${hexAddr(i.address).padEnd(14)} ${bytesToHex(i.bytes, ' ').padEnd(32)} ${i.text}`);
let sig = '';
try {
sig = signatureFromCode(insns, 12).text;
} catch {
// No pattern to suggest for this stretch.
}
return `${await where(st, at)}\n${rows.join('\n')}${sig ? `\n\nPattern for the start of this code: ${sig} (check it with find_pattern)` : ''}`;
},
},
{
name: 'find_pattern',
description: 'Searches the game\'s code for a byte pattern ("89 81 ?? ?? 00 00", ?? matches anything) and says where it is and whether it is unique. A cheat should only use a unique pattern.',
inputSchema: { type: 'object', properties: { pattern: S('Bytes in hex with ?? wildcards.') }, required: ['pattern'] },
run: async (a) => {
const st = await current();
const match = await findPattern(st.ctx, str(a.pattern));
if (!match) return 'Not found in the game\'s code.';
return `${await where(st, match.address)} ${match.unique ? 'unique' : 'NOT unique (matches in more than one place; lengthen the pattern)'}`;
},
},
{
name: 'list_cheats',
description: "Shows the cheats saved for the running game (the .cspecter file on the PS5, the same one the CheatSpecter web app loads), and which are switched on.",
inputSchema: { type: 'object', properties: { json: B('Also include each cheat as JSON, for editing.') } },
run: async (a) => {
const st = await current();
const table = await loadTable(st, true);
if (table.entries.length === 0) return `No cheats saved for ${st.name || st.game.titleId} yet. add_cheat creates one.`;
const rows = table.entries.map((e) => {
const status = isAction(e) ? 'action' : st.runner.isOn(e.id) ? 'ON' : 'off';
const { id: _id, unreviewed: _u, ...rest } = e;
return `[${status}] ${e.name}: ${describeEntry(e)}${e.note ? `\n ${e.note}` : ''}${a.json ? `\n ${JSON.stringify(rest)}` : ''}`;
});
return `${tableFileName(table.titleId, table.version)} for ${table.name || table.titleId}:\n${rows.join('\n')}`;
},
},
{
name: 'add_cheat',
description: `Saves a cheat for the running game to its .cspecter file on the PS5, replacing any cheat with the same name. It then shows up as a switch in the CheatSpecter web app. Test with set_cheat afterwards.\n\n${CHEAT_FORMAT}`,
inputSchema: { type: 'object', properties: { cheat: { type: 'object', description: 'The cheat, in the format described above.' } }, required: ['cheat'] },
run: async (a) => {
const st = await current();
const raw = a.cheat && typeof a.cheat === 'object' ? (a.cheat as Record<string, unknown>) : null;
if (!raw || !str(raw.name).trim()) throw new ToolError('The cheat needs at least a "name" and a "type".');
// Through the same checks as a file the app loads.
const probe = parseOwnTable(JSON.stringify({ format: 'cheatspecter', formatVersion: 1, game: {}, cheats: [{ ...raw, reviewed: true }] }), { own: true });
const entry = probe.entries[0];
if (!entry) throw new ToolError(`That is not a cheat CheatSpecter understands.\n\n${CHEAT_FORMAT}`);
const table = await loadTable(st);
const old = table.entries.find((e) => e.name.toLowerCase() === entry.name.toLowerCase());
if (old && st.runner.isOn(old.id)) await st.runner.disable(old).catch(() => undefined);
entry.id = old?.id ?? newId();
const entries = old ? table.entries.map((e) => (e === old ? entry : e)) : [...table.entries, entry];
await saveTable(st, { ...table, entries });
return `Saved "${entry.name}" (${describeEntry(entry)}) to ${tableFileName(table.titleId, table.version)}. ${old ? 'It replaced the cheat of the same name. ' : ''}It is off; set_cheat switches it on.`;
},
},
{
name: 'remove_cheat',
description: 'Deletes a cheat from the running game\'s file, switching it off first.',
inputSchema: { type: 'object', properties: { name: S('The cheat\'s name.') }, required: ['name'] },
run: async (a) => {
const st = await current();
const table = await loadTable(st);
const entry = findEntry(table, a.name);
if (st.runner.isOn(entry.id)) await st.runner.disable(entry);
await saveTable(st, { ...table, entries: table.entries.filter((e) => e !== entry) });
return `Removed "${entry.name}".`;
},
},
{
name: 'set_cheat',
description: 'Switches a saved cheat on or off in the running game (or runs it, if it is a one-off action). A cheat that does not match the game\'s code is refused unless "force" is set.',
inputSchema: { type: 'object', properties: { name: S('The cheat\'s name.'), on: B('true to switch on or run, false to switch off.'), force: B('Apply even if the original bytes do not match.') }, required: ['name', 'on'] },
run: async (a) => {
const st = await current();
const table = await loadTable(st);
const entry = findEntry(table, a.name);
if (entry.type === 'script') throw new ToolError('Scripts run in the CheatSpecter web app, not here.');
if (a.on === false || a.on === 'false') {
if (!st.runner.isOn(entry.id)) return `"${entry.name}" is already off.`;
await st.runner.disable(entry);
return `"${entry.name}" is off.`;
}
try {
await st.runner.enable(entry, { force: a.force === true });
} catch (e) {
if (e instanceof Error && e.name === 'MismatchError') {
throw new ToolError(`"${entry.name}" does not match this version of the game (the bytes it expects are not there), so nothing was changed.`);
}
throw e;
}
const result = st.runner.result(entry.id);
return isAction(entry) ? `Ran "${entry.name}".${result ? ' ' + result : ''}` : `"${entry.name}" is on.`;
},
},
];
// ---- protocol ------------------------------------------------------------------
const send = (message: unknown) => process.stdout.write(JSON.stringify(message) + '\n');
/** Tool calls run one at a time: they share one console connection. */
let queue: Promise<void> = Promise.resolve();
async function handle(message: { id?: number | string; method?: string; params?: Record<string, unknown> }): Promise<void> {
const { id, method, params } = message;
const reply = (result: unknown) => id !== undefined && send({ jsonrpc: '2.0', id, result });
const fail = (code: number, text: string) => id !== undefined && send({ jsonrpc: '2.0', id, error: { code, message: text } });
switch (method) {
case 'initialize':
reply({
protocolVersion: typeof params?.protocolVersion === 'string' ? params.protocolVersion : '2024-11-05',
capabilities: { tools: {} },
serverInfo: { name: 'cheatspecter', version: VERSION },
instructions:
'Tools for a jailbroken PS5 running the CheatSpecter payload, for single-player games the user owns. Start with console_status. The usual way to make a cheat: scan_start for a value the user can see, have them change it in the game, scan_next until few matches remain, watch the address while they change it again to find the code, disassemble around it, try a change with write_memory, then add_cheat so it becomes a switch in the CheatSpecter app. Prefer cheats located by a unique byte pattern.',
});
return;
case 'ping':
reply({});
return;
case 'tools/list':
reply({ tools: tools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) });
return;
case 'tools/call': {
const tool = tools.find((t) => t.name === params?.name);
if (!tool) {
fail(-32602, `Unknown tool: ${String(params?.name)}`);
return;
}
const run = async () => {
try {
const text = await tool.run((params?.arguments as Args) ?? {});
reply({ content: [{ type: 'text', text }] });
} catch (e) {
if (!(e instanceof ToolError)) log(`${tool.name} failed:`, e instanceof Error ? (e.stack ?? e.message) : String(e));
reply({ content: [{ type: 'text', text: e instanceof Error ? e.message : String(e) }], isError: true });
}
};
queue = queue.then(run, run);
return;
}
default:
// Notifications need no answer; unknown requests get the standard error.
if (id !== undefined) fail(-32601, `Method not found: ${String(method)}`);
}
}
const lines = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
lines.on('line', (line) => {
if (!line.trim()) return;
let message;
try {
message = JSON.parse(line);
} catch {
send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
return;
}
void handle(message);
});
lines.on('close', () => {
session?.close();
// Let anything in flight finish writing, then leave.
void queue.finally(() => process.exit(0));
});
log(`MCP server ${VERSION} ready${host ? `, console at ${host}` : ', no console address set yet'}`);
+5
View File
@@ -0,0 +1,5 @@
{
"extends": "../tsconfig.json",
"compilerOptions": { "types": ["node"], "lib": ["ES2022", "DOM", "DOM.Iterable"] },
"include": ["server.ts"]
}
+974
View File
@@ -0,0 +1,974 @@
// A pretend PS5 running ps5debug-NG, for developing and testing without a
// console. It speaks the same wire protocol on a TCP port and simulates one
// small "game" whose memory you can scan and patch.
//
// The handlers follow the debugger's own source (scan.c, proc.c, auth.c,
// console.c in ps5debug-NG v1.3.2) closely, including the multi-status
// replies, so the client is exercised against the real framing.
//
// node mock/mock-ps5.mjs # TCP 7440, UDP discovery 10100
import net from 'node:net';
import dgram from 'node:dgram';
import { pathToFileURL } from 'node:url';
export const MOCK_TCP_PORT = 7440;
export const MOCK_UDP_PORT = 10100;
const PACKET_MAGIC = 0xffaabbcc;
const ST = { SUCCESS: 0x40000000, ERROR: 0xf0000002, DATA_NULL: 0xf0000003 };
const bitswap32 = (x) => (((x >>> 1) & 0x55555555) | ((x << 1) & 0xaaaaaaaa)) >>> 0;
// ---- the pretend game -------------------------------------------------------
export const GAME = {
pid: 91,
titleId: 'PPSA99999',
contentId: 'UP9999-PPSA99999_00-SPECTERTESTGAME0',
name: 'eboot.bin',
version: '01.000.000',
imageBase: 0x4b3a8c0000n,
heapBase: 0x880000000n,
// Offsets into the image. Each holds a short instruction the game "runs".
code: {
healthDrain: { offset: 0x1000, bytes: Buffer.from('898190030000', 'hex') },
ammoSpend: { offset: 0x2040, bytes: Buffer.from('FF4B28', 'hex') },
goldSpend: { offset: 0x30a0, bytes: Buffer.from('F30F5CC1', 'hex') },
scoreAdd: { offset: 0x3200, bytes: Buffer.from('8387808803000A', 'hex') },
},
// Functions the mock can "call": add(a, b) and setGold(amount).
funcs: { add: 0x4000, setGold: 0x4100 },
// Offsets into the heap. The player object starts at 0x12000.
player: 0x12000,
vars: { health: 0x12340, ammo: 0x12344, unlocks: 0x12400, gold: 0x20010, score: 0x38880 },
// Static pointers in the image's data segment (imageBase + 0x10000 + offset):
// [data + 0x100] -> player
// [[data + 0x200] + 0x8] -> player
dataBase: 0x4b3a8d0000n,
statics: { player: 0x100, world: 0x200 },
world: 0x31000,
};
function createGame() {
// int3 padding with real instructions at the interesting offsets, each
// followed by a ret, so it disassembles cleanly.
const image = Buffer.alloc(0x10000, 0xcc);
for (const c of Object.values(GAME.code)) {
c.bytes.copy(image, c.offset);
image[c.offset + c.bytes.length] = 0xc3;
}
Buffer.from('488D0437C3', 'hex').copy(image, GAME.funcs.add); // lea rax,[rdi+rsi]; ret
Buffer.from('F3480F2AC7C3', 'hex').copy(image, GAME.funcs.setGold); // cvtsi2ss xmm0,rdi; ret
const heap = Buffer.alloc(0x40000);
heap.writeUInt32LE(100, GAME.vars.health);
heap.writeUInt32LE(30, GAME.vars.ammo);
heap.writeFloatLE(2500, GAME.vars.gold);
heap.writeUInt32LE(0, GAME.vars.score);
// Decoys, so a first scan for 100 finds more than one hit.
for (const off of [0x400, 0x9000, 0x1a2b0, 0x30000, 0x3fff0]) heap.writeUInt32LE(100, off);
const stack = Buffer.alloc(0x8000);
const data = Buffer.alloc(0x4000);
data.writeBigUInt64LE(GAME.heapBase + BigInt(GAME.player), GAME.statics.player);
data.writeBigUInt64LE(GAME.heapBase + BigInt(GAME.world), GAME.statics.world);
heap.writeBigUInt64LE(GAME.heapBase + BigInt(GAME.player), GAME.world + 8);
const regions = [
{ name: 'executable', start: GAME.imageBase, buf: image, prot: 5 },
{ name: 'executable', start: GAME.dataBase, buf: data, prot: 3 },
{ name: 'libkernel.sprx', start: 0x800000000n, buf: Buffer.alloc(0x4000, 0x90), prot: 5 },
{ name: '', start: GAME.heapBase, buf: heap, prot: 3 },
{ name: 'main stack', start: 0x7ef000000n, buf: stack, prot: 3 },
];
const intact = (c) => image.subarray(c.offset, c.offset + c.bytes.length).equals(c.bytes);
// The "game loop": each tick runs the instructions that are still there.
// NOP one out and the matching value stops moving. Each step names the
// memory it writes, so a debugger watchpoint can stop the game right after.
const steps = [
{
code: GAME.code.healthDrain,
at: GAME.vars.health,
size: 4,
run() {
const h = heap.readUInt32LE(GAME.vars.health);
heap.writeUInt32LE(h <= 1 ? 100 : h - 1, GAME.vars.health);
},
},
{
code: GAME.code.ammoSpend,
at: GAME.vars.ammo,
size: 4,
run() {
const a = heap.readUInt32LE(GAME.vars.ammo);
heap.writeUInt32LE(a === 0 ? 30 : a - 1, GAME.vars.ammo);
},
},
{
code: GAME.code.goldSpend,
at: GAME.vars.gold,
size: 4,
run() {
const g = heap.readFloatLE(GAME.vars.gold);
heap.writeFloatLE(g < 10 ? 2500 : g - 2.5, GAME.vars.gold);
},
},
{
code: GAME.code.scoreAdd,
at: GAME.vars.score,
size: 4,
run() {
heap.writeUInt32LE((heap.readUInt32LE(GAME.vars.score) + 10) >>> 0, GAME.vars.score);
},
},
];
/**
* @param {(step: {address: bigint, size: number, rip: bigint}) => boolean} [onWrite]
* called after each write; returning true stops the rest of the frame
*/
function tick(onWrite) {
for (const step of steps) {
if (!intact(step.code)) continue;
step.run();
const stop = onWrite?.({
address: GAME.heapBase + BigInt(step.at),
size: step.size,
rip: GAME.imageBase + BigInt(step.code.offset + step.code.bytes.length),
});
if (stop) return;
}
}
function locate(addr, len) {
for (const r of regions) {
const end = r.start + BigInt(r.buf.length);
if (addr >= r.start && addr + BigInt(len) <= end) return { r, off: Number(addr - r.start) };
}
return null;
}
/** Like the console: unreadable memory comes back as zeros. */
function read(addr, len) {
const out = Buffer.alloc(len);
for (const r of regions) {
const rEnd = r.start + BigInt(r.buf.length);
const lo = addr > r.start ? addr : r.start;
const hi = addr + BigInt(len) < rEnd ? addr + BigInt(len) : rEnd;
if (lo < hi) r.buf.copy(out, Number(lo - addr), Number(lo - r.start), Number(hi - r.start));
}
return out;
}
function write(addr, data) {
const hit = locate(addr, data.length);
if (!hit) return false;
data.copy(hit.r.buf, hit.off);
return true;
}
let nextAlloc = 0x200000000n;
/** Maps new memory. With a hint it lands on the first free page at or above it. */
function alloc(length, hint) {
const size = Math.max(0x4000, (length + 0x3fff) & ~0x3fff);
let start;
if (hint) {
start = (hint + 0x3fffn) & ~0x3fffn;
const overlaps = (st) => regions.some((r) => st < r.start + BigInt(r.buf.length) && r.start < st + BigInt(size));
while (overlaps(start)) start += 0x4000n;
} else {
start = nextAlloc;
nextAlloc += BigInt(size) + 0x100000n;
}
regions.push({ name: '', start, buf: Buffer.alloc(size), prot: 7, allocated: true });
return start;
}
function free(addr) {
const i = regions.findIndex((r) => r.allocated && r.start === addr);
if (i < 0) return false;
regions.splice(i, 1);
return true;
}
return { regions, read, write, tick, heap, image, data, alloc, free };
}
// ---- scan comparison (scan_compare.c) --------------------------------------
const SIZES = [1, 1, 2, 2, 4, 4, 8, 8, 4, 8];
function num(valType, buf, off) {
switch (valType) {
case 0: return buf.readUInt8(off);
case 1: return buf.readInt8(off);
case 2: return buf.readUInt16LE(off);
case 3: return buf.readInt16LE(off);
case 4: return buf.readUInt32LE(off);
case 5: return buf.readInt32LE(off);
case 6: return buf.readBigUInt64LE(off);
case 7: return buf.readBigInt64LE(off);
case 8: return buf.readFloatLE(off);
case 9: return buf.readDoubleLE(off);
default: throw new Error('bad value type');
}
}
function fuzzyEqual(a, b, min) {
if (a === b) return true;
const diff = Math.abs(a - b);
if (a === 0 || b === 0) return min * 1e-6 > diff;
const sum = Math.abs(a) + Math.abs(b);
if (min > sum) return min * 1e-6 > diff;
return 1e-6 > diff / sum;
}
function compareValues(cmp, valType, size, scan, mem, memOff, prev, prevOff) {
if (cmp >= 4 && cmp <= 10 && !prev) return false;
const m = () => num(valType, mem, memOff);
const s = () => num(valType, scan, 0);
const p = () => num(valType, prev, prevOff);
switch (cmp) {
case 0:
if (valType === 8) return scan.readUInt32LE(0) === 0 ? mem.readUInt32LE(memOff) === 0 : fuzzyEqual(s(), m(), 1.17549435e-38);
if (valType === 9) return scan.readBigUInt64LE(0) === 0n ? mem.readBigUInt64LE(memOff) === 0n : fuzzyEqual(s(), m(), 2.2250738585072014e-308);
return scan.subarray(0, size).equals(mem.subarray(memOff, memOff + size));
case 2: return m() > s();
case 3: return m() < s();
case 4: return m() >= s() && m() <= p(); // prev points at the upper bound
case 5: return m() > p();
case 7: return m() < p();
case 9: return !mem.subarray(memOff, memOff + size).equals(prev.subarray(prevOff, prevOff + size));
case 10: return mem.subarray(memOff, memOff + size).equals(prev.subarray(prevOff, prevOff + size));
default: return false;
}
}
// rescans: g_cmptype_needs_value / _extra / _previous
const NEEDS_VALUE = [1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0];
const NEEDS_EXTRA = [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
const NEEDS_PREV = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
// ---- auth (auth.c) ----------------------------------------------------------
function makeLfsr(a, b, c, d) {
let s1 = a, s2 = b, s3 = c, s4 = d;
return () => {
s1 = (((s1 << 18) & 0xfff80000) ^ ((s1 ^ (s1 << 6)) >>> 13)) >>> 0;
s2 = (((s2 << 2) & 0xffffffe0) ^ ((s2 ^ (s2 << 2)) >>> 27)) >>> 0;
s3 = (((s3 << 7) & 0xfffff800) ^ ((s3 ^ (s3 << 13)) >>> 21)) >>> 0;
s4 = (((s4 << 13) & 0xfff00000) ^ ((s4 ^ (s4 << 3)) >>> 12)) >>> 0;
return (s1 ^ s2 ^ s3 ^ s4) >>> 0;
};
}
function keystream() {
const next = makeLfsr(200, 300, 400, 500);
const out = Buffer.alloc(256);
for (let i = 0; i < 256; i++) out[i] = next() & 0xff;
return out;
}
// ---- a stand-in for the console's assembler ---------------------------------------
/**
* The real payload embeds Keystone. The mock understands just enough to test
* the plumbing: nop, ret, int3, and raw bytes via "db" / ".byte".
*/
function mockAssemble(text) {
const out = [];
let count = 0;
for (const raw of text.split(/[\n;]/)) {
const line = raw.replace(/(\/\/|#).*$/, '').trim().toLowerCase();
if (!line || /^[a-z_][a-z0-9_]*:$/.test(line)) continue;
if (line === 'nop') out.push(0x90);
else if (line === 'ret') out.push(0xc3);
else if (line === 'int3') out.push(0xcc);
else if (/^(db|\.byte)\s/.test(line)) {
for (const tok of line.replace(/^(db|\.byte)\s+/, '').split(/[\s,]+/).filter(Boolean)) {
const v = Number(tok.endsWith('h') ? '0x' + tok.slice(0, -1) : tok);
if (!Number.isInteger(v) || v < 0 || v > 255) return { error: `invalid operand (${tok})` };
out.push(v);
}
} else return { error: `invalid mnemonic (${line.split(/\s/)[0]})` };
count++;
}
return { bytes: Buffer.from(out), count };
}
// ---- socket reader ----------------------------------------------------------
class Reader {
constructor(sock) {
this.chunks = [];
this.avail = 0;
this.waiter = null;
this.ended = false;
sock.on('data', (d) => {
this.chunks.push(d);
this.avail += d.length;
this.pump();
});
const end = () => {
this.ended = true;
this.pump();
};
sock.on('end', end);
sock.on('close', end);
sock.on('error', end);
}
read(n) {
return new Promise((resolve, reject) => {
this.waiter = { n, resolve, reject };
this.pump();
});
}
pump() {
const w = this.waiter;
if (!w) return;
if (this.avail >= w.n) {
const all = Buffer.concat(this.chunks);
this.chunks = [all.subarray(w.n)];
this.avail -= w.n;
this.waiter = null;
w.resolve(all.subarray(0, w.n));
} else if (this.ended) {
this.waiter = null;
w.reject(new Error('closed'));
}
}
}
// ---- server -----------------------------------------------------------------
/**
* @param {object} [opts]
* @param {number} [opts.tcpPort]
* @param {number} [opts.udpPort] 0 disables discovery
* @param {boolean} [opts.tick] run the game loop (default true)
* @param {boolean} [opts.legacy] behave like the original ps5debug: no capability level
* @param {boolean} [opts.noBranding] never answer BRANDING / FW_VERSION, like a payload that predates them
* @param {boolean} [opts.noNearAlloc] hinted allocations fail, forcing far code caves
* @param {number} [opts.eventPort] where the debugger connects back on attach (real consoles use 755)
* @param {number} [opts.scanDelayMs] pause per scanned range, so progress is visible in the demo
*/
export function startMock(opts = {}) {
const tcpPort = opts.tcpPort ?? MOCK_TCP_PORT;
const udpPort = opts.udpPort ?? MOCK_UDP_PORT;
const game = createGame();
const state = { authed: false, notifications: [], foreground: true };
const authLfsr = makeLfsr(0x12345678, 0x9abcdef0, 0x0f1e2d3c, 0x4b5a6978);
// One debugger session for the whole console, as on the real thing.
const debug = { owner: null, events: null, watch: [null, null, null, null], stopped: false };
const debugTeardown = () => {
if (debug.events) debug.events.destroy();
debug.owner = null;
debug.events = null;
debug.watch = [null, null, null, null];
debug.stopped = false;
};
/** Runs one frame of the game, honouring watchpoints. */
const tick = () => {
if (debug.stopped) return;
game.tick((w) => {
if (!debug.owner || !debug.events) return false;
const hit = debug.watch.some((wp) => wp && wp.kind !== 0 && w.address < wp.address + BigInt(wp.size) && wp.address < w.address + BigInt(w.size));
if (!hit) return false;
// The 1184-byte stop report (PROTOCOL.md 1.9): thread, status, name, registers.
const pkt = Buffer.alloc(1184);
pkt.writeUInt32LE(100123, 0);
pkt.writeUInt32LE((5 << 8) | 0x7f, 4); // stopped by SIGTRAP
pkt.write('MainThread', 8, 39);
pkt.writeBigUInt64LE(w.address - 0x390n, 0x30 + 104); // rcx
pkt.writeBigUInt64LE(w.rip, 0x30 + 136); // rip: just past the writing instruction
pkt.writeBigUInt64LE(1n, 0x420 + 48); // DR6: watchpoint slot 0 fired
debug.stopped = true;
debug.events.write(pkt);
return true;
});
};
const timer = opts.tick === false ? null : setInterval(tick, 500);
if (timer) timer.unref?.();
async function handle(sock) {
const rd = new Reader(sock);
let turbo = null; // this connection's snapshot scan
sock.on('close', () => {
if (debug.owner === sock) debugTeardown();
});
const status = (s) => {
const b = Buffer.alloc(4);
b.writeUInt32LE(bitswap32(s));
sock.write(b);
};
const u32 = (v) => {
const b = Buffer.alloc(4);
b.writeUInt32LE(v >>> 0);
sock.write(b);
};
const sentinel = () => sock.write(Buffer.alloc(8, 0xff));
// The real server closes the connection whenever a handler fails early
// (main.c: a non-zero handler result ends the client loop).
const fatal = (s) => {
status(s);
sock.end();
};
for (;;) {
const hdr = await rd.read(12);
if (hdr.readUInt32LE(0) !== PACKET_MAGIC) continue;
const cmd = hdr.readUInt32LE(4);
const datalen = hdr.readUInt32LE(8);
if (datalen > 0x100000) {
status(ST.ERROR);
continue;
}
const d = datalen ? await rd.read(datalen) : null;
switch (cmd) {
case 0xbd000001: { // VERSION
u32(3);
sock.write('1.3');
break;
}
case 0xbd000500: { // FW_VERSION
if (opts.noBranding) break;
const b = Buffer.alloc(2);
b.writeUInt16LE(1000);
sock.write(b);
break;
}
case 0xbd000501: { // BRANDING
if (opts.noBranding) break;
const s = opts.legacy
? Buffer.from('ps5debug v1.0b5 (mock)')
: Buffer.concat([Buffer.from('ps5debug-NG by OSR v1.3.2 [mock0000mock0000]'), Buffer.from([0]), Buffer.from('1.1')]);
u32(s.length);
sock.write(s);
break;
}
case 0xbdaacc06: // NOP
status(ST.SUCCESS);
break;
case 0xbdaa0001: { // PROC_LIST
const procs = [['SceShellCore', 60], ['SceShellUI', 77]];
if (state.foreground) procs.push([GAME.name, GAME.pid]);
status(ST.SUCCESS);
u32(procs.length);
for (const [name, pid] of procs) {
const e = Buffer.alloc(36);
e.write(name, 0, 31);
e.writeInt32LE(pid, 32);
sock.write(e);
}
break;
}
case 0xbdaa0002: { // PROC_READ
if (!d) { status(ST.DATA_NULL); break; }
const addr = d.readBigUInt64LE(4);
const len = d.readUInt32LE(12);
status(ST.SUCCESS);
sock.write(game.read(addr, len));
break;
}
case 0xbdaa0003: { // PROC_WRITE (two status words)
if (!d) { status(ST.DATA_NULL); break; }
const addr = d.readBigUInt64LE(4);
const len = d.readUInt32LE(12);
status(ST.SUCCESS);
const data = await rd.read(len);
status(game.write(addr, data) ? ST.SUCCESS : ST.ERROR);
break;
}
case 0xbdaacc04: { // write-multi
if (opts.legacy) break; // the original payload never answers unknown commands
const count = d.readUInt32LE(4);
const wantStatus = d.readUInt32LE(8) & 1;
status(ST.SUCCESS);
const st = Buffer.alloc(count);
let failed = false;
for (let i = 0; i < count; i++) {
const h = await rd.read(12);
const data = await rd.read(h.readUInt32LE(8));
if (!game.write(h.readBigUInt64LE(0), data)) {
st[i] = 1;
failed = true;
}
}
if (wantStatus) sock.write(st);
status(wantStatus || !failed ? ST.SUCCESS : ST.ERROR);
break;
}
case 0xbdaa0004: { // PROC_MAPS
if (!d || d.readUInt32LE(0) !== GAME.pid || !state.foreground) { fatal(ST.ERROR); return; }
status(ST.SUCCESS);
u32(game.regions.length);
for (const r of game.regions) {
const e = Buffer.alloc(58);
e.write(r.name, 0, 31);
e.writeBigUInt64LE(r.start, 32);
e.writeBigUInt64LE(r.start + BigInt(r.buf.length), 40);
e.writeBigUInt64LE(0n, 48);
e.writeUInt16LE(r.prot, 56);
sock.write(e);
}
break;
}
case 0xbdaa0008: // PROC_PROTECT
status(ST.SUCCESS);
break;
case 0xbdaa000a: { // PROC_INFO
if (!d || d.readUInt32LE(0) !== GAME.pid || !state.foreground) { fatal(ST.DATA_NULL); return; }
const e = Buffer.alloc(188);
e.writeUInt32LE(GAME.pid, 0);
e.write(GAME.name, 4, 39);
e.write('/mnt/sandbox/pfsmnt/PPSA99999-app0/eboot.bin', 44, 63);
e.write(GAME.titleId, 108, 15);
e.write(GAME.contentId, 124, 63);
status(ST.SUCCESS);
sock.write(e);
break;
}
case 0xbdaaccff: { // PROC_AUTH
if (!d || d.readUInt32LE(0) !== 0xbb40e64d) { fatal(ST.DATA_NULL); return; }
status(ST.SUCCESS);
const challenge = Buffer.alloc(64);
for (let i = 0; i < 64; i++) {
const r = authLfsr();
challenge[i] = (r + Math.floor(r / 255)) & 0xff;
}
const ks = keystream();
const len = Buffer.alloc(2);
len.writeUInt16LE(64);
sock.write(len);
sock.write(challenge);
const response = await rd.read(64);
let ok = true;
for (let i = 0; i < 64; i++) if (response[i] !== (challenge[i] ^ ks[i])) ok = false;
if (!ok) { fatal(ST.DATA_NULL); return; }
if (d.readUInt32LE(4) & 2) state.authed = true;
status(ST.SUCCESS);
break;
}
case 0xbdaacc01: { // SCAN_START
if (!state.authed || !d) { fatal(ST.DATA_NULL); return; }
const address = d.readBigUInt64LE(4);
const length = d.readUInt32LE(12);
const valType = d[16], cmp = d[17], alignment = d[18];
const lenData = d.readUInt32LE(19);
if (cmp > 12 || lenData === 0) { fatal(ST.DATA_NULL); return; }
const needsValue = (((1 << cmp) & 0x114f) !== 0) || cmp === 4;
const size = SIZES[valType] ?? lenData;
status(ST.SUCCESS);
const pattern = needsValue ? await rd.read(lenData) : null;
status(ST.SUCCESS);
if (opts.scanDelayMs) await new Promise((r) => setTimeout(r, opts.scanDelayMs));
const step = alignment || size;
const mem = game.read(address, length);
const upper = cmp === 4 ? pattern : null;
let block = [];
let blockLen = 0;
const flush = () => {
if (!blockLen) return;
const h = Buffer.alloc(8);
h.writeBigUInt64LE(BigInt(blockLen));
sock.write(Buffer.concat([h, ...block]));
block = [];
blockLen = 0;
};
for (let j = 0; j + size <= length; j += step) {
if (compareValues(cmp, valType, size, pattern, mem, j, upper, size)) {
if (blockLen > 0x3ffe8 - size) flush();
const rec = Buffer.alloc(4 + size);
rec.writeUInt32LE(j, 0);
mem.copy(rec, 4, j, j + size);
block.push(rec);
blockLen += rec.length;
}
}
flush();
sentinel();
status(ST.SUCCESS);
break;
}
case 0xbdaacc02: { // SCAN_COUNT
if (!state.authed || !d) { fatal(ST.DATA_NULL); return; }
const base = d.readBigUInt64LE(4);
const valType = d[12], cmp = d[13];
const lenData = d.readUInt32LE(14);
if (cmp > 12) { fatal(ST.DATA_NULL); return; }
const needsValue = NEEDS_VALUE[cmp] || NEEDS_EXTRA[cmp];
const withPrev = !!NEEDS_PREV[cmp];
const size = SIZES[valType] ?? lenData;
status(ST.SUCCESS);
const pattern = needsValue && lenData ? await rd.read(lenData) : null;
const entrySize = withPrev ? 4 + size : 4;
for (;;) {
const chunkLen = (await rd.read(4)).readUInt32LE(0);
if (chunkLen === 0xffffffff) break;
if (chunkLen === 0) { sentinel(); continue; }
if (chunkLen > 0x40000) break;
const chunk = await rd.read(chunkLen);
const out = [];
for (let off = 0; off + entrySize <= chunkLen; off += entrySize) {
const entryOffset = chunk.readUInt32LE(off);
const mem = game.read(base + BigInt(entryOffset), size);
const prev = withPrev ? chunk : cmp === 4 && pattern && lenData >= 2 * size ? pattern : null;
const prevOff = withPrev ? off + 4 : size;
if (compareValues(cmp, valType, size, pattern, mem, 0, prev, prevOff)) {
const rec = Buffer.alloc(4 + size);
rec.writeUInt32LE(entryOffset, 0);
mem.copy(rec, 4);
out.push(rec);
}
}
if (out.length) {
const body = Buffer.concat(out);
const h = Buffer.alloc(8);
h.writeBigUInt64LE(BigInt(body.length));
sock.write(h);
sock.write(body);
}
sentinel();
}
status(ST.SUCCESS);
break;
}
case 0xbddd0004: { // NOTIFY
if (!d) { status(ST.DATA_NULL); break; }
const text = await rd.read(d.readUInt32LE(4));
state.notifications.push(text.toString('utf8').replace(/\0+$/, ''));
status(ST.SUCCESS);
break;
}
case 0xbddd0006: { // foreground app
if (opts.legacy) break;
const e = Buffer.alloc(140);
if (state.foreground) {
e.writeUInt32LE(GAME.pid, 0);
e.write(GAME.titleId, 4, 15);
e.write(GAME.contentId, 20, 63);
e.write(GAME.name, 84, 39);
e.write(GAME.version, 124, 15);
}
status(ST.SUCCESS);
sock.write(e);
break;
}
case 0xbdaa0006: { // PROC_CALL
if (!d) { fatal(ST.DATA_NULL); return; }
const rip = d.readBigUInt64LE(12);
const rdi = d.readBigUInt64LE(20), rsi = d.readBigUInt64LE(28);
let rax;
if (rip === GAME.imageBase + BigInt(GAME.funcs.add)) rax = BigInt.asUintN(64, rdi + rsi);
else if (rip === GAME.imageBase + BigInt(GAME.funcs.setGold)) {
game.heap.writeFloatLE(Number(rdi), GAME.vars.gold);
rax = 0n;
} else { status(ST.ERROR); break; }
const r = Buffer.alloc(12);
r.writeUInt32LE(GAME.pid, 0);
r.writeBigUInt64LE(rax, 4);
status(ST.SUCCESS);
sock.write(r);
break;
}
case 0xbdaa000b: { // PROC_ALLOC
if (!d) { fatal(ST.DATA_NULL); return; }
const r = Buffer.alloc(8);
r.writeBigUInt64LE(game.alloc(d.readUInt32LE(4), null));
status(ST.SUCCESS);
sock.write(r);
break;
}
case 0xbdaa000e: { // PROC_ALLOC_HINTED
if (!d) { fatal(ST.DATA_NULL); return; }
const r = Buffer.alloc(8);
if (opts.noNearAlloc) {
// The real handler still sends the (zeroed) result after an error status.
status(ST.ERROR);
sock.write(r);
break;
}
r.writeBigUInt64LE(game.alloc(d.readUInt32LE(12), d.readBigUInt64LE(4)));
status(ST.SUCCESS);
sock.write(r);
break;
}
case 0xbdaa000c: { // PROC_FREE
if (!d) { fatal(ST.DATA_NULL); return; }
status(game.free(d.readBigUInt64LE(4)) ? ST.SUCCESS : ST.ERROR);
break;
}
case 0xbdaa0024: { // assemble
if (opts.legacy) break;
if (!d || d.length < 12) { fatal(ST.DATA_NULL); return; }
const res = mockAssemble(d.subarray(12).toString('utf8'));
const r = Buffer.alloc(8);
if (res.error) {
const msg = Buffer.from(res.error);
r.writeUInt32LE(1, 0);
r.writeUInt32LE(msg.length, 4);
status(ST.ERROR);
sock.write(r);
sock.write(msg);
// The real handler reports failure to the client loop, which closes the connection.
sock.end();
return;
} else {
r.writeUInt32LE(res.bytes.length, 0);
r.writeUInt32LE(res.count, 4);
status(ST.SUCCESS);
sock.write(r);
sock.write(res.bytes);
}
break;
}
case 0xbdaa0501: { // SCAN_AOB
if (!d) { fatal(ST.DATA_NULL); return; }
const address = d.readBigUInt64LE(4);
const length = d.readUInt32LE(12);
const nth = d[16], unique = d[17];
const plen = d.readUInt32LE(18);
status(ST.SUCCESS);
const pattern = await rd.read(plen);
const mask = await rd.read(plen);
status(ST.SUCCESS);
const mem = game.read(address, length);
let found = 0n, seen = 0;
for (let i = 0; i + plen <= length; i++) {
let ok = true;
for (let j = 0; j < plen; j++) {
if (mask[j] === 1 && mem[i + j] !== pattern[j]) { ok = false; break; }
}
if (!ok) continue;
seen++;
if (seen === nth) found = address + BigInt(i);
if (unique && seen > 1) { found = 0n; break; }
if (!unique && seen === nth) break;
}
const r = Buffer.alloc(8);
r.writeBigUInt64LE(found);
sock.write(r);
status(ST.SUCCESS);
break;
}
// ---- turbo scan: only the snapshot (unknown value) flow ----
case 0xbdaacc10: { // TURBOSCAN_CAPS
if (opts.legacy) break;
const r = Buffer.alloc(16);
r.writeUInt32LE(1, 0);
r.writeUInt32LE(0x04 | 0x08 | 0x10, 4);
r.writeUInt32LE(1, 8);
status(ST.SUCCESS);
sock.write(r);
break;
}
case 0xbdaacc11: { // TURBOSCAN_START
if (!state.authed || !d) { fatal(ST.DATA_NULL); return; }
const valType = d[16], cmp = d[17];
const lenData = d.readUInt32LE(19);
const flags = d.readUInt32LE(23);
const snapshot = (flags & 4) !== 0;
if (cmp > 12 || (lenData === 0 && !snapshot)) { fatal(ST.DATA_NULL); return; }
if (!snapshot || !(flags & 0x10)) { fatal(ST.DATA_NULL); return; } // the mock only does segmented snapshots
const size = SIZES[valType];
const needsValue = ((1 << cmp) & 0x114f) !== 0 || cmp === 4;
status(ST.SUCCESS);
if (needsValue && lenData) await rd.read(lenData);
status(ST.SUCCESS);
const nseg = (await rd.read(4)).readUInt32LE(0);
const segs = await rd.read(nseg * 12);
if (opts.scanDelayMs) await new Promise((r) => setTimeout(r, opts.scanDelayMs));
const records = [];
let total = 0;
for (let i = 0; i < nseg; i++) {
const address = segs.readBigUInt64LE(i * 12);
const length = segs.readUInt32LE(i * 12 + 8);
total += length;
const mem = game.read(address, length);
for (let j = 0; j + size <= length; j += size) {
const v = mem.subarray(j, j + size);
if (!(flags & 8) && v.every((b) => b === 0)) continue; // zero slots are dropped unless asked for
records.push({ address: address + BigInt(j), value: Buffer.from(v) });
}
}
turbo = { valType, size, records };
const plan = Buffer.alloc(16);
plan.writeBigUInt64LE(BigInt(Math.floor(total / size)), 0);
plan.writeBigUInt64LE(BigInt(total), 8);
sock.write(plan);
const prog = Buffer.alloc(8);
prog.writeBigUInt64LE(BigInt(total));
sock.write(prog);
sentinel();
const sum = Buffer.alloc(12);
sum.writeUInt32LE(1, 0);
sum.writeBigUInt64LE(BigInt(records.length), 4);
sock.write(sum);
status(ST.SUCCESS);
break;
}
case 0xbdaacc12: { // TURBOSCAN_COUNT (server-resident only)
if (!state.authed || !d) { fatal(ST.DATA_NULL); return; }
const valType = d[12], cmp = d[13];
const lenData = d.readUInt32LE(14);
const flags = d.readUInt32LE(18);
if (cmp > 12 || !(flags & 2)) { fatal(ST.DATA_NULL); return; }
const needsValue = NEEDS_VALUE[cmp] || NEEDS_EXTRA[cmp];
status(ST.SUCCESS);
const pattern = needsValue && lenData ? await rd.read(lenData) : null;
const kept = [];
if (turbo && turbo.valType === valType) {
for (const rec of turbo.records) {
const mem = game.read(rec.address, turbo.size);
const prev = NEEDS_PREV[cmp] ? rec.value : cmp === 4 ? pattern : null;
if (compareValues(cmp, valType, turbo.size, pattern, mem, 0, prev, NEEDS_PREV[cmp] ? 0 : turbo.size)) {
kept.push({ address: rec.address, value: Buffer.from(mem) }); // baseline refreshed
}
}
turbo.records = kept;
}
sentinel();
const n = Buffer.alloc(8);
n.writeBigUInt64LE(BigInt(kept.length));
sock.write(n);
status(ST.SUCCESS);
break;
}
case 0xbdaacc13: { // TURBOSCAN_GET
if (!state.authed || !d) { fatal(ST.DATA_NULL); return; }
const start = d.readUInt32LE(0), count = d.readUInt32LE(4);
const rows = turbo ? turbo.records.slice(start, start + count) : [];
status(ST.SUCCESS);
u32(rows.length);
for (const rec of rows) {
const a = Buffer.alloc(8);
a.writeBigUInt64LE(rec.address);
sock.write(Buffer.concat([a, rec.value, rec.value]));
}
status(ST.SUCCESS);
break;
}
case 0xbdaacc14: // TURBOSCAN_END
if (!state.authed) { fatal(ST.DATA_NULL); return; }
turbo = null;
status(ST.SUCCESS);
break;
// ---- debugger ----
case 0xbdbb0001: { // DEBUG_ATTACH
if (opts.legacy) break;
if (debug.owner) { fatal(0xf0000008); return; } // CMD_ALREADY_DEBUG
if (!d || d.readUInt32LE(0) !== GAME.pid) { fatal(ST.ERROR); return; }
// The console connects back to whoever attached, on the event port.
const events = net.connect({ host: sock.remoteAddress.replace(/^::ffff:/, ''), port: opts.eventPort ?? 755 });
const ok = await new Promise((resolve) => {
events.once('connect', () => resolve(true));
events.once('error', () => resolve(false));
});
if (!ok) { fatal(ST.ERROR); return; }
events.on('error', () => {});
debug.owner = sock;
debug.events = events;
status(ST.SUCCESS);
break;
}
case 0xbdbb0002: // DEBUG_DETACH
// Recorded so tests can check the client disarmed its watchpoints first.
state.detachedWithWatchArmed = debug.watch.some(Boolean);
debugTeardown();
status(ST.SUCCESS);
break;
case 0xbdbb0004: { // DEBUG_SET_WATCHPOINT
if (!debug.owner) { fatal(ST.ERROR); return; }
if (!d) { fatal(ST.DATA_NULL); return; }
const index = d.readUInt32LE(0);
if (index > 3) { fatal(0xf000000a); return; } // CMD_INVALID_INDEX
const size = [1, 2, 8, 4][d.readUInt32LE(8) & 3];
debug.watch[index] = d.readUInt32LE(4) ? { address: d.readBigUInt64LE(16), size, kind: d.readUInt32LE(12) } : null;
status(ST.SUCCESS);
break;
}
case 0xbdbb0003: { // DEBUG_SET_BREAKPOINT (accepted, never triggers in the mock)
if (!debug.owner) { fatal(ST.ERROR); return; }
if (!d || d.readUInt32LE(0) > 29) { fatal(0xf000000a); return; }
status(ST.SUCCESS);
break;
}
case 0xbdbb0010: { // DEBUG_CONTINUE
if (!d) { fatal(ST.DATA_NULL); return; }
if (!debug.owner) { status(ST.ERROR); break; }
if (d[0] === 0) debug.stopped = false;
status(ST.SUCCESS);
break;
}
default:
// Unknown commands get no reply at all, like the real payload.
break;
}
}
}
const sockets = new Set();
const server = net.createServer((sock) => {
sock.setNoDelay(true);
sockets.add(sock);
sock.on('close', () => sockets.delete(sock));
sock.on('error', () => {});
handle(sock).catch(() => sock.destroy());
});
let udp = null;
if (udpPort) {
udp = dgram.createSocket({ type: 'udp4', reuseAddr: true });
udp.on('message', (msg, rinfo) => {
if (msg.length === 4 && msg.readUInt32LE(0) === 0xffffaaaa) udp.send(msg, rinfo.port, rinfo.address);
});
udp.on('error', () => {});
udp.bind(udpPort, '127.0.0.1');
udp.unref();
}
const ready = new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(tcpPort, '127.0.0.1', () => resolve(server.address().port));
});
return {
ready,
game,
state,
debug,
/** Runs one frame by hand (tests start the mock with tick: false). */
tick,
/** Makes the game receive a signal that has nothing to do with a watchpoint, as a crash would. */
raise(signal) {
if (!debug.owner || !debug.events) return;
const pkt = Buffer.alloc(1184);
pkt.writeUInt32LE(100123, 0);
pkt.writeUInt32LE((signal << 8) | 0x7f, 4);
pkt.writeBigUInt64LE(GAME.imageBase + 0x5000n, 0x30 + 136);
debug.stopped = true;
debug.events.write(pkt);
},
close() {
if (timer) clearInterval(timer);
for (const s of sockets) s.destroy();
if (udp) udp.close();
return new Promise((resolve) => server.close(() => resolve()));
},
};
}
if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
const mock = startMock();
mock.ready.then((port) => {
console.log(`Mock PS5 listening on 127.0.0.1:${port} (game ${GAME.titleId} v${GAME.version})`);
});
}
+3465
View File
File diff suppressed because it is too large. Load diff
+49
View File
@@ -0,0 +1,49 @@
{
"name": "cheatspecter",
"version": "0.3.0",
"private": true,
"description": "Browser-based real-time modding tool for jailbroken PS5 consoles running a ps5debug payload.",
"license": "GPL-3.0-only",
"type": "module",
"engines": {
"node": ">=20.19"
},
"scripts": {
"build": "vite build",
"prestart": "vite build",
"start": "node bridge/server.mjs",
"predemo": "vite build",
"demo": "node bridge/server.mjs --demo",
"dev": "node scripts/dev.mjs",
"typecheck": "tsc --noEmit",
"test": "node --test \"test/*.test.mjs\"",
"payload:host": "vite build && node scripts/build-payload.mjs host",
"payload": "vite build && node scripts/build-payload.mjs ps5",
"payload:send": "node scripts/send-payload.mjs",
"mcp": "node scripts/build-mcp.mjs"
},
"dependencies": {
"@radix-ui/react-use-controllable-state": "^1.2.6",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"iced-x86": "^1.21.0",
"lucide-react": "^1.54.0",
"radix-ui": "^1.7.0",
"react": "^19.3.0",
"react-dom": "^19.3.0",
"react-dropzone": "^20.1.2",
"tailwind-merge": "^3.7.0",
"tw-animate-css": "^1.4.0",
"ws": "^8.18.0"
},
"devDependencies": {
"@tailwindcss/vite": "^4.3.3",
"@types/node": "^26.6.5",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.1.2",
"tailwindcss": "^4.3.3",
"typescript": "^5.6.0",
"vite": "^8.3.4"
}
}
+74
View File
@@ -0,0 +1,74 @@
# On-console payload
`cheatspecter.elf` runs on the PS5 and removes the computer from the picture.
It serves the web app and bridges it to the debugger, so any phone or laptop
on the network just opens `http://<PS5 IP>:8744`.
**Status: builds and passes its tests on a computer; not yet run on a real
PS5.** The same source is compiled natively and exercised against the mock
console (`test/payload.test.mjs`): serving the app, the WebSocket handshake,
large transfers both ways, several connections at once, a missing debugger,
and cross-site rejection. What that cannot show is how it behaves under the
console's own loader and network stack.
## Use it
Send `cheatspecter-v<version>.elf` if you use a payload manager: it reads the
version from the file name and shows it next to the payload. `cheatspecter.elf`
is the same build under a fixed name, for scripts.
1. Load **ps5debug-NG** on the console as usual.
2. Send `payload/cheatspecter.elf` to your ELF loader, the same way you load
any other payload. From this folder:
```sh
npm run payload:send -- 192.168.1.20 # loader port 9021 by default
```
3. A notification on the TV shows the address to open.
It has to be sent again after each reboot, like any payload. Sending it twice
is harmless: the second copy sees the port is taken, says so, and exits.
## What it does
| Request | Behaviour |
| --- | --- |
| `GET /`, `/assets/*`, `/ghost.svg` | The web app, embedded in the ELF and served gzip-compressed. |
| `GET /api/info` | `{"mode":"console","version":"..."}`. The app sees this and skips the "find your PS5" screen. |
| `WS /ws` | Opens a TCP connection to `127.0.0.1:744` and relays binary frames both ways, unchanged. One WebSocket is one TCP connection. |
| `GET /api/library` | Installed titles: `{"titles":[{"id","meta":"json"\|"sfo","size","path"}]}`. `meta` is which metadata file the title has (`param.json` = PS5, `param.sfo` = PS4). |
| `GET /api/appmeta/<title id>/<param.json\|param.sfo\|icon0.png>` | The system's own metadata file for a title, untouched. The web app reads the name from it. |
| `POST /api/launch/<title id>` | Closes the running game, if any, and starts this one. |
| `GET /api/tables/<title id>` | Which game versions have a saved cheat file. |
| `GET`, `PUT /api/tables/<title id>/<version>` | The user's cheats for that game version, stored as `/data/cheatspecter/cheats/<title id>-<version>.cspecter`. |
| `WS /events` | Debugger stop reports. The payload listens on `127.0.0.1:755`, where the debugger connects when something attaches, and forwards what arrives. |
It is deliberately thin. All protocol knowledge and file parsing stay in the
web app, and ps5debug-NG keeps doing the kernel work.
WebSocket upgrades, launches and file saves are refused when the `Origin` host
differs from `Host`, so another web page cannot drive the console through a
visitor's browser. Title IDs and versions are checked against a strict pattern
before they are used in a path.
The library is built from the system's metadata folders
(`/system_data/priv/appmeta`, `/user/appmeta`). Sizes are the files found under
`/user/app`, `/user/patch`, the same folders on `/mnt/ext0` and `/mnt/ext1`, and
`/system_ex/app`, where game folders kept elsewhere are mounted. A title with
none of those is listed without a size; one with more than 200,000 files is
marked `partial`.
## Build it
```sh
npm run payload:host # for this computer; then: CS_PORT=8745 CS_DEBUGGER_PORT=7440 payload/build/cheatspecter-host
PS5_PAYLOAD_SDK=/opt/ps5-payload-sdk npm run payload # cheatspecter.elf
```
Both embed whatever `npm run build` produced, so the ELF needs rebuilding
after any change to the web app. The PS5 build needs
[ps5-payload-sdk](https://github.com/ps5-payload-dev/sdk) with clang and lld.
`src/main.c` is the whole thing: an HTTP server, a WebSocket relay with one
thread per direction, and SHA-1 and Base64 for the handshake.
+19
View File
@@ -0,0 +1,19 @@
/* Web app files embedded in the payload. Generated by scripts/embed-assets.mjs. */
#ifndef CS_ASSETS_H
#define CS_ASSETS_H
#include <stddef.h>
struct asset {
const char *path; /* "/index.html" */
const char *mime;
const unsigned char *data; /* gzip-compressed */
size_t size;
int immutable; /* content-hashed name: cache forever */
};
extern const struct asset CS_ASSETS[];
extern const int CS_ASSET_COUNT;
extern const char CS_VERSION[];
#endif
+1426
View File
File diff suppressed because it is too large. Load diff
+8
View File
@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" xmlns:c2pa="http://c2pa.org/manifest"><metadata><c2pa:manifest>AAAWgmp1bWIAAAAeanVtZGMycGEAEQAQgAAAqgA4m3EDYzJwYQAAABZcanVtYgAAAEdqdW1kYzJtYQARABCAAACqADibcQN1cm46YzJwYToyZmQwOTkwYi01ZjU3LTQ2YzktYTE2Zi04YmJlYmJlMTM0NzcAAAADl2p1bWIAAAApanVtZGMyYXMAEQAQgAAAqgA4m3EDYzJwYS5hc3NlcnRpb25zAAAAALxqdW1iAAAARGp1bWRjYm9yABEAEIAAAKoAOJtxE2MycGEuaW5ncmVkaWVudC52MwAAAAAYYzJzaGPOotfX2vlH/nUnNK+REAMAAABwY2JvcqNpZGM6Zm9ybWF0bWltYWdlL3N2Zyt4bWxqaW5zdGFuY2VJRHgseG1wOmlpZDo0NDZkYjcwMC0yNjgwLTQyYjUtOGZkMC0zMGM1MjZhMzlmOWNscmVsYXRpb25zaGlwaHBhcmVudE9mAAAB4mp1bWIAAABBanVtZGNib3IAEQAQgAAAqgA4m3ETYzJwYS5hY3Rpb25zLnYyAAAAABhjMnNoIIoEgWfbNw+17N2s2fSnbAAAAZljYm9yomdhY3Rpb25zgqJmYWN0aW9ua2MycGEub3BlbmVkanBhcmFtZXRlcnOha2luZ3JlZGllbnRzgaJjdXJseC1zZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmluZ3JlZGllbnQudjNkaGFzaFggX7hS0m+3DmO1r9z9E/c9M1fIntZO42L1pXuIT5B7kOekZmFjdGlvbngdY29tLmFudGhyb3BpYy5jbGF1ZGUucHJvdmlkZWRqcGFyYW1ldGVyc6F4H2NvbS5hbnRocm9waWMub3JpZ2luLWNvbmZpZGVuY2VndW5rbm93bmtkZXNjcmlwdGlvbnhmQ2xhdWRlIHByb3ZpZGVkIHRoaXMgZmlsZSBhdCB0aGUgcmVxdWVzdCBvZiBhIHVzZXIgYW5kIG1heSBoYXZlIGNyZWF0ZWQgb3IgbW9kaWZpZWQgdGhlIGZpbGUgY29udGVudHMubXNvZnR3YXJlQWdlbnShZG5hbWVmQ2xhdWRlcmFsbEFjdGlvbnNJbmNsdWRlZPUAAADIanVtYgAAAEBqdW1kY2JvcgARABCAAACqADibcRNjMnBhLmhhc2guZGF0YQAAAAAYYzJzaD/CZH3twzjXh1+Y7+ILwtwAAACAY2JvcqVjYWxnZnNoYTI1NmNwYWRNAAAAAAAAAAAAAAAAAGRoYXNoWCBSAIF//tQPqpyqSM0NKyINo/HxArL/hqve95S5Yq5YAWRuYW1lbmp1bWJmIG1hbmlmZXN0amV4Y2x1c2lvbnOBomVzdGFydBh7Zmxlbmd0aBkeBAAAAj5qdW1iAAAAJ2p1bWRjMmNsABEAEIAAAKoAOJtxA2MycGEuY2xhaW0udjIAAAACD2Nib3KlY2FsZ2ZzaGEyNTZpc2lnbmF0dXJleE1zZWxmI2p1bWJmPS9jMnBhL3VybjpjMnBhOjJmZDA5OTBiLTVmNTctNDZjOS1hMTZmLThiYmViYmUxMzQ3Ny9jMnBhLnNpZ25hdHVyZWppbnN0YW5jZUlEeCx4bXA6aWlkOjgxYmMwMjRlLTcxOGYtNDEyMi04MjE3LThmNzM4NzAyYzkzMXJjcmVhdGVkX2Fzc2VydGlvbnODomN1cmx4LXNlbGYjanVtYmY9YzJwYS5hc3NlcnRpb25zL2MycGEuaW5ncmVkaWVudC52M2RoYXNoWCBfuFLSb7cOY7Wv3P0T9z0zV8ie1k7jYvWle4hPkHuQ56JjdXJseCpzZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmFjdGlvbnMudjJkaGFzaFggyXVp/CMt70i5LlUePfBP82HSdbKl58WTbn+Sv/nMVmWiY3VybHgpc2VsZiNqdW1iZj1jMnBhLmFzc2VydGlvbnMvYzJwYS5oYXNoLmRhdGFkaGFzaFggnO8/tbYzNjnJaA8MyBu3ixlswMgij0R8IPz73UpX9vh0Y2xhaW1fZ2VuZXJhdG9yX2luZm+jZG5hbWVvQW50aHJvcGljIEZpbGVzZ3ZlcnNpb25lMS4wLjBrc3BlY1ZlcnNpb25lMi40LjAAABA4anVtYgAAAChqdW1kYzJjcwARABCAAACqADibcQNjMnBhLnNpZ25hdHVyZQAAABAIY2JvctKEWQISogEmGCFZAgowggIGMIIBjaADAgECAhRA5aAK7sI50L64g/oGQgU9Z1UTADAKBggqhkjOPQQDAzBJMRcwFQYDVQQKEw5BbnRocm9waWMsIFBCQzEuMCwGA1UEAxMlQW50aHJvcGljIENvbnRlbnQgQ3JlZGVudGlhbHMgUm9vdCBDQTAeFw0yNjA4MDcxODQzNTZaFw0yODA4MDYxOTQzNTZaMEQxFzAVBgNVBAoTDkFudGhyb3BpYywgUEJDMSkwJwYDVQQDEyBBbnRocm9waWMgQ2xhdWRlIENvbnRlbnQgU2lnbmluZzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJh6CmvLUBgFFNU0vUKlOVtE6djd17L5SuwX0LemFisBM3dkd/3cyjxFA3Qo5S46fX0/ihY0VZ7mfb9KF703t5OjWDBWMA4GA1UdDwEB/wQEAwIHgDAVBgNVHSUEDjAMBgorBgEEAYPoXgIBMAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAUzlHiBIFOZFsj+OPEz5o+nMHXXMIwCgYIKoZIzj0EAwMDZwAwZAIwMXMdFJ4BetLLVY7ORuE9noqbbAZOZn/aArXyTwFAZfKrPzxF2vPoJNf1+UCdg1XGAjBwX1zd9WGqYkqmL5SFqw1QySjr1zJfpJM9+1rdDwSPLMOPOjKuiXjoU/pUUeG9RwmhY3BhZFkNngAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALine truncated
<rect width="64" height="64" rx="14" fill="#070707"/>
<path d="M10 34C10 19 19.5 8 32 8s22 11 22 26v22l-7.3-6.5L39.3 56 32 49.5 24.7 56l-7.4-6.5L10 56Z" fill="#ffd400"/>
<ellipse cx="24" cy="30" rx="5.5" ry="6.5" fill="#fff"/>
<ellipse cx="40" cy="30" rx="5.5" ry="6.5" fill="#fff"/>
<circle cx="26.5" cy="31" r="3" fill="#0a0a0a"/>
<circle cx="42.5" cy="31" r="3" fill="#0a0a0a"/>
</svg>

After

Width:  |  Height:  |  Size: 8.0 KiB

+134
View File
@@ -0,0 +1,134 @@
// Builds the MCP server as a desktop extension: mcp/cheatspecter-<version>.mcpb
//
// An .mcpb file is a zip with a manifest and the server inside. Opening it in
// the Claude desktop app installs it; nothing has to be typed or configured
// beyond the PS5's address.
import fs from 'node:fs';
import path from 'node:path';
import zlib from 'node:zlib';
import { fileURLToPath } from 'node:url';
import { rolldown } from 'rolldown';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const { version } = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
const out = path.join(root, 'mcp/build');
fs.rmSync(out, { recursive: true, force: true });
fs.mkdirSync(path.join(out, 'server'), { recursive: true });
// One file with everything in it except the disassembler, which loads a
// WebAssembly file from beside itself and so is shipped as it is.
const bundle = await rolldown({
input: path.join(root, 'mcp/server.ts'),
platform: 'node',
external: ['iced-x86'],
transform: { define: { __VERSION__: JSON.stringify(version) } },
logLevel: 'warn',
});
await bundle.write({ file: path.join(out, 'server/index.mjs'), format: 'esm', codeSplitting: false });
await bundle.close();
const iced = path.join(root, 'node_modules/iced-x86');
const icedOut = path.join(out, 'server/node_modules/iced-x86');
fs.mkdirSync(icedOut, { recursive: true });
for (const f of ['package.json', 'iced_x86.js', 'iced_x86_bg.wasm', 'LICENSE.txt']) fs.copyFileSync(path.join(iced, f), path.join(icedOut, f));
const manifest = {
manifest_version: '0.3',
name: 'cheatspecter',
display_name: 'CheatSpecter',
version,
description: 'Find and make cheats for single-player games on a jailbroken PS5 running the CheatSpecter payload.',
long_description:
'Lets Claude work with a PS5 that has ps5debug-NG and the CheatSpecter payload loaded: see what game is running, search its memory for values, find the code that changes them, and save the result as a switch in the CheatSpecter app. For single-player games you own.',
author: { name: 'CheatSpecter' },
license: 'GPL-3.0-only',
server: {
type: 'node',
entry_point: 'server/index.mjs',
mcp_config: {
command: 'node',
args: ['${__dirname}/server/index.mjs'],
env: { CHEATSPECTER_HOST: '${user_config.host}' },
},
},
user_config: {
host: {
type: 'string',
title: 'PS5 address',
description: "Your PS5's IP address, as shown in the notification when the CheatSpecter payload starts (for example 192.168.1.50). Can be left empty and set later by asking Claude.",
required: false,
default: '',
},
},
tools: [],
compatibility: { runtimes: { node: '>=18.0.0' } },
};
// The tool list in the manifest is what the app shows before the server runs; take it from the source so the two cannot drift.
const source = fs.readFileSync(path.join(root, 'mcp/server.ts'), 'utf8');
for (const m of source.matchAll(/\n \{\n\s+name: '([a-z_]+)',\n\s+description:\s*\n?\s*(['"`])((?:\\.|(?!\2).)*)\2/g)) {
manifest.tools.push({ name: m[1], description: m[3].replace(/\\(['"`n])/g, (_, c) => (c === 'n' ? ' ' : c)).split('\n')[0].slice(0, 300) });
}
fs.writeFileSync(path.join(out, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n');
// ---- a zip, written by hand (deflate; no dependencies) ----
const crcTable = new Uint32Array(256).map((_, n) => {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
return c >>> 0;
});
const crc32 = (buf) => {
let c = 0xffffffff;
for (const b of buf) c = crcTable[(c ^ b) & 0xff] ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
};
const files = [];
const walk = (dir, rel = '') => {
for (const name of fs.readdirSync(dir).sort()) {
const full = path.join(dir, name);
const r = rel ? `${rel}/${name}` : name;
if (fs.statSync(full).isDirectory()) walk(full, r);
else files.push({ name: r, data: fs.readFileSync(full) });
}
};
walk(out);
const parts = [];
const central = [];
let offset = 0;
for (const f of files) {
const name = Buffer.from(f.name, 'utf8');
const packed = zlib.deflateRawSync(f.data, { level: 9 });
const head = Buffer.alloc(30);
head.writeUInt32LE(0x04034b50, 0);
head.writeUInt16LE(20, 4);
head.writeUInt16LE(0x0800, 6); // names are UTF-8
head.writeUInt16LE(8, 8); // deflate
head.writeUInt16LE(0, 10);
head.writeUInt16LE(0x21, 12); // 1980-01-01, so the same input always gives the same file
head.writeUInt32LE(crc32(f.data), 14);
head.writeUInt32LE(packed.length, 18);
head.writeUInt32LE(f.data.length, 22);
head.writeUInt16LE(name.length, 26);
parts.push(head, name, packed);
const cd = Buffer.alloc(46);
cd.writeUInt32LE(0x02014b50, 0);
cd.writeUInt16LE(20, 4);
cd.writeUInt16LE(20, 6);
head.copy(cd, 8, 6, 30); // flags .. name length
cd.writeUInt32LE(offset, 42);
central.push(cd, name);
offset += head.length + name.length + packed.length;
}
const cdBuf = Buffer.concat(central);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(files.length, 8);
end.writeUInt16LE(files.length, 10);
end.writeUInt32LE(cdBuf.length, 12);
end.writeUInt32LE(offset, 16);
for (const f of fs.readdirSync(path.join(root, 'mcp'))) if (/^cheatspecter-.*\.mcpb$/.test(f)) fs.rmSync(path.join(root, 'mcp', f));
const target = path.join(root, `mcp/cheatspecter-${version}.mcpb`);
fs.writeFileSync(target, Buffer.concat([...parts, cdBuf, end]));
console.log(`Built ${path.relative(root, target)} (${files.length} files, ${(fs.statSync(target).size / 1024).toFixed(0)} KB, ${manifest.tools.length} tools)`);
+53
View File
@@ -0,0 +1,53 @@
// Builds the on-console payload.
//
// node scripts/build-payload.mjs host for this computer (testing against the mock)
// node scripts/build-payload.mjs ps5 payload/cheatspecter.elf (needs PS5_PAYLOAD_SDK)
//
// Both embed the built web app from dist/, so run `npm run build` first; the
// npm scripts `payload:host` and `payload` do that for you.
import fs from 'node:fs';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const target = process.argv[2] ?? 'ps5';
const payload = path.join(root, 'payload');
const assets = path.join(payload, 'build/assets.c');
const sources = [path.join(payload, 'src/main.c'), assets];
const flags = ['-O2', '-Wall', '-Wextra', `-I${path.join(payload, 'src')}`];
const run = (cmd, args) => execFileSync(cmd, args, { stdio: 'inherit' });
if (!fs.existsSync(path.join(root, 'dist/index.html'))) {
console.error('The web app is not built yet. Run: npm run build');
process.exit(1);
}
run(process.execPath, [path.join(root, 'scripts/embed-assets.mjs'), path.join(root, 'dist'), assets]);
if (target === 'host') {
const out = path.join(payload, 'build/cheatspecter-host');
run(process.env.CC ?? 'cc', [...flags, '-o', out, ...sources, '-lpthread']);
console.log(`Built ${path.relative(root, out)}`);
} else if (target === 'ps5') {
const sdk = process.env.PS5_PAYLOAD_SDK;
if (!sdk) {
console.error('Set PS5_PAYLOAD_SDK to your ps5-payload-sdk install, e.g. /opt/ps5-payload-sdk');
process.exit(1);
}
const out = path.join(payload, 'cheatspecter.elf');
run(path.join(sdk, 'bin/prospero-clang'), [...flags, '-o', out, ...sources, '-lkernel_sys', '-lSceSystemService', '-lSceUserService']);
// Payload managers read the version from the file name ("name-v1.2.3.elf"),
// so the build is also written under one. Older versioned copies are removed.
const { version } = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
const versioned = path.join(payload, `cheatspecter-v${version}.elf`);
for (const f of fs.readdirSync(payload)) {
if (/^cheatspecter-v[\d.]+\.elf$/.test(f)) fs.rmSync(path.join(payload, f));
}
fs.copyFileSync(out, versioned);
console.log(`Built ${path.relative(root, out)} and ${path.relative(root, versioned)}`);
} else {
console.error('Usage: build-payload.mjs host|ps5');
process.exit(1);
}
+11
View File
@@ -0,0 +1,11 @@
// Runs the bridge (with the demo console) and the Vite dev server together.
import { spawn } from 'node:child_process';
const children = [
spawn(process.execPath, ['bridge/server.mjs', '--demo'], { stdio: 'inherit' }),
spawn(process.platform === 'win32' ? 'npx.cmd' : 'npx', ['vite'], { stdio: 'inherit' }),
];
const stop = () => children.forEach((c) => c.kill());
process.on('SIGINT', stop);
process.on('SIGTERM', stop);
children.forEach((c) => c.on('exit', stop));
+64
View File
@@ -0,0 +1,64 @@
// Turns the built web app (dist/) into a C file the payload compiles in.
// Every file is stored gzip-compressed and served that way.
//
// node scripts/embed-assets.mjs <dist dir> <output .c>
import fs from 'node:fs';
import path from 'node:path';
import zlib from 'node:zlib';
import { fileURLToPath } from 'node:url';
const [distDir, outFile] = process.argv.slice(2);
if (!distDir || !outFile) {
console.error('usage: embed-assets.mjs <dist dir> <output .c>');
process.exit(1);
}
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const version = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).version;
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.svg': 'image/svg+xml',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.ico': 'image/x-icon',
'.wasm': 'application/wasm',
};
function walk(dir, prefix = '') {
const out = [];
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const rel = `${prefix}/${entry.name}`;
if (entry.isDirectory()) out.push(...walk(path.join(dir, entry.name), rel));
else out.push(rel);
}
return out.sort();
}
const files = walk(distDir);
if (!files.includes('/index.html')) {
console.error(`${distDir} has no index.html; run "npm run build" first`);
process.exit(1);
}
let c = '/* Generated by scripts/embed-assets.mjs. Do not edit. */\n#include "assets.h"\n\n';
c += `const char CS_VERSION[] = ${JSON.stringify(version)};\n\n`;
const rows = [];
let total = 0;
files.forEach((rel, i) => {
const gz = zlib.gzipSync(fs.readFileSync(path.join(distDir, rel)), { level: 9 });
total += gz.length;
const bytes = [];
for (let o = 0; o < gz.length; o += 20) bytes.push(' ' + [...gz.subarray(o, o + 20)].join(','));
c += `static const unsigned char asset_${i}[] = {\n${bytes.join(',\n')}\n};\n\n`;
const mime = MIME[path.extname(rel).toLowerCase()] ?? 'application/octet-stream';
rows.push(` {${JSON.stringify(rel)}, ${JSON.stringify(mime)}, asset_${i}, sizeof asset_${i}, ${rel.startsWith('/assets/') ? 1 : 0}}`);
});
c += `const struct asset CS_ASSETS[] = {\n${rows.join(',\n')}\n};\n\nconst int CS_ASSET_COUNT = ${files.length};\n`;
fs.mkdirSync(path.dirname(outFile), { recursive: true });
fs.writeFileSync(outFile, c);
console.log(`Embedded ${files.length} files, ${(total / 1024).toFixed(0)} KB compressed -> ${outFile}`);
+48
View File
@@ -0,0 +1,48 @@
// Sends the built payload to an ELF loader on the console.
//
// npm run payload:send -- 192.168.1.20 (loader on port 9021)
// npm run payload:send -- 192.168.1.20 9020
import fs from 'node:fs';
import net from 'node:net';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const [host, portArg] = process.argv.slice(2);
if (!host) {
console.error('Usage: npm run payload:send -- <PS5 IP address> [loader port, default 9021]');
process.exit(1);
}
const port = Number(portArg ?? 9021);
const elf = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../payload/cheatspecter.elf');
if (!fs.existsSync(elf)) {
console.error('payload/cheatspecter.elf does not exist yet. Build it with: npm run payload');
process.exit(1);
}
const data = fs.readFileSync(elf);
const sock = net.connect({ host, port, timeout: 5000 });
// Some loaders keep the connection open after taking the file, so once every
// byte has gone out, a quiet connection is success, not a failure.
let sent = false;
let reported = false;
const done = () => {
if (reported) return;
reported = true;
console.log(`Sent ${(data.length / 1024).toFixed(0)} KB to ${host}:${port}. Watch the TV for the "CheatSpecter is ready" notification.`);
};
sock.on('timeout', () => {
if (sent) {
done();
sock.destroy();
} else sock.destroy(new Error('timed out'));
});
sock.on('connect', () => sock.end(data, () => (sent = true)));
sock.on('close', (hadError) => {
if (!hadError && sent) done();
});
sock.on('error', (err) => {
if (reported) return;
console.error(`Could not send to ${host}:${port} (${err.message}). Is an ELF loader running on the console?`);
process.exitCode = 1;
});
+142
View File
@@ -0,0 +1,142 @@
"use client";
import { useControllableState } from "@radix-ui/react-use-controllable-state";
import { type LucideIcon, XIcon } from "lucide-react";
import {
type ComponentProps,
createContext,
type HTMLAttributes,
type MouseEventHandler,
useContext,
} from "react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
type BannerContextProps = {
show: boolean;
setShow: (show: boolean) => void;
};
export const BannerContext = createContext<BannerContextProps>({
show: true,
setShow: () => {},
});
export type BannerProps = HTMLAttributes<HTMLDivElement> & {
visible?: boolean;
defaultVisible?: boolean;
onClose?: () => void;
inset?: boolean;
};
export const Banner = ({
children,
visible,
defaultVisible = true,
onClose,
className,
inset = false,
...props
}: BannerProps) => {
const [show, setShow] = useControllableState({
defaultProp: defaultVisible,
prop: visible,
onChange: onClose,
});
if (!show) {
return null;
}
return (
<BannerContext.Provider value={{ show, setShow }}>
<div
className={cn(
"flex w-full items-center justify-between gap-2 bg-primary px-4 py-2 text-primary-foreground",
inset && "rounded-lg",
className
)}
{...props}
>
{children}
</div>
</BannerContext.Provider>
);
};
export type BannerIconProps = HTMLAttributes<HTMLDivElement> & {
icon: LucideIcon;
};
export const BannerIcon = ({
icon: Icon,
className,
...props
}: BannerIconProps) => (
<div
className={cn(
"rounded-full border border-background/20 bg-background/10 p-1 shadow-sm",
className
)}
{...props}
>
<Icon size={16} />
</div>
);
export type BannerTitleProps = HTMLAttributes<HTMLParagraphElement>;
export const BannerTitle = ({ className, ...props }: BannerTitleProps) => (
<p className={cn("flex-1 text-sm", className)} {...props} />
);
export type BannerActionProps = ComponentProps<typeof Button>;
export const BannerAction = ({
variant = "outline",
size = "sm",
className,
...props
}: BannerActionProps) => (
<Button
className={cn(
"shrink-0 bg-transparent hover:bg-background/10 hover:text-background",
className
)}
size={size}
variant={variant}
{...props}
/>
);
export type BannerCloseProps = ComponentProps<typeof Button>;
export const BannerClose = ({
variant = "ghost",
size = "icon",
onClick,
className,
...props
}: BannerCloseProps) => {
const { setShow } = useContext(BannerContext);
const handleClick: MouseEventHandler<HTMLButtonElement> = (e) => {
setShow(false);
onClick?.(e);
};
return (
<Button
className={cn(
"shrink-0 bg-transparent hover:bg-background/10 hover:text-background",
className
)}
onClick={handleClick}
size={size}
variant={variant}
{...props}
>
<XIcon size={18} />
</Button>
);
};
+202
View File
@@ -0,0 +1,202 @@
"use client";
import { UploadIcon } from "lucide-react";
import type { ReactNode } from "react";
import { createContext, useContext } from "react";
import type { DropEvent, DropzoneOptions, FileRejection } from "react-dropzone";
import { useDropzone } from "react-dropzone";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
type DropzoneContextType = {
src?: File[];
accept?: DropzoneOptions["accept"];
maxSize?: DropzoneOptions["maxSize"];
minSize?: DropzoneOptions["minSize"];
maxFiles?: DropzoneOptions["maxFiles"];
};
const renderBytes = (bytes: number) => {
const units = ["B", "KB", "MB", "GB", "TB", "PB"];
let size = bytes;
let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return `${size.toFixed(2)}${units[unitIndex]}`;
};
const DropzoneContext = createContext<DropzoneContextType | undefined>(
undefined
);
export type DropzoneProps = Omit<DropzoneOptions, "onDrop"> & {
src?: File[];
className?: string;
onDrop?: (
acceptedFiles: File[],
fileRejections: FileRejection[],
event: DropEvent
) => void;
children?: ReactNode;
};
export const Dropzone = ({
accept,
maxFiles = 1,
maxSize,
minSize,
onDrop,
onError,
disabled,
src,
className,
children,
...props
}: DropzoneProps) => {
const { getRootProps, getInputProps, isDragActive } = useDropzone({
accept,
maxFiles,
maxSize,
minSize,
onError,
disabled,
onDrop: (acceptedFiles, fileRejections, event) => {
if (fileRejections.length > 0) {
const message = fileRejections.at(0)?.errors.at(0)?.message;
onError?.(new Error(message));
return;
}
onDrop?.(acceptedFiles, fileRejections, event);
},
...props,
});
return (
<DropzoneContext.Provider
key={JSON.stringify(src)}
value={{ src, accept, maxSize, minSize, maxFiles }}
>
<Button
className={cn(
"relative h-auto w-full flex-col overflow-hidden p-8",
isDragActive && "outline-none ring-1 ring-ring",
className
)}
disabled={disabled}
type="button"
variant="outline"
{...getRootProps()}
>
<input {...getInputProps()} disabled={disabled} />
{children}
</Button>
</DropzoneContext.Provider>
);
};
const useDropzoneContext = () => {
const context = useContext(DropzoneContext);
if (!context) {
throw new Error("useDropzoneContext must be used within a Dropzone");
}
return context;
};
export type DropzoneContentProps = {
children?: ReactNode;
className?: string;
};
const maxLabelItems = 3;
export const DropzoneContent = ({
children,
className,
}: DropzoneContentProps) => {
const { src } = useDropzoneContext();
if (!src) {
return null;
}
if (children) {
return children;
}
return (
<div className={cn("flex flex-col items-center justify-center", className)}>
<div className="flex size-8 items-center justify-center rounded-md bg-muted text-muted-foreground">
<UploadIcon size={16} />
</div>
<p className="my-2 w-full truncate font-medium text-sm">
{src.length > maxLabelItems
? `${new Intl.ListFormat("en").format(
src.slice(0, maxLabelItems).map((file) => file.name)
)} and ${src.length - maxLabelItems} more`
: new Intl.ListFormat("en").format(src.map((file) => file.name))}
</p>
<p className="w-full text-wrap text-muted-foreground text-xs">
Drag and drop or click to replace
</p>
</div>
);
};
export type DropzoneEmptyStateProps = {
children?: ReactNode;
className?: string;
};
export const DropzoneEmptyState = ({
children,
className,
}: DropzoneEmptyStateProps) => {
const { src, accept, maxSize, minSize, maxFiles } = useDropzoneContext();
if (src) {
return null;
}
if (children) {
return children;
}
let caption = "";
if (accept) {
caption += "Accepts ";
caption += new Intl.ListFormat("en").format(Object.keys(accept));
}
if (minSize && maxSize) {
caption += ` between ${renderBytes(minSize)} and ${renderBytes(maxSize)}`;
} else if (minSize) {
caption += ` at least ${renderBytes(minSize)}`;
} else if (maxSize) {
caption += ` less than ${renderBytes(maxSize)}`;
}
return (
<div className={cn("flex flex-col items-center justify-center", className)}>
<div className="flex size-8 items-center justify-center rounded-md bg-muted text-muted-foreground">
<UploadIcon size={16} />
</div>
<p className="my-2 w-full truncate text-wrap font-medium text-sm">
Upload {maxFiles === 1 ? "a file" : "files"}
</p>
<p className="w-full truncate text-wrap text-muted-foreground text-xs">
Drag and drop or click to upload
</p>
{caption && (
<p className="text-wrap text-muted-foreground text-xs">{caption}.</p>
)}
</div>
);
};
+166
View File
@@ -0,0 +1,166 @@
import { ChevronDownIcon, ChevronUpIcon, MinusIcon } from "lucide-react";
import type { ComponentProps, ReactNode } from "react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
export type PillProps = ComponentProps<typeof Badge> & {
themed?: boolean;
};
export const Pill = ({
variant = "secondary",
themed = false,
className,
...props
}: PillProps) => (
<Badge
className={cn("gap-2 rounded-full px-3 py-1.5 font-normal", className)}
variant={variant}
{...props}
/>
);
export type PillAvatarProps = ComponentProps<typeof AvatarImage> & {
fallback?: string;
};
export const PillAvatar = ({
fallback,
className,
...props
}: PillAvatarProps) => (
<Avatar className={cn("-ml-1 h-4 w-4", className)}>
<AvatarImage {...props} />
<AvatarFallback>{fallback}</AvatarFallback>
</Avatar>
);
export type PillButtonProps = ComponentProps<typeof Button>;
export const PillButton = ({ className, ...props }: PillButtonProps) => (
<Button
className={cn(
"-my-2 -mr-2 size-6 rounded-full p-0.5 hover:bg-foreground/5",
className
)}
size="icon"
variant="ghost"
{...props}
/>
);
export type PillStatusProps = {
children: ReactNode;
className?: string;
};
export const PillStatus = ({
children,
className,
...props
}: PillStatusProps) => (
<div
className={cn(
"flex items-center gap-2 border-r pr-2 font-medium",
className
)}
{...props}
>
{children}
</div>
);
export type PillIndicatorProps = {
variant?: "success" | "error" | "warning" | "info";
pulse?: boolean;
};
export const PillIndicator = ({
variant = "success",
pulse = false,
}: PillIndicatorProps) => (
<span className="relative flex size-2">
{pulse && (
<span
className={cn(
"absolute inline-flex h-full w-full animate-ping rounded-full opacity-75",
variant === "success" && "bg-emerald-400",
variant === "error" && "bg-rose-400",
variant === "warning" && "bg-amber-400",
variant === "info" && "bg-sky-400"
)}
/>
)}
<span
className={cn(
"relative inline-flex size-2 rounded-full",
variant === "success" && "bg-emerald-500",
variant === "error" && "bg-rose-500",
variant === "warning" && "bg-amber-500",
variant === "info" && "bg-sky-500"
)}
/>
</span>
);
export type PillDeltaProps = {
className?: string;
delta: number;
};
export const PillDelta = ({ className, delta }: PillDeltaProps) => {
if (!delta) {
return (
<MinusIcon className={cn("size-3 text-muted-foreground", className)} />
);
}
if (delta > 0) {
return (
<ChevronUpIcon className={cn("size-3 text-emerald-500", className)} />
);
}
return <ChevronDownIcon className={cn("size-3 text-rose-500", className)} />;
};
export type PillIconProps = {
icon: typeof ChevronUpIcon;
className?: string;
};
export const PillIcon = ({
icon: Icon,
className,
...props
}: PillIconProps) => (
<Icon
className={cn("size-3 text-muted-foreground", className)}
size={12}
{...props}
/>
);
export type PillAvatarGroupProps = {
children: ReactNode;
className?: string;
};
export const PillAvatarGroup = ({
children,
className,
...props
}: PillAvatarGroupProps) => (
<div
className={cn(
"-space-x-1 flex items-center",
"[&>*:not(:first-of-type)]:[mask-image:radial-gradient(circle_9px_at_-4px_50%,transparent_99%,white_100%)]",
className
)}
{...props}
>
{children}
</div>
);
+271
View File
@@ -0,0 +1,271 @@
import { Spinner as ShadcnSpinner } from "@/components/ui/spinner";
import {
LoaderCircleIcon,
LoaderIcon,
LoaderPinwheelIcon,
type LucideProps,
} from "lucide-react";
import { cn } from "@/lib/utils";
type SpinnerVariantProps = Omit<SpinnerProps, "variant">;
const Throbber = ({ className, ...props }: SpinnerVariantProps) => (
<LoaderIcon className={cn("animate-spin", className)} {...props} />
);
const Pinwheel = ({ className, ...props }: SpinnerVariantProps) => (
<LoaderPinwheelIcon className={cn("animate-spin", className)} {...props} />
);
const CircleFilled = ({
className,
size = 24,
...props
}: SpinnerVariantProps) => (
<div className="relative" style={{ width: size, height: size }}>
<div className="absolute inset-0 rotate-180">
<LoaderCircleIcon
className={cn("animate-spin", className, "text-foreground opacity-20")}
size={size}
{...props}
/>
</div>
<LoaderCircleIcon
className={cn("relative animate-spin", className)}
size={size}
{...props}
/>
</div>
);
const Ellipsis = ({ size = 24, ...props }: SpinnerVariantProps) => {
return (
<svg
height={size}
viewBox="0 0 24 24"
width={size}
xmlns="http://www.w3.org/2000/svg"
{...props}
>
<title>Loading...</title>
<circle cx="4" cy="12" fill="currentColor" r="2">
<animate
attributeName="cy"
begin="0;ellipsis3.end+0.25s"
calcMode="spline"
dur="0.6s"
id="ellipsis1"
keySplines=".33,.66,.66,1;.33,0,.66,.33"
values="12;6;12"
/>
</circle>
<circle cx="12" cy="12" fill="currentColor" r="2">
<animate
attributeName="cy"
begin="ellipsis1.begin+0.1s"
calcMode="spline"
dur="0.6s"
keySplines=".33,.66,.66,1;.33,0,.66,.33"
values="12;6;12"
/>
</circle>
<circle cx="20" cy="12" fill="currentColor" r="2">
<animate
attributeName="cy"
begin="ellipsis1.begin+0.2s"
calcMode="spline"
dur="0.6s"
id="ellipsis3"
keySplines=".33,.66,.66,1;.33,0,.66,.33"
values="12;6;12"
/>
</circle>
</svg>
);
};
const Ring = ({ size = 24, ...props }: SpinnerVariantProps) => (
<svg
height={size}
stroke="currentColor"
viewBox="0 0 44 44"
width={size}
xmlns="http://www.w3.org/2000/svg"
{...props}
>
<title>Loading...</title>
<g fill="none" fillRule="evenodd" strokeWidth="2">
<circle cx="22" cy="22" r="1">
<animate
attributeName="r"
begin="0s"
calcMode="spline"
dur="1.8s"
keySplines="0.165, 0.84, 0.44, 1"
keyTimes="0; 1"
repeatCount="indefinite"
values="1; 20"
/>
<animate
attributeName="stroke-opacity"
begin="0s"
calcMode="spline"
dur="1.8s"
keySplines="0.3, 0.61, 0.355, 1"
keyTimes="0; 1"
repeatCount="indefinite"
values="1; 0"
/>
</circle>
<circle cx="22" cy="22" r="1">
<animate
attributeName="r"
begin="-0.9s"
calcMode="spline"
dur="1.8s"
keySplines="0.165, 0.84, 0.44, 1"
keyTimes="0; 1"
repeatCount="indefinite"
values="1; 20"
/>
<animate
attributeName="stroke-opacity"
begin="-0.9s"
calcMode="spline"
dur="1.8s"
keySplines="0.3, 0.61, 0.355, 1"
keyTimes="0; 1"
repeatCount="indefinite"
values="1; 0"
/>
</circle>
</g>
</svg>
);
const Bars = ({ size = 24, ...props }: SpinnerVariantProps) => (
<svg
height={size}
viewBox="0 0 24 24"
width={size}
xmlns="http://www.w3.org/2000/svg"
{...props}
>
<title>Loading...</title>
<style>{`
.spinner-bar {
animation: spinner-bars-animation .8s linear infinite;
animation-delay: -.8s;
}
.spinner-bars-2 {
animation-delay: -.65s;
}
.spinner-bars-3 {
animation-delay: -0.5s;
}
@keyframes spinner-bars-animation {
0% {
y: 1px;
height: 22px;
}
93.75% {
y: 5px;
height: 14px;
opacity: 0.2;
}
}
`}</style>
<rect
className="spinner-bar"
fill="currentColor"
height="22"
width="6"
x="1"
y="1"
/>
<rect
className="spinner-bar spinner-bars-2"
fill="currentColor"
height="22"
width="6"
x="9"
y="1"
/>
<rect
className="spinner-bar spinner-bars-3"
fill="currentColor"
height="22"
width="6"
x="17"
y="1"
/>
</svg>
);
const Infinite = ({ size = 24, ...props }: SpinnerVariantProps) => (
<svg
height={size}
preserveAspectRatio="xMidYMid"
viewBox="0 0 100 100"
width={size}
xmlns="http://www.w3.org/2000/svg"
{...props}
>
<title>Loading...</title>
<path
d="M24.3 30C11.4 30 5 43.3 5 50s6.4 20 19.3 20c19.3 0 32.1-40 51.4-40 C88.6 30 95 43.3 95 50s-6.4 20-19.3 20C56.4 70 43.6 30 24.3 30z"
fill="none"
stroke="currentColor"
strokeDasharray="205.271142578125 51.317785644531256"
strokeLinecap="round"
strokeWidth="10"
style={{
transform: "scale(0.8)",
transformOrigin: "50px 50px",
}}
>
<animate
attributeName="stroke-dashoffset"
dur="2s"
keyTimes="0;1"
repeatCount="indefinite"
values="0;256.58892822265625"
/>
</path>
</svg>
);
export type SpinnerProps = LucideProps & {
variant?:
| "default"
| "throbber"
| "pinwheel"
| "circle-filled"
| "ellipsis"
| "ring"
| "bars"
| "infinite";
};
export const Spinner = ({ variant, ...props }: SpinnerProps) => {
switch (variant) {
case "throbber":
return <Throbber {...props} />;
case "pinwheel":
return <Pinwheel {...props} />;
case "circle-filled":
return <CircleFilled {...props} />;
case "ellipsis":
return <Ellipsis {...props} />;
case "ring":
return <Ring {...props} />;
case "bars":
return <Bars {...props} />;
case "infinite":
return <Infinite {...props} />;
default:
return (
<ShadcnSpinner className={cn("size-6", props.className)} {...props} />
);
}
};
+62
View File
@@ -0,0 +1,62 @@
import type { ComponentProps, HTMLAttributes } from "react";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
export type StatusProps = ComponentProps<typeof Badge> & {
status: "online" | "offline" | "maintenance" | "degraded";
};
export const Status = ({ className, status, ...props }: StatusProps) => (
<Badge
className={cn("flex items-center gap-2", "group", status, className)}
variant="secondary"
{...props}
/>
);
export type StatusIndicatorProps = HTMLAttributes<HTMLSpanElement>;
export const StatusIndicator = ({
className,
...props
}: StatusIndicatorProps) => (
<span className="relative flex h-2 w-2" {...props}>
<span
className={cn(
"absolute inline-flex h-full w-full animate-ping rounded-full opacity-75",
"group-[.online]:bg-emerald-500",
"group-[.offline]:bg-red-500",
"group-[.maintenance]:bg-blue-500",
"group-[.degraded]:bg-amber-500"
)}
/>
<span
className={cn(
"relative inline-flex h-2 w-2 rounded-full",
"group-[.online]:bg-emerald-500",
"group-[.offline]:bg-red-500",
"group-[.maintenance]:bg-blue-500",
"group-[.degraded]:bg-amber-500"
)}
/>
</span>
);
export type StatusLabelProps = HTMLAttributes<HTMLSpanElement>;
export const StatusLabel = ({
className,
children,
...props
}: StatusLabelProps) => (
<span className={cn("text-muted-foreground", className)} {...props}>
{children ?? (
<>
<span className="hidden group-[.online]:block">Online</span>
<span className="hidden group-[.offline]:block">Offline</span>
<span className="hidden group-[.maintenance]:block">Maintenance</span>
<span className="hidden group-[.degraded]:block">Degraded</span>
</>
)}
</span>
);
+65
View File
@@ -0,0 +1,65 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative grid w-full grid-cols-[0_1fr] items-start gap-y-0.5 rounded-lg border px-4 py-3 text-sm has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-[>svg]:gap-x-3 [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
{
variants: {
variant: {
default: "bg-card text-card-foreground",
destructive:
"bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Alert({
className,
variant,
...props
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
return (
<div
data-slot="alert"
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
)
}
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-title"
className={cn(
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
className
)}
{...props}
/>
)
}
function AlertDescription({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-description"
className={cn(
"col-start-2 grid justify-items-start gap-1 text-sm text-muted-foreground [&_p]:leading-relaxed",
className
)}
{...props}
/>
)
}
export { Alert, AlertTitle, AlertDescription }
+106
View File
@@ -0,0 +1,106 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { Avatar as AvatarPrimitive } from "radix-ui"
function Avatar({
className,
size = "default",
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root> & {
size?: "default" | "sm" | "lg"
}) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
data-size={size}
className={cn(
"group/avatar relative flex size-8 shrink-0 overflow-hidden rounded-full select-none data-[size=lg]:size-10 data-[size=sm]:size-6",
className
)}
{...props}
/>
)
}
function AvatarImage({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn("aspect-square size-full", className)}
{...props}
/>
)
}
function AvatarFallback({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
"flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",
className
)}
{...props}
/>
)
}
function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="avatar-badge"
className={cn(
"absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground ring-2 ring-background select-none",
"group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
"group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
"group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
className
)}
{...props}
/>
)
}
function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="avatar-group"
className={cn(
"group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background",
className
)}
{...props}
/>
)
}
function AvatarGroupCount({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="avatar-group-count"
className={cn(
"relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
className
)}
{...props}
/>
)
}
export {
Avatar,
AvatarImage,
AvatarFallback,
AvatarBadge,
AvatarGroup,
AvatarGroupCount,
}
+47
View File
@@ -0,0 +1,47 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Slot } from "radix-ui"
const badgeVariants = cva(
"inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary:
"bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90",
outline:
"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
ghost: "[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
link: "text-primary underline-offset-4 [a&]:hover:underline",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant = "default",
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "span"
return (
<Comp
data-slot="badge"
data-variant={variant}
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
)
}
export { Badge, badgeVariants }
+63
View File
@@ -0,0 +1,63 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Slot } from "radix-ui"
const buttonVariants = cva(
"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
"icon-sm": "size-8",
"icon-lg": "size-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot.Root : "button"
return (
<Comp
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }
+91
View File
@@ -0,0 +1,91 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"flex flex-col gap-6 rounded-xl border bg-card py-6 text-card-foreground shadow-sm",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}
+156
View File
@@ -0,0 +1,156 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { XIcon } from "lucide-react"
import { Dialog as DialogPrimitive } from "radix-ui"
import { Button } from "@/components/ui/button"
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close asChild>
<Button variant="outline">Close</Button>
</DialogPrimitive.Close>
)}
</div>
)
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}
+256
View File
@@ -0,0 +1,256 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"
function DropdownMenu({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
)
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return (
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
)
}
function DropdownMenuContent({
className,
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
"z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
)
}
function DropdownMenuGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
)
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",
className
)}
{...props}
/>
)
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
)
}
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return (
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
}
function DropdownMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
)
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className
)}
{...props}
/>
)
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
)
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger>
)
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
"z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
className
)}
{...props}
/>
)
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}
+20
View File
@@ -0,0 +1,20 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
"aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",
className
)}
{...props}
/>
)
}
export { Input }
+21
View File
@@ -0,0 +1,21 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { Label as LabelPrimitive } from "radix-ui"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }
+187
View File
@@ -0,0 +1,187 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
import { Select as SelectPrimitive } from "radix-ui"
function Select({
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />
}
function SelectGroup({
...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />
}
function SelectValue({
...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default"
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDownIcon className="size-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
)
}
function SelectContent({
className,
children,
position = "item-aligned",
align = "center",
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
"relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
align={align}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
)
}
function SelectLabel({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("px-2 py-1.5 text-xs text-muted-foreground", className)}
{...props}
/>
)
}
function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
)}
{...props}
>
<span
data-slot="select-item-indicator"
className="absolute right-2 flex size-3.5 items-center justify-center"
>
<SelectPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
)
}
function SelectSeparator({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton>
)
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton>
)
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
}
+15
View File
@@ -0,0 +1,15 @@
import { cn } from "@/lib/utils"
import { Loader2Icon } from "lucide-react"
function Spinner({ className, ...props }: React.ComponentProps<"svg">) {
return (
<Loader2Icon
role="status"
aria-label="Loading"
className={cn("size-4 animate-spin", className)}
{...props}
/>
)
}
export { Spinner }
+32
View File
@@ -0,0 +1,32 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { Switch as SwitchPrimitive } from "radix-ui"
function Switch({
className,
size = "default",
...props
}: React.ComponentProps<typeof SwitchPrimitive.Root> & {
size?: "sm" | "default"
}) {
return (
<SwitchPrimitive.Root
data-slot="switch"
data-size={size}
className={cn(
"peer group/switch inline-flex shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-[1.15rem] data-[size=default]:w-8 data-[size=sm]:h-3.5 data-[size=sm]:w-6 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input dark:data-[state=unchecked]:bg-input/80",
className
)}
{...props}
>
<SwitchPrimitive.Thumb
data-slot="switch-thumb"
className={cn(
"pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0 dark:data-[state=checked]:bg-primary-foreground dark:data-[state=unchecked]:bg-foreground"
)}
/>
</SwitchPrimitive.Root>
)
}
export { Switch }
+115
View File
@@ -0,0 +1,115 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
)
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
)
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
)
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
)
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
className
)}
{...props}
/>
)
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
)
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}
+90
View File
@@ -0,0 +1,90 @@
"use client"
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Tabs as TabsPrimitive } from "radix-ui"
function Tabs({
className,
orientation = "horizontal",
...props
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
return (
<TabsPrimitive.Root
data-slot="tabs"
data-orientation={orientation}
orientation={orientation}
className={cn(
"group/tabs flex gap-2 data-[orientation=horizontal]:flex-col",
className
)}
{...props}
/>
)
}
const tabsListVariants = cva(
"group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-[orientation=horizontal]/tabs:h-9 group-data-[orientation=vertical]/tabs:h-fit group-data-[orientation=vertical]/tabs:flex-col data-[variant=line]:rounded-none",
{
variants: {
variant: {
default: "bg-muted",
line: "gap-1 bg-transparent",
},
},
defaultVariants: {
variant: "default",
},
}
)
function TabsList({
className,
variant = "default",
...props
}: React.ComponentProps<typeof TabsPrimitive.List> &
VariantProps<typeof tabsListVariants>) {
return (
<TabsPrimitive.List
data-slot="tabs-list"
data-variant={variant}
className={cn(tabsListVariants({ variant }), className)}
{...props}
/>
)
}
function TabsTrigger({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
return (
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
"relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-[orientation=vertical]/tabs:w-full group-data-[orientation=vertical]/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 group-data-[variant=default]/tabs-list:data-[state=active]:shadow-sm group-data-[variant=line]/tabs-list:data-[state=active]:shadow-none dark:text-muted-foreground dark:hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent",
"data-[state=active]:bg-background data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 dark:data-[state=active]:text-foreground",
"after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-[orientation=horizontal]/tabs:after:inset-x-0 group-data-[orientation=horizontal]/tabs:after:bottom-[-5px] group-data-[orientation=horizontal]/tabs:after:h-0.5 group-data-[orientation=vertical]/tabs:after:inset-y-0 group-data-[orientation=vertical]/tabs:after:-right-1 group-data-[orientation=vertical]/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-[state=active]:after:opacity-100",
className
)}
{...props}
/>
)
}
function TabsContent({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
return (
<TabsPrimitive.Content
data-slot="tabs-content"
className={cn("flex-1 outline-none", className)}
{...props}
/>
)
}
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }
+17
View File
@@ -0,0 +1,17 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
"flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:ring-destructive/40",
className
)}
{...props}
/>
)
}
export { Textarea }
+94
View File
@@ -0,0 +1,94 @@
// Small byte helpers shared by the browser app, the tests and nothing else.
// Everything on the wire is little-endian.
export function hexToBytes(hex: string): Uint8Array {
const clean = hex.replace(/[^0-9a-fA-F]/g, '');
if (clean.length % 2 !== 0) throw new Error(`Odd-length hex string: "${hex}"`);
const out = new Uint8Array(clean.length / 2);
for (let i = 0; i < out.length; i++) out[i] = parseInt(clean.substr(i * 2, 2), 16);
return out;
}
export function bytesToHex(bytes: Uint8Array, sep = ''): string {
let s = '';
for (let i = 0; i < bytes.length; i++) {
if (i && sep) s += sep;
s += bytes[i].toString(16).padStart(2, '0').toUpperCase();
}
return s;
}
export function concat(...parts: Uint8Array[]): Uint8Array {
let n = 0;
for (const p of parts) n += p.length;
const out = new Uint8Array(n);
let o = 0;
for (const p of parts) {
out.set(p, o);
o += p.length;
}
return out;
}
export function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
return true;
}
/** Decode a fixed-size, NUL-padded C string field. */
export function cstr(bytes: Uint8Array): string {
let end = bytes.indexOf(0);
if (end < 0) end = bytes.length;
return new TextDecoder('utf-8', { fatal: false }).decode(bytes.subarray(0, end));
}
export function view(bytes: Uint8Array): DataView {
return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
}
export function fmtAddr(addr: bigint): string {
return '0x' + addr.toString(16).toUpperCase();
}
export function fmtBytes(n: number): string {
if (n < 1024) return `${n} B`;
if (n < 1024 ** 2) return `${(n / 1024).toFixed(0)} KB`;
if (n < 1024 ** 3) return `${(n / 1024 ** 2).toFixed(0)} MB`;
return `${(n / 1024 ** 3).toFixed(2)} GB`;
}
/** Builds a packed little-endian struct. */
export class Packer {
private parts: Uint8Array[] = [];
u8(v: number): this {
this.parts.push(Uint8Array.of(v & 0xff));
return this;
}
u16(v: number): this {
const b = new Uint8Array(2);
view(b).setUint16(0, v, true);
this.parts.push(b);
return this;
}
u32(v: number): this {
const b = new Uint8Array(4);
view(b).setUint32(0, v >>> 0, true);
this.parts.push(b);
return this;
}
u64(v: bigint): this {
const b = new Uint8Array(8);
view(b).setBigUint64(0, BigInt.asUintN(64, v), true);
this.parts.push(b);
return this;
}
bytes(b: Uint8Array): this {
this.parts.push(b);
return this;
}
done(): Uint8Array {
return concat(...this.parts);
}
}
+263
View File
@@ -0,0 +1,263 @@
// Where cheat tables come from.
//
// Tables are fetched by the browser, not the console: the PS5 can stay
// offline while the phone or computer showing this page downloads what it
// needs. Each online source is a public Git repository with, per format
// (JSON, SHN, MC4), an index file (one "FILENAME=Game name" line per table)
// next to a folder of tables.
// Files are read from their original location at runtime; nothing is copied
// into this project.
import { sameVersion } from './cheats.ts';
import { decodeText, parseAnyTable } from './trainer.ts';
import type { CheatTable } from './cheats.ts';
import { loadJson, saveJson } from './storage.ts';
/** One list of tables in a source: an index file and the folder its files sit in. */
export interface CatalogIndex {
format: TableFormat;
indexUrl: string;
fileBase: string;
}
export interface CatalogSource {
id: string;
name: string;
/** Link shown to the user as the origin of the tables. */
home: string;
indexes: CatalogIndex[];
}
export type TableFormat = 'json' | 'shn' | 'mc4';
function repo(base: string, formats: TableFormat[]): CatalogIndex[] {
return formats.map((format) => ({ format, indexUrl: `${base}${format}.txt`, fileBase: `${base}${format}/` }));
}
export const ONLINE_SOURCES: CatalogSource[] = [
{
id: 'etahen',
name: 'etaHEN PS5 Cheats',
home: 'https://github.com/etaHEN/PS5_Cheats',
indexes: repo('https://raw.githubusercontent.com/etaHEN/PS5_Cheats/main/', ['json', 'shn', 'mc4']),
},
{
id: 'goldhen',
name: 'GoldHEN Cheat Repository',
home: 'https://github.com/GoldHEN/GoldHEN_Cheat_Repository',
indexes: repo('https://raw.githubusercontent.com/GoldHEN/GoldHEN_Cheat_Repository/main/', ['json', 'shn', 'mc4']),
},
{
id: 'hencc',
name: 'HEN Cheats Collection',
home: 'https://github.com/TeeKay87/HEN-Cheats-Collection',
// Its SHN folder has no index file; those tables are the same cheats as its JSON and MC4 ones.
indexes: repo('https://raw.githubusercontent.com/TeeKay87/HEN-Cheats-Collection/master/cheats/', ['json', 'mc4']),
},
];
/** Tables kept next to the app by whatever serves it (the dev bridge's cheats/ folder). */
export const LOCAL_SOURCE: CatalogSource = {
id: 'local',
name: 'This computer',
home: '',
indexes: [{ format: 'json', indexUrl: 'api/local-cheats', fileBase: 'local-cheats/' }],
};
/** Tables the user imported; stored in this browser. */
export const MINE_SOURCE_ID = 'mine';
export interface CatalogEntry {
sourceId: string;
sourceName: string;
file: string;
url: string;
titleId: string;
version: string;
gameName: string;
format: TableFormat;
/** True when the table's version matches the running game. */
exact: boolean;
}
interface CachedIndex {
at: number;
lines: string[];
}
interface CachedTable {
at: number;
text: string;
}
const INDEX_TTL_MS = 12 * 60 * 60 * 1000;
const FORMAT_ORDER: TableFormat[] = ['json', 'shn', 'mc4'];
const FILE_RE = /^([A-Z]{4}\d{5})_([0-9.]+?)(?:_.*)?\.(json|shn|mc4)(\.xml)?$/i;
export function parseIndexLine(
line: string,
): { file: string; titleId: string; version: string; gameName: string; format: TableFormat } | null {
const eq = line.indexOf('=');
let file = (eq < 0 ? line : line.slice(0, eq)).trim();
const m = FILE_RE.exec(file);
if (!m) return null;
// "X.mc4.xml" files only hold the cheats' names; the cheats themselves are in "X.mc4" beside them.
if (m[4]) file = file.slice(0, -m[4].length);
let gameName = eq < 0 ? '' : line.slice(eq + 1).trim();
// Some indexes repeat the file name where the game's name should be.
if (/^[A-Z]{4}\d{5}_[0-9.]+$/i.test(gameName)) gameName = '';
return { file, titleId: m[1].toUpperCase(), version: m[2], gameName, format: m[3].toLowerCase() as TableFormat };
}
/** Fetches a file as text. Trainer files are not always UTF-8, so the bytes are decoded here. */
async function fetchText(url: string): Promise<string> {
const res = await fetch(url, { cache: 'no-cache' });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return decodeText(new Uint8Array(await res.arrayBuffer()));
}
async function loadIndex(source: CatalogSource, index: CatalogIndex): Promise<{ lines: string[]; stale: boolean }> {
const key = `index.${source.id}.${index.format}`;
const cached = source.id === LOCAL_SOURCE.id ? null : loadJson<CachedIndex | null>(key, null);
if (cached && Date.now() - cached.at < INDEX_TTL_MS) return { lines: cached.lines, stale: false };
try {
const text = await fetchText(index.indexUrl);
// Only lines that name a table are kept: the indexes are big, and browser storage is not.
const lines = text.split(/\r?\n/).filter((l) => parseIndexLine(l) !== null);
if (source.id !== LOCAL_SOURCE.id) saveJson(key, { at: Date.now(), lines } satisfies CachedIndex);
return { lines, stale: false };
} catch (e) {
// Offline or the host is down: an old copy beats nothing.
if (cached) return { lines: cached.lines, stale: true };
throw e;
}
}
export interface CatalogResult {
entries: CatalogEntry[];
/** Sources that could not be reached, with the reason. */
failed: { source: string; reason: string }[];
/** Sources answered from an old saved copy because they were unreachable. */
stale: string[];
}
/** Finds every table for a title, best match first. */
export async function findTables(
titleId: string,
version: string,
opts: { includeLocal: boolean },
): Promise<CatalogResult> {
const sources = opts.includeLocal ? [LOCAL_SOURCE, ...ONLINE_SOURCES] : ONLINE_SOURCES;
const result: CatalogResult = { entries: [], failed: [], stale: [] };
const wanted = titleId.toUpperCase();
for (const mine of listMyTables(wanted)) {
result.entries.push({
sourceId: MINE_SOURCE_ID,
sourceName: 'Imported by you',
file: mine.file,
url: '',
titleId: wanted,
version: mine.version,
gameName: mine.name,
format: mine.format,
exact: sameVersion(mine.version, version),
});
}
const jobs = sources.flatMap((source) => source.indexes.map((index) => ({ source, index })));
const settled = await Promise.allSettled(jobs.map((j) => loadIndex(j.source, j.index)));
const found: CatalogEntry[] = [];
settled.forEach((r, i) => {
const { source, index } = jobs[i];
if (r.status === 'rejected') {
// A missing local folder is normal, not worth reporting.
if (source.id !== LOCAL_SOURCE.id && !result.failed.some((f) => f.source === source.name)) {
result.failed.push({ source: source.name, reason: r.reason instanceof Error ? r.reason.message : String(r.reason) });
}
return;
}
if (r.value.stale && !result.stale.includes(source.name)) result.stale.push(source.name);
for (const line of r.value.lines) {
const parsed = parseIndexLine(line);
if (!parsed || parsed.titleId !== wanted) continue;
found.push({
sourceId: source.id,
sourceName: source.name,
file: parsed.file,
url: index.fileBase + encodeURIComponent(parsed.file),
titleId: parsed.titleId,
version: parsed.version,
gameName: parsed.gameName,
format: parsed.format,
exact: sameVersion(parsed.version, version),
});
}
});
// A repository often carries one table in all three formats under the same
// name. JSON says the most (descriptions, buttons), so it is the one kept.
const stem = (e: CatalogEntry) => `${e.sourceId}/${e.file.replace(/\.[^.]+$/, '').toLowerCase()}`;
const best = new Map<string, CatalogEntry>();
for (const e of found) {
const have = best.get(stem(e));
if (!have || FORMAT_ORDER.indexOf(e.format) < FORMAT_ORDER.indexOf(have.format)) best.set(stem(e), e);
}
result.entries.push(...found.filter((e) => best.get(stem(e)) === e));
// Exact version matches first, then the richer formats; otherwise keep source order.
result.entries.sort((a, b) => Number(b.exact) - Number(a.exact) || FORMAT_ORDER.indexOf(a.format) - FORMAT_ORDER.indexOf(b.format));
return result;
}
/** Downloads and parses one table, keeping a copy for offline use. */
export async function loadTable(entry: CatalogEntry): Promise<CheatTable> {
if (entry.sourceId === MINE_SOURCE_ID) {
const mine = loadJson<Record<string, string>>('mine', {});
const text = mine[entry.file];
if (!text) throw new Error('That imported table is no longer saved in this browser');
return parseAnyTable(text);
}
const key = `table.${entry.sourceId}.${entry.file}`;
try {
const text = await fetchText(entry.url);
const table = parseAnyTable(text);
if (entry.sourceId !== LOCAL_SOURCE.id) saveJson(key, { at: Date.now(), text } satisfies CachedTable);
return table;
} catch (e) {
const cached = loadJson<CachedTable | null>(key, null);
if (cached) return parseAnyTable(cached.text);
throw e;
}
}
// ---- imported tables ------------------------------------------------------
function formatOf(text: string): TableFormat {
const first = text.trimStart()[0];
return first === '{' ? 'json' : first === '<' ? 'shn' : 'mc4';
}
function listMyTables(titleId: string): { file: string; version: string; name: string; format: TableFormat }[] {
const mine = loadJson<Record<string, string>>('mine', {});
const out: { file: string; version: string; name: string; format: TableFormat }[] = [];
for (const [file, text] of Object.entries(mine)) {
try {
const t = parseAnyTable(text);
if (t.titleId === titleId) out.push({ file, version: t.version, name: t.name, format: formatOf(text) });
} catch {
// skip a table that no longer parses
}
}
return out;
}
/** Saves an imported table in this browser. Returns the parsed table. */
export function importTable(fileName: string, text: string): CheatTable {
const table = parseAnyTable(text);
if (!table.titleId) throw new Error('This table does not say which game it is for');
const mine = loadJson<Record<string, string>>('mine', {});
mine[fileName] = text;
if (!saveJson('mine', mine)) throw new Error('This browser would not save the table (storage is full or blocked)');
return table;
}
+182
View File
@@ -0,0 +1,182 @@
// Cheat tables: parsing the community JSON format and applying it to a
// running game.
//
// The JSON format is the one GoldHEN and etaHEN use. A table belongs to one
// title ID and one game version. Each mod is a list of patches; a patch is an
// offset from the start of the game's executable plus the bytes for "on" and
// "off".
import { bytesEqual, hexToBytes } from './bytes.ts';
import { PROT } from './ps5debug.ts';
import type { MapEntry, Ps5Debug } from './ps5debug.ts';
export interface Patch {
offset: bigint;
on: Uint8Array;
off: Uint8Array;
}
export interface Mod {
name: string;
description: string;
/** "checkbox" mods toggle; "button" mods are applied once and have no off state. */
type: 'checkbox' | 'button';
patches: Patch[];
/** Set when the mod uses a feature this app does not handle yet. */
unsupported: string | null;
}
export interface CheatTable {
name: string;
titleId: string;
version: string;
/** Executable the offsets are relative to, normally "eboot.bin". */
process: string;
credits: string[];
mods: Mod[];
}
export type ModState = 'on' | 'off' | 'mismatch' | 'unknown';
export function parseCheatTable(text: string): CheatTable {
let raw: unknown;
try {
// Some files in the wild start with a byte-order mark.
raw = JSON.parse(text.replace(/^\uFEFF/, ''));
} catch {
throw new Error('This file is not valid JSON');
}
if (!raw || typeof raw !== 'object') throw new Error('This file is not a cheat table');
const t = raw as Record<string, unknown>;
if (!Array.isArray(t.mods)) throw new Error('This file has no "mods" list, so it is not a cheat table');
const mods: Mod[] = [];
for (const m of t.mods as Record<string, unknown>[]) {
if (!m || typeof m !== 'object') continue;
const name = String(m.name ?? 'Unnamed cheat');
const description = String(m.description ?? m.hint ?? '').trim();
const type = m.type === 'button' ? 'button' : 'checkbox';
const patches: Patch[] = [];
let unsupported: string | null = null;
for (const p of Array.isArray(m.memory) ? (m.memory as Record<string, unknown>[]) : []) {
try {
const section = p.section === undefined || p.section === null ? 0 : parseInt(String(p.section), 10) || 0;
if (section !== 0) {
// Non-zero sections are offsets into a "master code" cave, which needs
// the relocation logic etaHEN has and this app does not yet.
unsupported = 'Depends on a master code';
continue;
}
patches.push({
offset: BigInt('0x' + String(p.offset).replace(/^0x/i, '')),
on: hexToBytes(String(p.on ?? '')),
off: hexToBytes(String(p.off ?? '')),
});
} catch {
unsupported = 'Could not read this cheat';
}
}
if (patches.length === 0 && !unsupported) unsupported = 'Has no patches';
mods.push({ name, description, type, patches, unsupported });
}
return {
name: String(t.name ?? 'Unknown game'),
titleId: String(t.id ?? '').toUpperCase(),
version: String(t.version ?? ''),
process: String(t.process ?? 'eboot.bin') || 'eboot.bin',
credits: Array.isArray(t.credits) ? (t.credits as unknown[]).map(String).filter(Boolean) : [],
mods,
};
}
/**
* "01.026.000" and "1.26.0" are the same version; collections are not
* consistent about zero padding.
*/
export function normalizeVersion(v: string): string {
return v
.trim()
.split('.')
.map((part) => String(parseInt(part, 10) || 0))
.join('.');
}
export function sameVersion(a: string, b: string): boolean {
if (!a || !b) return false;
const na = normalizeVersion(a).split('.');
const nb = normalizeVersion(b).split('.');
const n = Math.max(na.length, nb.length);
for (let i = 0; i < n; i++) if ((na[i] ?? '0') !== (nb[i] ?? '0')) return false;
return true;
}
export interface ImageBase {
address: bigint;
/** Which map entry the base came from, for display. */
from: string;
}
/**
* Finds where the game's executable is loaded. Cheat offsets are relative to
* it, and it moves every launch.
*
* Debuggers label the main image's maps with the file name or the generic
* "executable", so those are tried first, then the lowest executable map.
*/
export function findImageBase(maps: MapEntry[], processName: string): ImageBase | null {
if (maps.length === 0) return null;
const wanted = processName.toLowerCase();
const named = maps.filter((m) => {
const n = m.name.toLowerCase();
return n === wanted || n === 'executable';
});
const pickLowest = (list: MapEntry[]): MapEntry => list.reduce((a, b) => (b.start < a.start ? b : a));
if (named.length) {
const m = pickLowest(named);
return { address: m.start, from: m.name };
}
// "(aux)" entries are page-table runs ps5debug-NG appends; they carry no
// module identity, so they are only a last resort.
const real = maps.filter((m) => m.name !== '(aux)');
if (real.length) maps = real;
const exec = maps.filter((m) => m.prot & PROT.EXEC);
if (exec.length) {
const m = pickLowest(exec);
return { address: m.start, from: m.name || 'first executable map' };
}
const m = pickLowest(maps);
return { address: m.start, from: m.name || 'first map' };
}
/** Reads the game's memory to work out whether a mod is currently applied. */
export async function readModState(dbg: Ps5Debug, pid: number, base: bigint, mod: Mod): Promise<ModState> {
if (mod.unsupported || mod.patches.length === 0) return 'unknown';
let allOn = true;
let allOff = true;
for (const p of mod.patches) {
const len = Math.max(p.on.length, p.off.length);
if (len === 0) return 'unknown';
const cur = await dbg.read(pid, base + p.offset, len);
if (!bytesEqual(cur.subarray(0, p.on.length), p.on)) allOn = false;
if (!bytesEqual(cur.subarray(0, p.off.length), p.off)) allOff = false;
}
// Button mods often list identical on/off bytes, so "on" wins a tie only
// when the two actually differ somewhere.
const distinguishable = mod.patches.some((p) => !bytesEqual(p.on, p.off));
if (!distinguishable) return 'unknown';
if (allOn) return 'on';
if (allOff) return 'off';
return 'mismatch';
}
/** Writes a mod's "on" or "off" bytes. */
export async function applyMod(dbg: Ps5Debug, pid: number, base: bigint, mod: Mod, on: boolean): Promise<void> {
if (mod.unsupported) throw new Error(mod.unsupported);
for (const p of mod.patches) {
const data = on ? p.on : p.off;
if (data.length === 0) continue;
await dbg.write(pid, base + p.offset, data);
}
}
+229
View File
@@ -0,0 +1,229 @@
// The console's game library: which games are installed, what they are
// called, how big they are, and starting one.
//
// The debugger cannot answer any of this, so it comes from the CheatSpecter
// payload on the console, which hands over the system's own metadata files
// untouched. Reading them happens here: param.json for PS5 titles, the older
// binary param.sfo for PS4 ones.
import { loadJson, saveJson } from './storage.ts';
import type { Target } from './session.ts';
export type Platform = 'PS5' | 'PS4';
export interface TitleMeta {
name: string;
/** As the game reports it, e.g. "01.009.000" (PS5) or "01.07" (PS4). Empty when not stated. */
version: string;
platform: Platform;
}
export interface LibraryTitle {
id: string;
platform: Platform;
/** Bytes on disk; 0 when the console's install folder for it was not found. */
size: number;
/** True when the game has more files than the console counts in one go, so the real size is larger. */
partial: boolean;
/** Where it is installed, or '' when not found. */
path: string;
}
/** The payload is not loaded on this console, so the library cannot be read. */
export class LibraryUnavailable extends Error {
constructor() {
super('The CheatSpecter payload is not running on the console');
this.name = 'LibraryUnavailable';
}
}
// ---- reading the metadata files ---------------------------------------------
function text(v: unknown): string {
return typeof v === 'string' ? v.trim() : '';
}
/** PS5 `param.json`. Returns null when it holds no usable name. */
export function parseParamJson(source: string): TitleMeta | null {
let doc: unknown;
try {
doc = JSON.parse(source);
} catch {
return null;
}
if (!doc || typeof doc !== 'object') return null;
const root = doc as Record<string, unknown>;
const localized = root.localizedParameters;
let name = '';
if (localized && typeof localized === 'object') {
const table = localized as Record<string, unknown>;
const pick = (lang: unknown): string => {
const entry = typeof lang === 'string' ? table[lang] : undefined;
return entry && typeof entry === 'object' ? text((entry as Record<string, unknown>).titleName) : '';
};
name = pick(table.defaultLanguage) || pick('en-US') || pick('en-GB');
if (!name) {
for (const key of Object.keys(table)) {
name = pick(key);
if (name) break;
}
}
}
name ||= text(root.titleName);
if (!name) return null;
return { name, version: text(root.contentVersion), platform: 'PS5' };
}
/** Every entry of a PS4 `param.sfo`, or null when the bytes are not one. */
export function parseSfo(bytes: Uint8Array): Record<string, string | number> | null {
if (bytes.length < 20) return null;
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
if (view.getUint32(0, false) !== 0x00505346) return null; // "\0PSF"
const keyTable = view.getUint32(8, true);
const dataTable = view.getUint32(12, true);
const count = view.getUint32(16, true);
if (count > 4096 || 20 + count * 16 > bytes.length || keyTable > bytes.length || dataTable > bytes.length) return null;
const utf8 = new TextDecoder('utf-8');
const out: Record<string, string | number> = {};
for (let i = 0; i < count; i++) {
const at = 20 + i * 16;
const keyStart = keyTable + view.getUint16(at, true);
const format = view.getUint16(at + 2, true);
const length = view.getUint32(at + 4, true);
const dataStart = dataTable + view.getUint32(at + 12, true);
let keyEnd = keyStart;
while (keyEnd < bytes.length && bytes[keyEnd] !== 0) keyEnd++;
if (keyStart >= bytes.length || dataStart + length > bytes.length) return null;
const key = utf8.decode(bytes.subarray(keyStart, keyEnd));
if (format === 0x0404) {
if (length >= 4) out[key] = view.getUint32(dataStart, true);
} else {
let end = dataStart;
while (end < dataStart + length && bytes[end] !== 0) end++;
out[key] = utf8.decode(bytes.subarray(dataStart, end));
}
}
return out;
}
/** PS4 `param.sfo`. Returns null when it holds no usable name. */
export function parseParamSfo(bytes: Uint8Array): TitleMeta | null {
const sfo = parseSfo(bytes);
if (!sfo) return null;
const name = text(sfo.TITLE);
if (!name) return null;
return { name, version: text(sfo.APP_VER) || text(sfo.VERSION), platform: 'PS4' };
}
// ---- talking to the payload --------------------------------------------------
export function consoleApiUrl(target: Target | null, path: string): string {
// Served from the console itself, the payload is this very server. Through
// the bridge on a computer, the bridge needs to know which console to ask.
return target ? `${path}?host=${encodeURIComponent(target.host)}` : path;
}
export function iconUrl(target: Target | null, titleId: string): string {
return consoleApiUrl(target, `api/appmeta/${titleId}/icon0.png`);
}
async function get(target: Target | null, path: string): Promise<Response | null> {
let res: Response;
try {
res = await fetch(consoleApiUrl(target, path), { cache: 'no-store' });
} catch {
throw new LibraryUnavailable();
}
// 502: the bridge found nothing listening on the console. 404 on the library
// itself: an older payload from before it had one.
if (res.status === 502) throw new LibraryUnavailable();
return res.ok ? res : null;
}
export async function fetchLibrary(target: Target | null): Promise<LibraryTitle[]> {
const res = await get(target, 'api/library');
if (!res) throw new LibraryUnavailable();
let doc: { titles?: unknown };
try {
doc = (await res.json()) as { titles?: unknown };
} catch {
throw new LibraryUnavailable();
}
if (!Array.isArray(doc.titles)) throw new LibraryUnavailable();
const out: LibraryTitle[] = [];
for (const raw of doc.titles as Record<string, unknown>[]) {
if (!raw || typeof raw.id !== 'string' || !/^[A-Z]{4}\d{5}$/.test(raw.id)) continue;
out.push({
id: raw.id,
platform: raw.meta === 'sfo' ? 'PS4' : 'PS5',
size: typeof raw.size === 'number' && raw.size > 0 ? raw.size : 0,
partial: raw.partial === true,
path: typeof raw.path === 'string' ? raw.path : '',
});
}
return out;
}
const NAME_CACHE = 'titles';
type NameCache = Record<string, TitleMeta>;
/** A name seen before for this title, for showing something at once. */
export function cachedMeta(titleId: string): TitleMeta | null {
return loadJson<NameCache>(NAME_CACHE, {})[titleId] ?? null;
}
function remember(titleId: string, meta: TitleMeta): void {
const cache = loadJson<NameCache>(NAME_CACHE, {});
cache[titleId] = meta;
saveJson(NAME_CACHE, cache);
}
/**
* A title's name and version from the console. `hint` says which file to try
* first; without it the title ID decides (PPSA titles are PS5 ones). Returns
* null when the console has no metadata for it.
*/
export async function fetchTitleMeta(target: Target | null, titleId: string, hint?: Platform): Promise<TitleMeta | null> {
const first: Platform = hint ?? (titleId.startsWith('PPSA') ? 'PS5' : 'PS4');
for (const platform of first === 'PS5' ? (['PS5', 'PS4'] as const) : (['PS4', 'PS5'] as const)) {
const res = await get(target, `api/appmeta/${titleId}/${platform === 'PS5' ? 'param.json' : 'param.sfo'}`);
if (!res) continue;
const meta = platform === 'PS5' ? parseParamJson(await res.text()) : parseParamSfo(new Uint8Array(await res.arrayBuffer()));
if (meta) {
remember(titleId, meta);
return meta;
}
}
return null;
}
/** Closes the running game, if any, and starts this one. Throws with a readable reason on failure. */
export async function launchTitle(target: Target | null, titleId: string): Promise<void> {
let res: Response;
try {
res = await fetch(consoleApiUrl(target, `api/launch/${titleId}`), { method: 'POST', cache: 'no-store' });
} catch {
throw new LibraryUnavailable();
}
if (res.status === 502) throw new LibraryUnavailable();
let doc: { ok?: boolean; error?: string; code?: string } = {};
try {
doc = (await res.json()) as typeof doc;
} catch {
// fall through to the generic message
}
if (res.ok && doc.ok) return;
throw new Error(`${doc.error ?? `The console did not start the game (HTTP ${res.status})`}${doc.code ? ` (${doc.code})` : ''}`);
}
export function formatSize(bytes: number): string {
if (!(bytes > 0)) return '';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let value = bytes;
let unit = 0;
while (value >= 1024 && unit < units.length - 1) {
value /= 1024;
unit++;
}
return `${value >= 100 || unit === 0 ? Math.round(value) : value.toFixed(1)} ${units[unit]}`;
}
+215
View File
@@ -0,0 +1,215 @@
// Where something lives in a running game, described in a way that survives
// restarts (and, for signatures, game updates).
import { PROT } from './ps5debug.ts';
import type { MapEntry, Ps5Debug } from './ps5debug.ts';
import { findImageBase } from './cheats.ts';
import { fmtAddr, view } from './bytes.ts';
import { parsePattern } from './x86.ts';
import type { AsyncX86 } from './x86.ts';
export type Location =
/** Offset from the start of the game's executable. Breaks when the game is updated. */
| { kind: 'module'; offset: string }
/** A byte pattern found in the game's code, plus a distance from where it matched. Survives most updates. */
| { kind: 'signature'; pattern: string; offset: number }
/**
* A pointer path, Cheat Engine style: read the pointer stored at
* executable+base, add offsets[0], read again, ... and add the last offset
* without reading. For values on the heap, which move every launch.
*/
| { kind: 'pointer'; base: string; offsets: string[] }
/** A raw address. Only good until the game restarts. */
| { kind: 'address'; address: string };
/** Everything the workbench needs to know about the game it is working on. */
export interface GameContext {
pid: number;
processName: string;
/** Connection for quick commands. Called each time because it can be replaced. */
dbg: () => Ps5Debug;
/** Connection for long-running searches. */
scanDbg: () => Ps5Debug;
x86: AsyncX86;
/** Assembles code on the console. Uses a throwaway connection, because an assembler error ends the one it is sent on. */
assemble: (base: bigint, text: string) => Promise<Uint8Array>;
/** Memory map, cached. Pass true to re-read it. */
maps: (refresh?: boolean) => Promise<MapEntry[]>;
/** Signatures already located this session. */
signatureCache: Map<string, bigint>;
}
export function createGameContext(opts: {
pid: number;
processName?: string;
dbg: () => Ps5Debug;
scanDbg?: () => Ps5Debug;
x86: AsyncX86;
assemble?: (base: bigint, text: string) => Promise<Uint8Array>;
}): GameContext {
let cached: MapEntry[] | null = null;
return {
pid: opts.pid,
processName: opts.processName ?? 'eboot.bin',
dbg: opts.dbg,
scanDbg: opts.scanDbg ?? opts.dbg,
x86: opts.x86,
assemble: opts.assemble ?? ((base, text) => opts.dbg().assemble(base, text)),
signatureCache: new Map(),
maps: async (refresh) => {
if (!cached || refresh) cached = await opts.dbg().maps(opts.pid);
return cached;
},
};
}
const hex = (text: string): bigint => {
const t = text.trim().replace(/^0x/i, '');
if (!/^[0-9a-fA-F]+$/.test(t)) throw new Error(`"${text}" is not a hex number`);
return BigInt('0x' + t);
};
export async function imageBase(ctx: GameContext): Promise<bigint> {
const base = findImageBase(await ctx.maps(), ctx.processName);
if (!base) throw new Error('Could not work out where the game is loaded');
return base.address;
}
/**
* The address range of the game's own executable: its code and its static
* data. Used to recognise "this pointer is stored in the game image", which
* is what makes a pointer path stable.
*/
export async function imageRange(ctx: GameContext): Promise<{ start: bigint; end: bigint }> {
const maps = await ctx.maps();
const base = findImageBase(maps, ctx.processName);
if (!base) throw new Error('Could not work out where the game is loaded');
const first = maps.find((m) => m.start === base.address);
const name = first?.name ?? '';
// The image is the run of touching maps that carry the same name as its first one.
const sorted = [...maps].sort((a, b) => (a.start < b.start ? -1 : 1));
let end = first ? first.end : base.address;
for (const m of sorted) {
if (m.start < end || m.name !== name) continue;
if (m.start === end) end = m.end;
else break;
}
return { start: base.address, end };
}
export interface PatternMatch {
address: bigint;
/** False when the pattern also matches somewhere else. */
unique: boolean;
}
/** Searches the game's code (or all readable memory) for a byte pattern. */
export async function findPattern(ctx: GameContext, text: string, where: 'code' | 'all' = 'code'): Promise<PatternMatch | null> {
const { pattern, mask } = parsePattern(text);
// Unreadable memory is searched as zeros, so a pattern of only zeros would "match" there.
if (pattern.every((b, i) => mask[i] === 0 || b === 0)) throw new Error('A pattern made only of 00 bytes matches almost anywhere. Add some other bytes.');
const maps = await ctx.maps(true);
const regions = maps.filter((m) => m.prot & PROT.READ && (where === 'all' || m.prot & PROT.EXEC) && m.end > m.start);
let first: bigint | null = null;
const MAX = 0x40000000;
for (const m of regions) {
for (let start = m.start; start < m.end; ) {
const remaining = m.end - start;
const length = remaining > BigInt(MAX) ? MAX : Number(remaining);
for (const nth of [1, 2]) {
const hit = await ctx.scanDbg().aobScan({ pid: ctx.pid, address: start, length, pattern, mask, nth });
if (hit === 0n) break;
if (first === null) first = hit;
else if (hit !== first) return { address: first, unique: false };
}
// Overlap slices by the pattern length so a match across the seam is not lost.
const step = BigInt(length) - BigInt(pattern.length - 1);
start += remaining > BigInt(MAX) ? step : remaining;
}
}
return first === null ? null : { address: first, unique: true };
}
export class LocationError extends Error {
constructor(message: string) {
super(message);
this.name = 'LocationError';
}
}
/** Turns a Location into the address it means right now. */
export async function resolveLocation(ctx: GameContext, loc: Location): Promise<bigint> {
switch (loc.kind) {
case 'address':
return hex(loc.address);
case 'module':
return (await imageBase(ctx)) + hex(loc.offset);
case 'signature': {
let at = ctx.signatureCache.get(loc.pattern);
if (at === undefined) {
const match = await findPattern(ctx, loc.pattern, 'code');
if (!match) throw new LocationError('The byte pattern was not found in this game. It may be for a different version.');
if (!match.unique) throw new LocationError('The byte pattern matches in more than one place, so it is not safe to use.');
at = match.address;
ctx.signatureCache.set(loc.pattern, at);
}
return at + BigInt(loc.offset);
}
case 'pointer': {
if (loc.offsets.length === 0) throw new LocationError('A pointer path needs at least one offset');
let addr = (await imageBase(ctx)) + hex(loc.base);
for (let i = 0; i < loc.offsets.length; i++) {
const raw = await ctx.dbg().read(ctx.pid, addr, 8);
const ptr = view(raw).getBigUint64(0, true);
if (ptr < 0x10000n) {
throw new LocationError('The pointer path leads nowhere right now. The game may not have loaded that part yet (try again in-game).');
}
addr = ptr + signedHex(loc.offsets[i]);
if (i === loc.offsets.length - 1) return addr;
}
return addr;
}
}
}
function signedHex(text: string): bigint {
const t = text.trim();
return t.startsWith('-') ? -hex(t.slice(1)) : hex(t);
}
export function describeLocation(loc: Location): string {
switch (loc.kind) {
case 'address':
return fmtAddr(hex(loc.address));
case 'module':
return `game+${fmtAddr(hex(loc.offset))}`;
case 'signature':
return `pattern ${loc.pattern}${loc.offset ? (loc.offset > 0 ? ` +${loc.offset}` : ` ${loc.offset}`) : ''}`;
case 'pointer': {
let s = `[game+${fmtAddr(hex(loc.base))}]`;
loc.offsets.forEach((o, i) => {
s = i === loc.offsets.length - 1 ? `${s}+${o}` : `[${s}+${o}]`;
});
return s;
}
}
}
/**
* Parses what someone types into an address box: a hex address, or
* "game+1A2B" for an offset into the executable.
*/
export async function parseAddress(ctx: GameContext, text: string): Promise<bigint> {
const t = text.trim().replace(/\s+/g, '');
if (!t) throw new Error('Enter an address');
const m = /^(?:game|base|eboot(?:\.bin)?)\+(.+)$/i.exec(t);
if (m) return (await imageBase(ctx)) + hex(m[1]);
return hex(t);
}
/** The best lasting description of an address inside the game's executable, or null if it is elsewhere. */
export async function moduleLocation(ctx: GameContext, address: bigint): Promise<Location | null> {
const range = await imageRange(ctx);
if (address < range.start || address >= range.end) return null;
return { kind: 'module', offset: (address - range.start).toString(16).toUpperCase() };
}
+51
View File
@@ -0,0 +1,51 @@
// Turning something found in the game into a saved cheat.
import { bytesToHex } from './bytes.ts';
import { findPattern, moduleLocation } from './locations.ts';
import type { GameContext, Location } from './locations.ts';
import { newId } from './table.ts';
import type { PatchEntry, ValueEntry } from './table.ts';
import { signatureFromCode } from './x86.ts';
import type { Insn } from './x86.ts';
import type { ValueKind } from './scanner.ts';
/**
* The most durable way to refer to a spot in the game's code. A byte
* signature is tried first, growing until it matches in exactly one place;
* that keeps working after most game updates. Failing that, an offset into
* the executable (good until the next update), then the raw address.
*/
export async function codeLocation(ctx: GameContext, address: bigint): Promise<Location> {
try {
const bytes = await ctx.dbg().read(ctx.pid, address, 64);
const insns = await ctx.x86.disassemble(bytes, address, 16);
for (const min of [8, 12, 16, 24, 32]) {
const sig = signatureFromCode(insns, min);
if (sig.length < 5) continue;
const match = await findPattern(ctx, sig.text, 'code');
if (match && match.unique && match.address === address) return { kind: 'signature', pattern: sig.text, offset: 0 };
if (!match) break; // the code changed under us; do not keep trying
}
} catch {
// fall through to an offset
}
return (await moduleLocation(ctx, address)) ?? { kind: 'address', address: address.toString(16).toUpperCase() };
}
/** A switch that removes one instruction by overwriting it with no-ops. */
export async function nopEntry(ctx: GameContext, insn: Insn, name?: string): Promise<PatchEntry> {
return {
id: newId(),
type: 'patch',
name: name ?? `Skip "${insn.text}"`,
at: await codeLocation(ctx, insn.address),
on: '90'.repeat(insn.length),
off: bytesToHex(insn.bytes),
};
}
/** A value to set or hold. Uses an executable offset when the value is static, else the raw address. */
export async function valueEntry(ctx: GameContext, address: bigint, kind: ValueKind, value: string, at?: Location): Promise<ValueEntry> {
const loc = at ?? (await moduleLocation(ctx, address)) ?? { kind: 'address' as const, address: address.toString(16).toUpperCase() };
return { id: newId(), type: 'value', name: `Value at 0x${address.toString(16).toUpperCase()}`, at: loc, valueType: kind.id, value, freeze: true };
}
+108
View File
@@ -0,0 +1,108 @@
// Finding a pointer path to a value.
//
// Game values usually sit on the heap, at an address that changes every
// launch. What stays put is a chain: a pointer at a fixed spot in the game's
// executable leads to an object, which holds a pointer to another, and so on
// until the value. This works backwards from the value: look for anything
// that points at (or just below) it, check whether that pointer is stored in
// the executable, and if not, repeat one level up.
import { COMPARE, VALUE_TYPE } from './ps5debug.ts';
import { view } from './bytes.ts';
import { imageRange } from './locations.ts';
import type { GameContext, Location } from './locations.ts';
import { scannableRegions } from './scanner.ts';
export interface PointerPath {
location: Location & { kind: 'pointer' };
depth: number;
}
export interface PointerScanOptions {
/** How many pointers deep to look (1-4). */
maxDepth?: number;
/** Largest distance from a pointer's target to the thing it leads to. */
maxOffset?: number;
/** How many candidates to follow up per level. */
fanout?: number;
/** Stop once this many paths are found. */
maxResults?: number;
}
interface Candidate {
/** Where the pointer is stored. */
at: bigint;
/** Distance from the pointer's value to the thing we were looking for. */
offset: bigint;
}
export async function findPointerPaths(
ctx: GameContext,
target: bigint,
opts: PointerScanOptions,
onProgress: (text: string) => void,
): Promise<PointerPath[]> {
const maxDepth = Math.max(1, Math.min(4, opts.maxDepth ?? 3));
const maxOffset = BigInt(opts.maxOffset ?? 0x1000);
const fanout = opts.fanout ?? 6;
const maxResults = opts.maxResults ?? 20;
const dbg = ctx.scanDbg();
if (!dbg.authed) await dbg.auth();
const image = await imageRange(ctx);
const regions = scannableRegions(await ctx.maps(true));
const results: PointerPath[] = [];
const seen = new Set<bigint>();
/** Everything in writable memory that points into [addr - maxOffset, addr]. */
const pointersTo = async (addr: bigint): Promise<Candidate[]> => {
const lo = addr > maxOffset ? addr - maxOffset : 0n;
const value = new Uint8Array(16);
view(value).setBigUint64(0, lo, true);
view(value).setBigUint64(8, addr, true);
const found: Candidate[] = [];
for (const region of regions) {
await dbg.scanStart(
{ pid: ctx.pid, address: region.start, length: region.length, valueType: VALUE_TYPE.U64, compareType: COMPARE.BETWEEN, alignment: 8, value },
(block) => {
const dv = view(block.records);
// A generous cap; the list is sorted by offset afterwards, so the best ones are kept.
for (let i = 0; i < block.count && found.length < 200_000; i++) {
const at = region.start + BigInt(dv.getUint32(i * 12, true));
found.push({ at, offset: addr - dv.getBigUint64(i * 12 + 4, true) });
}
},
);
}
// Small offsets first: a field near the start of an object is the likelier real path.
return found.sort((a, b) => (a.offset < b.offset ? -1 : a.offset > b.offset ? 1 : 0));
};
const hexOf = (n: bigint) => '0x' + n.toString(16).toUpperCase();
// Breadth first, so the shortest paths come out first.
let frontier: { addr: bigint; tail: string[] }[] = [{ addr: target, tail: [] }];
for (let depth = 1; depth <= maxDepth && frontier.length && results.length < maxResults; depth++) {
const next: { addr: bigint; tail: string[] }[] = [];
let n = 0;
for (const node of frontier) {
onProgress(`Level ${depth} of ${maxDepth}: checking ${++n} of ${frontier.length}`);
const cands = await pointersTo(node.addr);
let followed = 0;
for (const c of cands) {
const tail = [hexOf(c.offset), ...node.tail];
if (c.at >= image.start && c.at < image.end) {
results.push({ location: { kind: 'pointer', base: (c.at - image.start).toString(16).toUpperCase(), offsets: tail }, depth });
if (results.length >= maxResults) break;
} else if (followed < fanout && !seen.has(c.at)) {
seen.add(c.at);
followed++;
next.push({ addr: c.at, tail });
}
}
if (results.length >= maxResults) break;
}
frontier = next;
}
return results;
}
+1021
View File
File diff suppressed because it is too large. Load diff
+583
View File
@@ -0,0 +1,583 @@
// Memory scanning: a first pass over the game's writable memory, then rescans
// that narrow the candidate list. The console does the comparing; this side
// keeps the candidates and re-uploads them each pass.
import { PROT, COMPARE, VALUE_TYPE, compareNeedsPrevious, valueTypeSize } from './ps5debug.ts';
import type { MapEntry, Ps5Debug, ScanBlock } from './ps5debug.ts';
import { concat, view } from './bytes.ts';
export interface ValueKind {
id: string;
label: string;
wire: number;
size: number;
float: boolean;
signed: boolean;
}
export const VALUE_KINDS: ValueKind[] = [
{ id: 'u32', label: '4 bytes', wire: VALUE_TYPE.U32, size: 4, float: false, signed: false },
{ id: 'float', label: 'Float', wire: VALUE_TYPE.FLOAT, size: 4, float: true, signed: true },
{ id: 'u16', label: '2 bytes', wire: VALUE_TYPE.U16, size: 2, float: false, signed: false },
{ id: 'u8', label: '1 byte', wire: VALUE_TYPE.U8, size: 1, float: false, signed: false },
{ id: 'u64', label: '8 bytes', wire: VALUE_TYPE.U64, size: 8, float: false, signed: false },
{ id: 'double', label: 'Double', wire: VALUE_TYPE.DOUBLE, size: 8, float: true, signed: true },
{ id: 'i32', label: '4 bytes (signed)', wire: VALUE_TYPE.I32, size: 4, float: false, signed: true },
{ id: 'i16', label: '2 bytes (signed)', wire: VALUE_TYPE.I16, size: 2, float: false, signed: true },
{ id: 'i8', label: '1 byte (signed)', wire: VALUE_TYPE.I8, size: 1, float: false, signed: true },
{ id: 'i64', label: '8 bytes (signed)', wire: VALUE_TYPE.I64, size: 8, float: false, signed: true },
];
export function valueKind(id: string): ValueKind {
const k = VALUE_KINDS.find((x) => x.id === id);
if (!k) throw new Error(`Unknown value type "${id}"`);
return k;
}
export interface CompareKind {
id: string;
label: string;
wire: number;
/** How many values the user types in. */
inputs: 0 | 1 | 2;
/** Usable for the first scan (no previous values exist yet). */
first: boolean;
}
/** What the search screen needs from a scan, whichever way it is carried out. */
export interface Scan {
readonly kind: ValueKind;
readonly passes: number;
readonly matches: number;
first(regions: ScanRegion[], compare: CompareKind, value: Uint8Array, onProgress: (p: ScanProgress) => void): Promise<void>;
next(compare: CompareKind, value: Uint8Array, onProgress: (p: ScanProgress) => void): Promise<void>;
hits(limit: number): Promise<ScanHit[]>;
/** Releases anything held on the console. */
end(): Promise<void>;
}
export const COMPARE_KINDS: CompareKind[] = [
{ id: 'unknown', label: 'Unknown (I cannot see a number)', wire: COMPARE.UNKNOWN, inputs: 0, first: true },
{ id: 'exact', label: 'Exactly', wire: COMPARE.EXACT, inputs: 1, first: true },
{ id: 'bigger', label: 'Bigger than', wire: COMPARE.BIGGER, inputs: 1, first: true },
{ id: 'smaller', label: 'Smaller than', wire: COMPARE.SMALLER, inputs: 1, first: true },
{ id: 'between', label: 'Between', wire: COMPARE.BETWEEN, inputs: 2, first: true },
{ id: 'increased', label: 'Went up', wire: COMPARE.INCREASED, inputs: 0, first: false },
{ id: 'decreased', label: 'Went down', wire: COMPARE.DECREASED, inputs: 0, first: false },
{ id: 'changed', label: 'Changed', wire: COMPARE.CHANGED, inputs: 0, first: false },
{ id: 'unchanged', label: 'Stayed the same', wire: COMPARE.UNCHANGED, inputs: 0, first: false },
];
export function compareKind(id: string): CompareKind {
const k = COMPARE_KINDS.find((x) => x.id === id);
if (!k) throw new Error(`Unknown comparison "${id}"`);
return k;
}
/** Parses what the user typed. Integers accept decimal or 0x hex. */
export function encodeValue(kind: ValueKind, text: string): Uint8Array {
const t = text.trim();
if (t === '') throw new Error('Enter a value');
const out = new Uint8Array(kind.size);
const dv = view(out);
if (kind.float) {
const n = Number(t);
if (!Number.isFinite(n)) throw new Error(`"${text}" is not a number`);
if (kind.size === 4) dv.setFloat32(0, n, true);
else dv.setFloat64(0, n, true);
return out;
}
let big: bigint;
try {
big = BigInt(t);
} catch {
throw new Error(`"${text}" is not a whole number`);
}
const bits = kind.size * 8;
const min = kind.signed ? -(1n << BigInt(bits - 1)) : 0n;
const max = kind.signed ? (1n << BigInt(bits - 1)) - 1n : (1n << BigInt(bits)) - 1n;
if (big < min || big > max) throw new Error(`${text} does not fit in ${kind.label}`);
if (kind.size === 8) dv.setBigUint64(0, BigInt.asUintN(64, big), true);
else writeSmallInt(dv, kind.size, Number(BigInt.asUintN(bits, big)));
return out;
}
function writeSmallInt(dv: DataView, size: number, v: number): void {
if (size === 1) dv.setUint8(0, v);
else if (size === 2) dv.setUint16(0, v, true);
else dv.setUint32(0, v, true);
}
export function decodeValue(kind: ValueKind, bytes: Uint8Array): string {
const dv = view(bytes);
if (kind.float) {
const n = kind.size === 4 ? dv.getFloat32(0, true) : dv.getFloat64(0, true);
if (!Number.isFinite(n)) return String(n);
const s = n.toPrecision(kind.size === 4 ? 7 : 12);
return String(Number(s));
}
switch (kind.size) {
case 1:
return String(kind.signed ? dv.getInt8(0) : dv.getUint8(0));
case 2:
return String(kind.signed ? dv.getInt16(0, true) : dv.getUint16(0, true));
case 4:
return String(kind.signed ? dv.getInt32(0, true) : dv.getUint32(0, true));
default:
return String(kind.signed ? dv.getBigInt64(0, true) : dv.getBigUint64(0, true));
}
}
/** One slice of memory and the candidates found in it. */
interface Slice {
base: bigint;
length: number;
/** Packed (u32 offset, value) records, in address order. */
records: Uint8Array;
count: number;
}
export interface ScanRegion {
start: bigint;
length: number;
}
export interface ScanProgress {
/** 0..1 */
fraction: number;
matches: number;
detail: string;
}
export interface ScanHit {
address: bigint;
value: Uint8Array;
/** Set by an "Auto" search, where each hit can be of a different type. */
kind?: ValueKind;
}
/** Slices are capped so each one's offsets fit in a u32 and progress moves steadily. */
const SLICE_BYTES = 64 * 1024 * 1024;
/**
* Candidate limit. Past this the result set is not worth keeping in a browser
* tab (or on a phone), and the right move is a more specific first scan.
*/
export const MAX_MATCHES = 4_000_000;
export class TooManyMatchesError extends Error {
constructor() {
super(
`More than ${MAX_MATCHES.toLocaleString()} matches. Try a less common value ` +
'(0 and 1 are everywhere), or change the value in the game and scan for the new one.',
);
this.name = 'TooManyMatchesError';
}
}
/**
* Picks the memory worth scanning: readable and writable, not code. Game
* values live in data, heap and stack; scanning executable pages only adds
* noise.
*/
export function scannableRegions(maps: MapEntry[]): ScanRegion[] {
const wanted = maps
.filter((m) => m.prot & PROT.READ && m.prot & PROT.WRITE && !(m.prot & PROT.EXEC) && m.end > m.start)
.sort((x, y) => (x.start < y.start ? -1 : x.start > y.start ? 1 : 0));
// ps5debug-NG adds page-table-derived "(aux)" entries to the map, and those
// can overlap the regular ones. Merge into disjoint ranges so nothing is
// scanned (and counted) twice.
const merged: { start: bigint; end: bigint }[] = [];
for (const m of wanted) {
const last = merged[merged.length - 1];
if (last && m.start <= last.end) {
if (m.end > last.end) last.end = m.end;
} else {
merged.push({ start: m.start, end: m.end });
}
}
const out: ScanRegion[] = [];
for (const m of merged) {
let start = m.start;
let remaining = m.end - m.start;
while (remaining > 0n) {
const take = remaining > BigInt(SLICE_BYTES) ? SLICE_BYTES : Number(remaining);
out.push({ start, length: take });
start += BigInt(take);
remaining -= BigInt(take);
}
}
return out;
}
class BlockCollector {
private parts: Uint8Array[] = [];
count = 0;
add(block: ScanBlock): void {
if (block.count === 0) return;
this.parts.push(block.records);
this.count += block.count;
}
take(): Uint8Array {
const out = this.parts.length === 1 ? this.parts[0] : concat(...this.parts);
this.parts = [];
return out;
}
}
export class ScanSession implements Scan {
readonly kind: ValueKind;
readonly pid: number;
/** Number of completed passes. */
passes = 0;
private slices: Slice[] = [];
private getDbg: () => Ps5Debug;
/**
* `getDbg` is called at the start of every pass rather than once, because
* the connection can be replaced between passes (the console drops it after
* certain errors and the session opens a new one).
*/
constructor(getDbg: () => Ps5Debug, pid: number, kind: ValueKind) {
this.getDbg = getDbg;
this.pid = pid;
this.kind = kind;
}
get matches(): number {
let n = 0;
for (const s of this.slices) n += s.count;
return n;
}
/** First pass over every scannable region. */
async first(
regions: ScanRegion[],
compare: CompareKind,
value: Uint8Array,
onProgress: (p: ScanProgress) => void,
): Promise<void> {
if (!compare.first) throw new Error(`"${compare.label}" needs an earlier scan to compare against`);
const dbg = this.getDbg();
if (!dbg.authed) await dbg.auth();
const total = regions.reduce((n, r) => n + r.length, 0);
let done = 0;
let matches = 0;
const slices: Slice[] = [];
for (const region of regions) {
const collector = new BlockCollector();
await dbg.scanStart(
{
pid: this.pid,
address: region.start,
length: region.length,
valueType: this.kind.wire,
compareType: compare.wire,
alignment: this.kind.size,
value,
},
(block) => {
// Keep draining after the limit so the stream stays in step.
if (matches + collector.count <= MAX_MATCHES) collector.add(block);
else collector.count += block.count;
},
);
matches += collector.count;
if (matches > MAX_MATCHES) throw new TooManyMatchesError();
if (collector.count > 0) {
slices.push({ base: region.start, length: region.length, records: collector.take(), count: collector.count });
}
done += region.length;
onProgress({ fraction: total ? done / total : 1, matches, detail: '' });
}
this.slices = slices;
this.passes = 1;
}
/**
* Narrows the current candidates. The console requires each uploaded chunk
* to be in ascending address order with a common alignment; that holds
* because first() scans aligned and results are never reordered.
*/
async next(compare: CompareKind, value: Uint8Array, onProgress: (p: ScanProgress) => void): Promise<void> {
if (this.passes === 0) throw new Error('Run a first scan before narrowing down');
const dbg = this.getDbg();
if (!dbg.authed) await dbg.auth();
const recordSize = 4 + this.kind.size;
const withPrevious = compareNeedsPrevious(compare.wire);
const before = this.matches;
let processed = 0;
let matches = 0;
const kept: Slice[] = [];
for (const slice of this.slices) {
const candidates = withPrevious ? slice.records : stripValues(slice.records, recordSize);
const collector = new BlockCollector();
await dbg.scanCount(
{
pid: this.pid,
base: slice.base,
valueType: this.kind.wire,
compareType: compare.wire,
value,
candidates,
},
(block) => collector.add(block),
);
if (collector.count > 0) {
kept.push({ base: slice.base, length: slice.length, records: collector.take(), count: collector.count });
matches += collector.count;
}
processed += slice.count;
onProgress({ fraction: before ? processed / before : 1, matches, detail: '' });
}
this.slices = kept;
this.passes++;
}
async end(): Promise<void> {
this.slices = [];
}
/** The first `limit` candidates with the values they had at the last pass. */
async hits(limit: number): Promise<ScanHit[]> {
const recordSize = 4 + this.kind.size;
const out: ScanHit[] = [];
for (const slice of this.slices) {
const dv = view(slice.records);
for (let i = 0; i < slice.count && out.length < limit; i++) {
const o = i * recordSize;
out.push({
address: slice.base + BigInt(dv.getUint32(o, true)),
value: slice.records.slice(o + 4, o + recordSize),
});
}
if (out.length >= limit) break;
}
return out;
}
}
function stripValues(records: Uint8Array, recordSize: number): Uint8Array {
const count = records.length / recordSize;
const out = new Uint8Array(count * 4);
for (let i = 0; i < count; i++) {
out.set(records.subarray(i * recordSize, i * recordSize + 4), i * 4);
}
return out;
}
/**
* A search that starts from "I do not know the value" (a health bar with no
* number). Every value in memory is a candidate at first, far too many to
* send to a browser, so the console keeps the list and only the count and
* the first few rows come back.
*/
export class SnapshotScan implements Scan {
readonly kind: ValueKind;
readonly pid: number;
passes = 0;
matches = 0;
private getDbg: () => Ps5Debug;
/** The connection that owns the snapshot. If it is replaced, the snapshot is gone. */
private owner: Ps5Debug | null = null;
private slots = 0;
constructor(getDbg: () => Ps5Debug, pid: number, kind: ValueKind) {
this.getDbg = getDbg;
this.pid = pid;
this.kind = kind;
}
async first(regions: ScanRegion[], _compare: CompareKind, _value: Uint8Array, onProgress: (p: ScanProgress) => void): Promise<void> {
const dbg = this.getDbg();
if (!dbg.authed) await dbg.auth();
const count = await dbg.turboSnapshot(
{ pid: this.pid, valueType: this.kind.wire, segments: regions.map((r) => ({ address: r.start, length: r.length })) },
(done, total) => onProgress({ fraction: total ? done / total : 0, matches: 0, detail: '' }),
);
if (count === null) throw new Error('The console could not hold a snapshot of this much memory. Try a search for a known value instead.');
this.owner = dbg;
this.slots = regions.reduce((n, r) => n + Math.floor(r.length / this.kind.size), 0);
this.matches = count;
this.passes = 1;
}
async next(compare: CompareKind, value: Uint8Array, onProgress: (p: ScanProgress) => void): Promise<void> {
const dbg = this.checkOwner();
this.matches = await dbg.turboNarrow({ pid: this.pid, valueType: this.kind.wire, compareType: compare.wire, value }, (done) =>
onProgress({ fraction: this.slots ? Math.min(1, done / this.slots) : 0, matches: 0, detail: '' }),
);
this.passes++;
}
async hits(limit: number): Promise<ScanHit[]> {
if (this.matches === 0) return [];
const rows = await this.checkOwner().turboGet(0, limit, this.kind.size);
return rows.map((r) => ({ address: r.address, value: r.current }));
}
async end(): Promise<void> {
const dbg = this.owner;
this.owner = null;
if (dbg && !dbg.closed) await dbg.turboEnd().catch(() => undefined);
}
private checkOwner(): Ps5Debug {
const dbg = this.getDbg();
if (!this.owner || dbg !== this.owner) {
throw new Error('The connection was reset and the console dropped this search. Start a new search.');
}
return dbg;
}
}
// ---- "Auto": not knowing the type ---------------------------------------------
/** Stands for "whichever type it turns out to be" in the type list. */
export const AUTO_KIND: ValueKind = { id: 'auto', label: 'Auto', wire: -1, size: 4, float: false, signed: false };
/**
* The types an Auto search tries, likeliest first. The 1- and 2-byte types are
* left out: a small number stored that way nearly always shows up as 4 bytes
* at the same address too, so they would only list every result twice.
*/
const AUTO_TRY = ['u32', 'float', 'double'];
/**
* A search for someone who can see a number but not how the game stores it.
* The same value is searched as each common type in turn, and the results are
* kept side by side; narrowing down narrows every one of them. It takes about
* as many times longer as there are types.
*/
export class AutoScan implements Scan {
readonly kind = AUTO_KIND;
readonly pid: number;
passes = 0;
/** Types dropped along the way, with the reason, for telling the user. */
dropped: { kind: ValueKind; reason: string }[] = [];
private parts: ScanSession[] = [];
private getDbg: () => Ps5Debug;
private texts: [string, string] = ['', ''];
constructor(getDbg: () => Ps5Debug, pid: number) {
this.getDbg = getDbg;
this.pid = pid;
}
/** The value(s) as typed. Each type reads them in its own way, so they are kept as text. */
input(value: string, value2 = ''): void {
this.texts = [value, value2];
}
get kinds(): ValueKind[] {
return this.parts.map((p) => p.kind);
}
get matches(): number {
return this.parts.reduce((n, p) => n + p.matches, 0);
}
/** The typed value as bytes for one type, or null if that type cannot hold it (99.5 is not a whole number). */
private encode(kind: ValueKind, compare: CompareKind): Uint8Array | null {
if (compare.inputs === 0) return new Uint8Array(0);
const one = (text: string): Uint8Array => {
try {
return encodeValue(kind, text);
} catch (e) {
// A negative whole number needs the signed type of the same size.
if (!kind.float && !kind.signed && /^\s*-/.test(text)) return encodeValue({ ...kind, signed: true }, text);
throw e;
}
};
try {
return compare.inputs === 1 ? one(this.texts[0]) : concat(one(this.texts[0]), one(this.texts[1]));
} catch {
return null;
}
}
async first(regions: ScanRegion[], compare: CompareKind, _value: Uint8Array, onProgress: (p: ScanProgress) => void): Promise<void> {
if (compare.inputs === 0) throw new Error('Auto needs a number to look for. Pick a type to search for an unknown value.');
const plan = AUTO_TRY.map((id) => valueKind(id))
.map((kind) => ({ kind, value: this.encode(kind, compare) }))
.filter((p): p is { kind: ValueKind; value: Uint8Array } => p.value !== null);
if (plan.length === 0) throw new Error(`"${this.texts[0]}" is not a number`);
const parts: ScanSession[] = [];
const dropped: { kind: ValueKind; reason: string }[] = [];
let found = 0;
for (let i = 0; i < plan.length; i++) {
const { kind, value } = plan[i];
const part = new ScanSession(this.getDbg, this.pid, kind);
const report = (p: ScanProgress) =>
onProgress({ fraction: (i + p.fraction) / plan.length, matches: found + p.matches, detail: `as ${kind.label.toLowerCase()}` });
try {
await part.first(regions, compare, value, report);
parts.push(part);
found += part.matches;
} catch (e) {
// One type drowning in matches should not sink the others.
if (!(e instanceof TooManyMatchesError)) throw e;
dropped.push({ kind, reason: 'too many matches' });
}
}
if (parts.length === 0) throw new TooManyMatchesError();
this.parts = parts;
this.dropped = dropped;
this.passes = 1;
}
async next(compare: CompareKind, _value: Uint8Array, onProgress: (p: ScanProgress) => void): Promise<void> {
if (this.passes === 0) throw new Error('Run a first scan before narrowing down');
const before = this.matches;
const kept: ScanSession[] = [];
let done = 0;
let found = 0;
for (const part of this.parts) {
const had = part.matches;
const value = this.encode(part.kind, compare);
if (value === null) {
// The new value cannot be this type at all, so none of its candidates survive.
this.dropped.push({ kind: part.kind, reason: 'cannot hold that value' });
} else if (had > 0) {
const base = done;
await part.next(compare, value, (p) =>
onProgress({ fraction: before ? (base + p.fraction * had) / before : 1, matches: found + p.matches, detail: `as ${part.kind.label.toLowerCase()}` }),
);
if (part.matches > 0) kept.push(part);
found += part.matches;
}
done += had;
}
this.parts = kept;
this.passes++;
}
/** A fair share of each type's hits, so one type with many leftovers cannot hide the others. */
async hits(limit: number): Promise<ScanHit[]> {
const lists: ScanHit[][] = [];
for (const part of this.parts) lists.push((await part.hits(limit)).map((h) => ({ ...h, kind: part.kind })));
const out: ScanHit[] = [];
for (let i = 0; out.length < limit && lists.some((l) => i < l.length); i++) {
for (const list of lists) if (i < list.length && out.length < limit) out.push(list[i]);
}
return out;
}
async end(): Promise<void> {
for (const part of this.parts) await part.end();
this.parts = [];
}
}
+194
View File
@@ -0,0 +1,194 @@
// Scripts: cheats with logic.
//
// A script is a few lines of JavaScript that can read and write the game's
// memory, call its functions, and switch other entries on and off:
//
// const health = await cs.address('game+1A2B3C');
// while (true) {
// if (await cs.read(health, 'u32') < 50) await cs.write(health, 'u32', 100);
// await cs.sleep(200);
// }
//
// Scripts run in a Web Worker: they cannot touch the page, an endless loop
// cannot freeze the app, and stopping one is immediate. Everything they do to
// the game goes through the small API below, which is carried out on this
// side.
import { hexToBytes, bytesToHex } from './bytes.ts';
import { findPattern, parseAddress, resolveLocation } from './locations.ts';
import type { GameContext, Location } from './locations.ts';
import { decodeValue, encodeValue, valueKind } from './scanner.ts';
export interface ScriptHostApi {
/** Switch another entry in the table on or off, by name. */
setEntry: (name: string, on: boolean) => Promise<void>;
}
type Addr = bigint | number | string;
async function toAddress(ctx: GameContext, a: Addr): Promise<bigint> {
if (typeof a === 'bigint') return a;
if (typeof a === 'number') {
if (!Number.isSafeInteger(a) || a < 0) throw new Error('Not a valid address');
return BigInt(a);
}
return parseAddress(ctx, String(a));
}
/** Carries out one API call made by a script. Kept separate from the worker plumbing so it can be tested. */
export async function handleScriptCall(ctx: GameContext, api: ScriptHostApi, method: string, args: unknown[]): Promise<unknown> {
const dbg = ctx.dbg();
switch (method) {
case 'read': {
const kind = valueKind(String(args[1] ?? 'u32'));
const raw = await dbg.read(ctx.pid, await toAddress(ctx, args[0] as Addr), kind.size);
const text = decodeValue(kind, raw);
// 64-bit integers do not fit in a JavaScript number.
return kind.size === 8 && !kind.float ? BigInt(text) : Number(text);
}
case 'write': {
const kind = valueKind(String(args[1] ?? 'u32'));
await dbg.write(ctx.pid, await toAddress(ctx, args[0] as Addr), encodeValue(kind, String(args[2])));
return undefined;
}
case 'readBytes': {
const n = Number(args[1]);
if (!Number.isInteger(n) || n < 1 || n > 0x100000) throw new Error('readBytes: length must be between 1 and 1048576');
return bytesToHex(await dbg.read(ctx.pid, await toAddress(ctx, args[0] as Addr), n), ' ');
}
case 'writeBytes': {
await dbg.write(ctx.pid, await toAddress(ctx, args[0] as Addr), hexToBytes(String(args[1])));
return undefined;
}
case 'address':
return typeof args[0] === 'object' && args[0] !== null
? resolveLocation(ctx, args[0] as Location)
: toAddress(ctx, args[0] as Addr);
case 'find': {
const match = await findPattern(ctx, String(args[0]), 'code');
return match ? match.address : null;
}
case 'pointer': {
const offsets = (args[1] as unknown[]).map((o) => (typeof o === 'string' ? o : '0x' + BigInt(o as number | bigint).toString(16)));
const base = typeof args[0] === 'string' ? args[0].replace(/^(game|base|eboot)\+/i, '') : BigInt(args[0] as number | bigint).toString(16);
return resolveLocation(ctx, { kind: 'pointer', base, offsets });
}
case 'call': {
const list = (args[1] as unknown[]).map((a) => BigInt.asUintN(64, BigInt(a as number | bigint | string)));
return dbg.call(ctx.pid, await toAddress(ctx, args[0] as Addr), list);
}
case 'enable':
return api.setEntry(String(args[0]), true);
case 'disable':
return api.setEntry(String(args[0]), false);
case 'notify':
return dbg.notify(String(args[0]).slice(0, 500));
default:
throw new Error(`Unknown script function: ${method}`);
}
}
/** What a script sees as `cs`. Shown in the editor as a reference. */
export const SCRIPT_REFERENCE = `await cs.read(address, type) // type: u8 u16 u32 u64 i8 i16 i32 i64 float double
await cs.write(address, type, value)
await cs.readBytes(address, count) // -> "89 81 90 03"
await cs.writeBytes(address, "90 90 90")
await cs.address("game+1A2B3C") // offset into the game's executable -> address
await cs.find("89 81 ?? ?? 00 00") // byte pattern in the game's code -> address or null
await cs.pointer("game+10100", 0x340) // follow a pointer path -> address
await cs.call(address, arg1, arg2) // call a game function -> its result
await cs.enable("Entry name") // switch another entry on
await cs.disable("Entry name")
await cs.notify("text") // show a notification on the TV
await cs.sleep(milliseconds)
cs.log("anything") // appears under the script`;
// Runs inside the worker. No imports: it is turned into a Blob.
const WORKER_SOURCE = `
let nextId = 1;
const pending = new Map();
function rpc(method, args) {
return new Promise((resolve, reject) => {
const id = nextId++;
pending.set(id, { resolve, reject });
postMessage({ t: 'rpc', id, method, args });
});
}
function show(x) {
if (typeof x === 'bigint') return '0x' + x.toString(16).toUpperCase();
if (typeof x === 'object' && x !== null) { try { return JSON.stringify(x, (k, v) => typeof v === 'bigint' ? '0x' + v.toString(16) : v); } catch { return String(x); } }
return String(x);
}
const cs = {
read: (address, type) => rpc('read', [address, type || 'u32']),
write: (address, type, value) => rpc('write', [address, type, typeof value === 'bigint' ? value.toString() : value]),
readBytes: (address, count) => rpc('readBytes', [address, count]),
writeBytes: (address, hex) => rpc('writeBytes', [address, hex]),
address: (what) => rpc('address', [what]),
find: (pattern) => rpc('find', [pattern]),
pointer: (base, ...offsets) => rpc('pointer', [base, offsets]),
call: (address, ...args) => rpc('call', [address, args]),
enable: (name) => rpc('enable', [name]),
disable: (name) => rpc('disable', [name]),
notify: (text) => rpc('notify', [String(text)]),
sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
log: (...parts) => postMessage({ t: 'log', line: parts.map(show).join(' ') }),
};
onmessage = async (e) => {
const m = e.data;
if (m.t === 'res') {
const p = pending.get(m.id);
pending.delete(m.id);
if (p) (m.error ? p.reject(new Error(m.error)) : p.resolve(m.value));
} else if (m.t === 'run') {
try {
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
await new AsyncFunction('cs', m.code)(cs);
postMessage({ t: 'done' });
} catch (err) {
postMessage({ t: 'done', error: String((err && err.message) || err) });
}
}
};
`;
/**
* Starts a script. `onEnd` is called when it finishes or fails by itself (not
* when stopped). Returns the function that stops it.
*/
export function startScript(
ctx: GameContext,
api: ScriptHostApi,
code: string,
log: (line: string) => void,
onEnd: (error?: string) => void,
): () => void {
const url = URL.createObjectURL(new Blob([WORKER_SOURCE], { type: 'text/javascript' }));
const worker = new Worker(url);
let stopped = false;
const stop = () => {
if (stopped) return;
stopped = true;
worker.terminate();
URL.revokeObjectURL(url);
};
worker.onmessage = (e: MessageEvent) => {
const m = e.data as { t: string; id?: number; method?: string; args?: unknown[]; line?: string; error?: string };
if (m.t === 'log') log(String(m.line));
else if (m.t === 'done') {
stop();
onEnd(m.error);
} else if (m.t === 'rpc') {
handleScriptCall(ctx, api, m.method!, m.args ?? []).then(
(value) => !stopped && worker.postMessage({ t: 'res', id: m.id, value }),
(err) => !stopped && worker.postMessage({ t: 'res', id: m.id, error: err instanceof Error ? err.message : String(err) }),
);
}
};
worker.onerror = (e) => {
stop();
onEnd(e.message || 'The script could not be started');
};
worker.postMessage({ t: 'run', code });
return stop;
}
+200
View File
@@ -0,0 +1,200 @@
// One connected console: two debugger connections (one for quick reads and
// writes, one for long scans so a scan never freezes the rest of the app) and
// the question "what game is running right now?".
import { Ps5Debug } from './ps5debug.ts';
import type { Branding } from './ps5debug.ts';
import { openWebSocketStream } from './transport.ts';
import type { ByteStream } from './transport.ts';
export interface Target {
/** Console address. Ignored when the page is served by the console itself. */
host: string;
port: number;
label?: string;
}
export interface Game {
pid: number;
titleId: string;
/** Empty when the debugger cannot report it (original ps5debug). */
version: string;
contentId: string;
}
export interface ServerInfo {
/** "bridge": served by the dev bridge on a computer. "console": served from the PS5. */
mode: 'bridge' | 'console';
version: string;
/** Present when the bridge was started with a built-in demo console. */
demo?: Target;
/** False when the bridge could not open the port debugger events arrive on. */
events?: boolean;
}
export async function fetchServerInfo(): Promise<ServerInfo> {
const res = await fetch('api/info', { cache: 'no-store' });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as ServerInfo;
}
export async function discoverConsoles(): Promise<Target[]> {
const res = await fetch('api/discover', { cache: 'no-store' });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as Target[];
}
function wsUrl(target: Target | null): string {
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
const base = `${scheme}://${location.host}${location.pathname.replace(/[^/]*$/, '')}ws`;
if (!target) return base;
return `${base}?host=${encodeURIComponent(target.host)}&port=${target.port}`;
}
/** The events endpoint sits next to /ws and takes the same console address. */
function eventsUrlFor(commandUrl: string): string {
return commandUrl.replace(/\/ws(\?|$)/, '/events$1');
}
export function formatFirmware(fw: number): string {
return `${Math.floor(fw / 100)}.${String(fw % 100).padStart(2, '0')}`;
}
type Channel = 'main' | 'scan';
/** More reopens than this inside the window means the console is really gone. */
const REOPEN_LIMIT = 4;
const REOPEN_WINDOW_MS = 10_000;
export class Session {
readonly target: Target | null;
/** Quick commands: cheats, reads, writes, polling. Read it fresh each call; it is replaced on reconnect. */
main!: Ps5Debug;
/** Long-running scans. Also replaced on reconnect. */
scan!: Ps5Debug;
branding: Branding = { brand: '', capability: '' };
/** 0 when the debugger does not report it. */
firmware = 0;
/** ps5debug-NG extras are available: foreground app, bulk writes, the scanner. */
extended = false;
onLost: ((reason: string) => void) | null = null;
private url: string;
private ended = false;
private reopens: number[] = [];
private constructor(target: Target | null, url: string) {
this.target = target;
this.url = url;
}
/** `url` is only passed by tests; the app derives it from the page address. */
static async connect(target: Target | null, url?: string): Promise<Session> {
const s = new Session(target, url ?? wsUrl(target));
let stream = await openWebSocketStream(s.url);
try {
// VERSION exists in every ps4debug/ps5debug descendant, so it doubles as
// the check that a debugger is answering at all.
await new Ps5Debug(stream).version();
// Branding and firmware are newer. A payload that does not know them
// simply never answers, which leaves the stream unusable, so they get a
// short timeout and a fresh connection if they fail.
const probe = new Ps5Debug(stream, { timeoutMs: 1500 });
try {
s.branding = await probe.branding();
s.firmware = await probe.firmware();
} catch {
if (!stream.closed) stream.close();
stream = await openWebSocketStream(s.url);
}
s.extended = s.branding.capability !== '' && parseFloat(s.branding.capability) >= 1;
s.adopt('main', stream);
s.adopt('scan', await openWebSocketStream(s.url));
} catch (e) {
s.close();
if (!stream.closed) stream.close();
throw e;
}
return s;
}
private adopt(channel: Channel, stream: ByteStream): void {
const dbg = new Ps5Debug(stream);
if (channel === 'main') this.main = dbg;
else this.scan = dbg;
stream.onClose = (reason) => void this.reopen(channel, reason);
if (stream.closed) void this.reopen(channel, 'Connection lost');
}
/**
* The console closes a connection after reporting certain errors (a game
* that just quit, for example). That is routine, so the channel is reopened
* quietly; only repeated failures count as losing the console.
*/
private async reopen(channel: Channel, reason: string): Promise<void> {
if (this.ended) return;
const now = Date.now();
this.reopens = this.reopens.filter((t) => now - t < REOPEN_WINDOW_MS);
this.reopens.push(now);
if (this.reopens.length > REOPEN_LIMIT) {
this.fail(reason);
return;
}
try {
const stream = await openWebSocketStream(this.url, 4000);
if (this.ended) {
stream.close();
return;
}
await new Ps5Debug(stream, { timeoutMs: 4000 }).version();
this.adopt(channel, stream);
} catch {
this.fail(reason);
}
}
private fail(reason: string): void {
if (this.ended) return;
this.close();
if (this.onLost) this.onLost(reason);
}
close(): void {
this.ended = true;
if (this.main && !this.main.closed) this.main.close();
if (this.scan && !this.scan.closed) this.scan.close();
}
/**
* Opens a separate connection for a debugging session (watchpoints,
* breakpoints). The console ties a debug session to the connection that
* attached and tears it down when that connection closes, so it gets its
* own, and closing it is always a safe way out.
*/
async openDebugger(): Promise<Ps5Debug> {
return new Ps5Debug(await openWebSocketStream(this.url), { timeoutMs: 15000 });
}
/** Opens the channel debugger stop reports arrive on. Open it before attaching. */
openEvents(): Promise<ByteStream> {
return openWebSocketStream(eventsUrlFor(this.url));
}
/** The game on screen, or null at the home screen. */
async currentGame(): Promise<Game | null> {
if (this.extended) {
const app = await this.main.foregroundApp();
if (!app) return null;
return { pid: app.pid, titleId: app.titleId, version: app.version, contentId: app.contentId };
}
// The original ps5debug has no "foreground app" command. Every game's main
// process is called eboot.bin, so take the first one, as ps5debug-NG does.
const procs = await this.main.processList();
const eboot = procs.find((p) => p.name === 'eboot.bin');
if (!eboot) return null;
const info = await this.main.processInfo(eboot.pid);
return { pid: eboot.pid, titleId: info.titleId, version: '', contentId: info.contentId };
}
}
+30
View File
@@ -0,0 +1,30 @@
// localStorage with the failure modes handled: it can be missing, full, or
// blocked (private windows), and the app has to work regardless.
const PREFIX = 'cheatspecter.';
export function loadJson<T>(key: string, fallback: T): T {
try {
const raw = localStorage.getItem(PREFIX + key);
return raw === null ? fallback : (JSON.parse(raw) as T);
} catch {
return fallback;
}
}
export function saveJson(key: string, value: unknown): boolean {
try {
localStorage.setItem(PREFIX + key, JSON.stringify(value));
return true;
} catch {
return false;
}
}
export function removeKey(key: string): void {
try {
localStorage.removeItem(PREFIX + key);
} catch {
// nothing to do
}
}
+604
View File
@@ -0,0 +1,604 @@
// CheatSpecter's own cheat tables.
//
// The community JSON format can only say "write these bytes at this offset".
// This format adds the things needed to build real features: locations that
// survive updates, pointer paths, injected code, function calls and scripts.
import { bytesEqual, hexToBytes, view } from './bytes.ts';
import { describeLocation, resolveLocation } from './locations.ts';
import type { GameContext, Location } from './locations.ts';
import { decodeValue, encodeValue, valueKind } from './scanner.ts';
import { loadJson, saveJson } from './storage.ts';
export const TABLE_FORMAT = 'cheatspecter/1';
interface EntryBase {
id: string;
name: string;
note?: string;
/** Set on entries that arrived in an imported file and can run code, until the user has looked at them. */
unreviewed?: boolean;
}
/** One place a patch changes. */
export interface PatchSite {
at: Location;
/** Hex bytes written when switched on. */
on: string;
/** Hex bytes expected before, if known. Used to refuse a patch that does not fit this game build. */
off?: string;
}
/** Replace bytes of game code or data; undone by putting the old bytes back. */
export interface PatchEntry extends EntryBase, PatchSite {
type: 'patch';
/** Further places changed by the same switch, for cheats that need more than one. */
more?: PatchSite[];
}
/** Every place a patch changes, the first one included. */
export function patchSites(entry: PatchEntry): PatchSite[] {
const first: PatchSite = { at: entry.at, on: entry.on, off: entry.off };
return Array.isArray(entry.more) ? [first, ...entry.more] : [first];
}
/** Set a value, optionally holding it there. */
export interface ValueEntry extends EntryBase {
type: 'value';
at: Location;
valueType: string;
value: string;
freeze: boolean;
}
/** Redirect a point in the game's code through new code written in assembly. */
export interface InjectEntry extends EntryBase {
type: 'inject';
at: Location;
/** x86-64 assembly, Intel syntax. */
code: string;
/**
* Where the instructions that the hook overwrites go:
* "before" runs the new code first, then them; "after" the reverse;
* "replace" drops them.
*/
placement: 'before' | 'after' | 'replace';
}
/** Call one of the game's own functions. */
export interface CallEntry extends EntryBase {
type: 'call';
fn: Location;
/** Up to six integer arguments, decimal or 0x hex. */
args: string[];
}
/** A small program with logic; see script.ts for what it can do. */
export interface ScriptEntry extends EntryBase {
type: 'script';
code: string;
}
export type Entry = PatchEntry | ValueEntry | InjectEntry | CallEntry | ScriptEntry;
export interface OwnTable {
format: typeof TABLE_FORMAT;
titleId: string;
/** Game version the table was made on; informational. */
version: string;
name: string;
entries: Entry[];
}
export function newId(): string {
return Math.random().toString(36).slice(2, 10);
}
export function emptyTable(titleId: string, version: string, name = ''): OwnTable {
return { format: TABLE_FORMAT, titleId, version, name, entries: [] };
}
// ---- the .cspecter file ---------------------------------------------------------
//
// A table on disk is a `.cspecter` file: JSON, written minified to keep it
// small. Its shape, laid out for reading:
//
// {
// "format": "cheatspecter",
// "formatVersion": 1,
// "game": { "name": "…", "titleId": "PPSA07391", "version": "01.009.000" },
// "cheats": [ { "name": "…", "type": "patch", … } ]
// }
export const FILE_FORMAT = 'cheatspecter';
export const FILE_FORMAT_VERSION = 1;
export const FILE_EXTENSION = '.cspecter';
/** The browser's copy: shown at once on load, and the fallback when no file can be written. */
export function loadOwnTable(titleId: string, version: string): OwnTable {
const t = loadJson<OwnTable | null>(`own.${titleId}`, null);
return t && t.format === TABLE_FORMAT ? t : emptyTable(titleId, version);
}
export function saveOwnTable(table: OwnTable): boolean {
return saveJson(`own.${table.titleId}`, table);
}
export function isOwnTableText(text: string): boolean {
try {
const format = (JSON.parse(text.replace(/^\uFEFF/, '')) as { format?: string }).format;
return format === FILE_FORMAT || format === TABLE_FORMAT;
} catch {
return false;
}
}
const RUNS_CODE = new Set(['inject', 'call', 'script']);
const ENTRY_TYPES = ['patch', 'value', 'inject', 'call', 'script'];
/**
* Parses and checks a table file.
*
* A file someone else made (`own` unset) is not trusted: entries that can run
* code come back marked unreviewed. With `own`, the file is the user's own
* saved table, and entries keep the review state it recorded.
*/
export function parseOwnTable(text: string, opts: { own?: boolean } = {}): OwnTable {
let raw: unknown;
try {
raw = JSON.parse(text.replace(/^\uFEFF/, ''));
} catch {
throw new Error('This file is not valid JSON');
}
const doc = raw as Record<string, unknown> | null;
// Tables exported before the .cspecter format kept everything at the top level.
const legacy = !!doc && doc.format === TABLE_FORMAT;
if (!doc || (doc.format !== FILE_FORMAT && !legacy)) throw new Error('This is not a CheatSpecter table');
if (!legacy && typeof doc.formatVersion === 'number' && doc.formatVersion > FILE_FORMAT_VERSION) {
throw new Error('This table was made with a newer CheatSpecter. Update CheatSpecter to open it.');
}
const game = (legacy ? doc : doc.game && typeof doc.game === 'object' ? doc.game : {}) as Record<string, unknown>;
const list = legacy ? doc.entries : doc.cheats;
if (!Array.isArray(list)) throw new Error('This table has no cheats');
const entries: Entry[] = [];
for (const item of list as (Entry & { reviewed?: boolean })[]) {
if (!item || typeof item !== 'object' || typeof item.name !== 'string') continue;
if (!ENTRY_TYPES.includes(item.type)) continue;
const { reviewed, ...e } = item;
const runsCode = RUNS_CODE.has(e.type);
entries.push({
// Fields a file may leave out because they were empty.
...(e.type === 'call' ? { args: [] } : e.type === 'value' ? { freeze: false } : {}),
...e,
id: newId(),
unreviewed: runsCode && !(opts.own && reviewed === true) ? true : undefined,
} as Entry);
}
return {
format: TABLE_FORMAT,
titleId: String(game.titleId ?? '').toUpperCase(),
version: String(game.version ?? ''),
name: String(game.name ?? ''),
entries,
};
}
/** Drops what a reader can do without: session-only fields, and anything empty. */
function lean(entry: Entry): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [key, value] of Object.entries(entry)) {
if (key === 'id' || key === 'unreviewed') continue;
if (value === undefined || value === null || value === '') continue;
if (Array.isArray(value) && value.length === 0) continue;
out[key] = value;
}
return out;
}
function fileText(table: OwnTable, cheats: unknown[]): string {
// Minified: a table with scripts and injected code would otherwise be largely
// whitespace. Any JSON formatter makes it readable again, and a file someone
// formatted by hand loads just the same.
return JSON.stringify({
format: FILE_FORMAT,
formatVersion: FILE_FORMAT_VERSION,
game: { name: table.name, titleId: table.titleId, version: table.version },
cheats,
});
}
/** The table as the user's own saved file: everything, including which entries they have reviewed. */
export function saveFileText(table: OwnTable): string {
return fileText(
table,
// Only a "yes" is recorded; an entry without it is treated as not looked at yet.
table.entries.map((e) => (RUNS_CODE.has(e.type) && !e.unreviewed ? { ...lean(e), reviewed: true } : lean(e))),
);
}
/** The table as a file to share. Per-session details are stripped. */
export function exportOwnTable(table: OwnTable): string {
return fileText(
table,
table.entries
// A raw address means nothing on anyone else's console, or after a restart.
.filter((e) => !('at' in e && e.at.kind === 'address') && !(e.type === 'call' && e.fn.kind === 'address'))
.filter((e) => !(e.type === 'patch' && patchSites(e).some((p) => p.at.kind === 'address')))
.map(lean),
);
}
/**
* The patch entries as a GoldHEN / etaHEN table, for use without CheatSpecter.
* Only plain offset patches with known "off" bytes can be expressed there.
*/
export function exportCommunityTable(table: OwnTable): { text: string; included: number; skipped: number } {
const mods = [];
let skipped = 0;
for (const e of table.entries) {
const sites = e.type === 'patch' ? patchSites(e) : [];
if (sites.length > 0 && sites.every((p) => p.at.kind === 'module' && p.off)) {
const memory = sites.map((p) => ({ offset: (p.at as { offset: string }).offset.replace(/^0x/i, '').toUpperCase(), on: p.on, off: p.off }));
mods.push({ name: e.name, type: 'checkbox', memory });
} else skipped++;
}
const out = { name: table.name || table.titleId, id: table.titleId, version: table.version, process: 'eboot.bin', mods, credits: [] };
return { text: JSON.stringify(out, null, 2) + '\n', included: mods.length, skipped };
}
export function describeEntry(e: Entry): string {
switch (e.type) {
case 'patch': {
const extra = patchSites(e).length - 1;
return `Patch at ${describeLocation(e.at)}${extra > 0 ? ` and ${extra} more ${extra === 1 ? 'place' : 'places'}` : ''}`;
}
case 'value':
return `${e.freeze ? 'Hold' : 'Set'} ${valueKind(e.valueType).label.toLowerCase()} at ${describeLocation(e.at)} to ${e.value}`;
case 'inject':
return `Injected code at ${describeLocation(e.at)}`;
case 'call':
return `Call ${describeLocation(e.fn)}(${e.args.join(', ')})`;
case 'script':
return 'Script';
}
}
/** Switches have an on and an off; actions just run. */
export function isAction(e: Entry): boolean {
return e.type === 'call' || (e.type === 'value' && !e.freeze);
}
// ---- running entries -----------------------------------------------------------
export class MismatchError extends Error {
constructor() {
super('The game code here is not what this cheat expects, so it was left alone. It is probably for a different game version.');
this.name = 'MismatchError';
}
}
interface EntryState {
on: boolean;
address?: bigint;
/** Bytes that were there before, to put back. */
original?: Uint8Array;
/** For a patch: each place it changed, with what to put back there. */
sites?: { address: bigint; original: Uint8Array }[];
/** Memory allocated for the injected code currently in use. */
cave?: { address: bigint; size: number };
frozen?: Uint8Array;
/** Result of the last run of an action. */
result?: string;
}
const CAVE_SIZE = 0x1000;
function jump(from: bigint, to: bigint): Uint8Array {
const rel = to - (from + 5n);
if (rel >= -0x80000000n && rel <= 0x7fffffffn) {
const b = new Uint8Array(5);
b[0] = 0xe9;
view(b).setInt32(1, Number(rel), true);
return b;
}
// Too far for a relative jump: jmp [rip+0] followed by the absolute address.
const b = new Uint8Array(14);
b.set([0xff, 0x25, 0, 0, 0, 0]);
view(b).setBigUint64(6, to, true);
return b;
}
export interface RunnerHooks {
/** Starts a script entry; returns a function that stops it. */
startScript?: (entry: ScriptEntry, log: (line: string) => void) => () => void;
onLog?: (entryId: string, line: string) => void;
}
/** Applies and undoes entries against a running game, and remembers what it did. */
export class TableRunner {
private ctx: GameContext;
private hooks: RunnerHooks;
private states = new Map<string, EntryState>();
private scripts = new Map<string, () => void>();
private timer: ReturnType<typeof setInterval> | null = null;
private freezing = false;
/** Set when the last freeze pass failed. */
freezeError: string | null = null;
constructor(ctx: GameContext, hooks: RunnerHooks = {}) {
this.ctx = ctx;
this.hooks = hooks;
}
isOn(id: string): boolean {
return this.states.get(id)?.on ?? false;
}
result(id: string): string | undefined {
return this.states.get(id)?.result;
}
address(id: string): bigint | undefined {
return this.states.get(id)?.address;
}
private state(id: string): EntryState {
let s = this.states.get(id);
if (!s) {
s = { on: false };
this.states.set(id, s);
}
return s;
}
/**
* Notices patches that are already in the game's memory, such as ones left
* on from before the page was reloaded or applied by another tool, and
* shows them as on. Returns true if anything changed.
*/
async adopt(entries: Entry[]): Promise<boolean> {
let changed = false;
for (const entry of entries) {
if (entry.type !== 'patch' || entry.unreviewed) continue;
const st = this.state(entry.id);
if (st.on) continue;
try {
const found: { address: bigint; original: Uint8Array }[] = [];
for (const site of patchSites(entry)) {
// Only where the location is cheap to work out and the original bytes are known to put back.
if (!site.off || (site.at.kind !== 'module' && site.at.kind !== 'address')) break;
const on = hexToBytes(site.on);
const off = hexToBytes(site.off);
if (on.length === 0 || bytesEqual(on, off)) break;
const address = await resolveLocation(this.ctx, site.at);
const current = await this.ctx.dbg().read(this.ctx.pid, address, on.length);
if (!bytesEqual(current, on)) break;
found.push({ address, original: off });
}
// Every place has to be applied; a half-applied cheat stays off so switching it on finishes the job.
if (found.length !== patchSites(entry).length) continue;
st.sites = found;
st.address = found[0].address;
st.on = true;
changed = true;
} catch {
// Not readable right now; it simply stays shown as off.
}
}
return changed;
}
/** Switches an entry on, or runs it if it is an action. `force` skips the "does this fit the game" check. */
async enable(entry: Entry, opts: { force?: boolean } = {}): Promise<void> {
const { ctx } = this;
const dbg = ctx.dbg();
const st = this.state(entry.id);
switch (entry.type) {
case 'patch': {
// Look at every place first, so a cheat that does not fit is refused before anything is written.
const plan: { address: bigint; on: Uint8Array; original: Uint8Array; applied: boolean }[] = [];
for (const site of patchSites(entry)) {
const on = hexToBytes(site.on);
if (on.length === 0) throw new Error('This patch has no bytes to write');
const address = await resolveLocation(ctx, site.at);
const current = await dbg.read(ctx.pid, address, on.length);
const off = site.off ? hexToBytes(site.off) : null;
if (bytesEqual(current, on)) {
// Already applied (earlier session, or another tool).
const known = st.sites?.find((x) => x.address === address)?.original;
plan.push({ address, on, original: known ?? off ?? current, applied: true });
} else {
if (off && !bytesEqual(current.subarray(0, off.length), off) && !opts.force) throw new MismatchError();
plan.push({ address, on, original: current, applied: false });
}
}
for (const p of plan) if (!p.applied) await dbg.write(ctx.pid, p.address, p.on);
st.sites = plan.map((p) => ({ address: p.address, original: p.original }));
st.address = plan[0].address;
st.on = true;
return;
}
case 'value': {
const bytes = encodeValue(valueKind(entry.valueType), entry.value);
const address = await resolveLocation(ctx, entry.at);
await dbg.write(ctx.pid, address, bytes);
st.address = address;
if (entry.freeze) {
st.frozen = bytes;
st.on = true;
this.startTimer();
} else {
st.result = `Set to ${decodeValue(valueKind(entry.valueType), bytes)}`;
}
return;
}
case 'call': {
const address = await resolveLocation(ctx, entry.fn);
const args = entry.args.map((a) => {
try {
return BigInt.asUintN(64, BigInt(a.trim()));
} catch {
throw new Error(`"${a}" is not a number`);
}
});
const rax = await dbg.call(ctx.pid, address, args);
st.address = address;
st.result = `Returned 0x${rax.toString(16).toUpperCase()} (${BigInt.asIntN(64, rax)})`;
return;
}
case 'inject': {
await this.enableInject(entry, st);
return;
}
case 'script': {
if (!this.hooks.startScript) throw new Error('Scripts cannot run here');
if (st.on) return;
const stop = this.hooks.startScript(entry, (line) => this.hooks.onLog?.(entry.id, line));
this.scripts.set(entry.id, stop);
st.on = true;
return;
}
}
}
private async enableInject(entry: InjectEntry, st: EntryState): Promise<void> {
const { ctx } = this;
const dbg = ctx.dbg();
const site = await resolveLocation(ctx, entry.at);
const head = await dbg.read(ctx.pid, site, 48);
if (st.on) return;
if (head[0] === 0xe9 || (head[0] === 0xff && head[1] === 0x25)) {
throw new Error('There is already a jump at this spot, probably a hook left from earlier. Restart the game to clear it.');
}
const insns = await ctx.x86.disassemble(head, site, 12);
// Always a fresh block: a game thread may still be running inside the one
// used last time, and rewriting code under it would crash the game. The
// old block is simply left behind (4 KB).
// Near the hook if possible, so the jump there fits in five bytes.
let caveAt = await dbg.allocNear(ctx.pid, site, CAVE_SIZE);
if (caveAt === 0n) caveAt = await dbg.alloc(ctx.pid, CAVE_SIZE);
st.cave = { address: caveAt, size: CAVE_SIZE };
const cave = st.cave.address;
// How many whole instructions the jump to the cave will overwrite.
const hookJump = jump(site, cave);
let covered = 0;
for (const insn of insns) {
if (covered >= hookJump.length) break;
if (insn.invalid) throw new Error('The code at this spot could not be decoded, so it cannot be hooked safely.');
covered += insn.length;
}
if (covered < hookJump.length) throw new Error('There is not enough code at this spot to place a hook.');
const original = head.slice(0, covered);
const assembleAt = async (address: bigint): Promise<Uint8Array> =>
entry.code.trim() ? ctx.assemble(address, entry.code) : new Uint8Array(0);
let body: Uint8Array;
if (entry.placement === 'replace') {
body = await assembleAt(cave);
} else if (entry.placement === 'before') {
const user = await assembleAt(cave);
const moved = await ctx.x86.relocate(original, site, cave + BigInt(user.length));
body = concatBytes(user, moved);
} else {
const moved = await ctx.x86.relocate(original, site, cave);
const user = await assembleAt(cave + BigInt(moved.length));
body = concatBytes(moved, user);
}
const back = jump(cave + BigInt(body.length), site + BigInt(covered));
const full = concatBytes(body, back);
if (full.length > st.cave.size) throw new Error('The injected code is too long');
// Cave first, hook last: the game must never jump into half-written code.
await dbg.write(ctx.pid, cave, full);
const hook = new Uint8Array(covered).fill(0x90);
hook.set(hookJump);
await dbg.write(ctx.pid, site, hook);
st.address = site;
st.original = original;
st.on = true;
const count = insns.filter((i) => i.address < site + BigInt(covered)).length;
st.result =
count > 1
? `Hooked. The jump replaced ${count} instructions; if the game ever jumps into the middle of them it will crash, so prefer a spot that starts with a long instruction.`
: undefined;
}
/** Switches an entry off, putting back whatever it changed. */
async disable(entry: Entry): Promise<void> {
const st = this.state(entry.id);
if (!st.on) return;
const dbg = this.ctx.dbg();
switch (entry.type) {
case 'patch':
// Last changed, first restored.
for (const site of [...(st.sites ?? [])].reverse()) await dbg.write(this.ctx.pid, site.address, site.original);
break;
case 'inject':
if (st.address !== undefined && st.original) await dbg.write(this.ctx.pid, st.address, st.original);
break;
case 'value':
st.frozen = undefined;
break;
case 'script':
this.scripts.get(entry.id)?.();
this.scripts.delete(entry.id);
break;
case 'call':
break;
}
st.on = false;
}
/** Called by a script that finished or failed on its own. */
scriptEnded(id: string): void {
this.scripts.delete(id);
const st = this.states.get(id);
if (st) st.on = false;
}
/** Reads what a value entry currently holds, for display. */
async readValue(entry: ValueEntry): Promise<string> {
const kind = valueKind(entry.valueType);
const address = await resolveLocation(this.ctx, entry.at);
return decodeValue(kind, await this.ctx.dbg().read(this.ctx.pid, address, kind.size));
}
private startTimer(): void {
if (this.timer) return;
this.timer = setInterval(() => void this.freezePass(), 250);
}
private async freezePass(): Promise<void> {
if (this.freezing) return;
const list = [...this.states.values()].filter((s) => s.on && s.frozen && s.address !== undefined);
if (list.length === 0) return;
this.freezing = true;
try {
for (const s of list) await this.ctx.dbg().write(this.ctx.pid, s.address!, s.frozen!);
this.freezeError = null;
} catch (e) {
this.freezeError = e instanceof Error ? e.message : String(e);
} finally {
this.freezing = false;
}
}
/** Stops timers and scripts. Patches stay in the game; call disable() first to undo them. */
dispose(): void {
if (this.timer) clearInterval(this.timer);
this.timer = null;
for (const stop of this.scripts.values()) stop();
this.scripts.clear();
}
}
function concatBytes(a: Uint8Array, b: Uint8Array): Uint8Array {
const out = new Uint8Array(a.length + b.length);
out.set(a);
out.set(b, a.length);
return out;
}
+127
View File
@@ -0,0 +1,127 @@
// Saving the user's own tables as real files.
//
// "Save to PS5" keeps them in one folder on the console, one file per game
// and game version, where they are found and loaded again whenever that game
// is running, from any device. "Save to this device" hands the same kind of
// file to the browser to store wherever the user likes.
//
// Browser storage is tied to the page's address, and a console's address can
// change with every restart, so it is never more than a working copy.
import { consoleApiUrl } from './library.ts';
import type { Target } from './session.ts';
import { FILE_EXTENSION, exportOwnTable, parseOwnTable, saveFileText } from './table.ts';
import type { OwnTable } from './table.ts';
/** The CheatSpecter payload is not running on the console, so nothing can be stored there. */
export class Ps5StorageUnavailable extends Error {
constructor() {
super('The CheatSpecter payload is not running on the console');
this.name = 'Ps5StorageUnavailable';
}
}
/** The version as it goes into a file name. Debuggers that cannot report one give "". */
export function fileVersion(version: string): string {
const clean = version.replace(/[^0-9A-Za-z.]/g, '').replace(/^\.+/, '').slice(0, 16);
return clean || 'unknown';
}
/** e.g. "PPSA18605-01.009.000.cspecter" */
export function tableFileName(titleId: string, version: string): string {
return `${titleId}-${fileVersion(version)}${FILE_EXTENSION}`;
}
async function request(target: Target | null, path: string, init?: RequestInit): Promise<Response> {
let res: Response;
try {
res = await fetch(consoleApiUrl(target, path), { cache: 'no-store', ...init });
} catch {
throw new Ps5StorageUnavailable();
}
if (res.status === 502) throw new Ps5StorageUnavailable();
return res;
}
export interface Ps5Tables {
/** The folder on the console, for telling the user where their files are. */
folder: string;
/** Game versions that have a saved file. */
versions: string[];
}
export async function listPs5Tables(target: Target | null, titleId: string): Promise<Ps5Tables> {
const res = await request(target, `api/tables/${titleId}`);
// A payload from before it kept files answers 404 here.
if (!res.ok) throw new Ps5StorageUnavailable();
const doc = (await res.json().catch(() => null)) as Partial<Ps5Tables> | null;
if (!doc || !Array.isArray(doc.versions)) throw new Ps5StorageUnavailable();
return { folder: typeof doc.folder === 'string' ? doc.folder : '', versions: doc.versions.filter((v) => typeof v === 'string') };
}
/** Which saved file to open for the running version: its own, else the most recent older-or-other one. */
export function pickVersion(versions: string[], running: string): string | null {
const want = fileVersion(running);
if (versions.includes(want)) return want;
const sorted = [...versions].sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
return sorted.length ? sorted[sorted.length - 1] : null;
}
export async function loadPs5Table(target: Target | null, titleId: string, version: string): Promise<OwnTable | null> {
const res = await request(target, `api/tables/${titleId}/${fileVersion(version)}`);
if (res.status === 404) return null;
if (!res.ok) throw new Error(`The console could not read the file (HTTP ${res.status})`);
return parseOwnTable(await res.text(), { own: true });
}
export async function savePs5Table(target: Target | null, table: OwnTable): Promise<void> {
const res = await request(target, `api/tables/${table.titleId}/${fileVersion(table.version)}`, {
method: 'PUT',
headers: { 'content-type': 'application/json' },
body: saveFileText(table),
});
if (res.status === 404 || res.status === 405) throw new Ps5StorageUnavailable();
if (!res.ok) throw new Error(`The console could not save the file (HTTP ${res.status})`);
}
interface SavePicker {
showSaveFilePicker?: (options: {
suggestedName: string;
types: { description: string; accept: Record<string, string[]> }[];
}) => Promise<{ name: string; createWritable: () => Promise<{ write: (data: string) => Promise<void>; close: () => Promise<void> }> }>;
}
/**
* Saves a file through the browser. Where the browser has a "Save as" window
* (Chrome and Edge, on a secure address) the user picks the place and name;
* elsewhere it is an ordinary download under the suggested name.
* Returns the name it was saved under, or null when the user cancelled.
*/
export async function saveToDevice(suggestedName: string, text: string, description = 'CheatSpecter cheats'): Promise<string | null> {
const picker = (globalThis as SavePicker).showSaveFilePicker;
if (typeof picker === 'function') {
const extension = suggestedName.slice(suggestedName.lastIndexOf('.'));
try {
const handle = await picker({ suggestedName, types: [{ description, accept: { 'application/json': [extension] } }] });
const out = await handle.createWritable();
await out.write(text);
await out.close();
return handle.name;
} catch (e) {
if (e instanceof DOMException && e.name === 'AbortError') return null;
// Some browsers expose the picker but refuse it here; fall through to a download.
}
}
const url = URL.createObjectURL(new Blob([text], { type: 'application/json' }));
const a = document.createElement('a');
a.href = url;
a.download = suggestedName;
a.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
return suggestedName;
}
/** The table as the file "Save to this device" writes. */
export function deviceFileText(table: OwnTable): string {
return exportOwnTable(table);
}
+200
View File
@@ -0,0 +1,200 @@
// "What writes to this address?"
//
// Sets a hardware watchpoint on a value and collects the instructions that
// touch it. Each one is a candidate cheat: the instruction that subtracts
// your ammo is the one to disable for infinite ammo.
//
// How it works: the debugger attaches to the game and arms a watchpoint. When
// the game touches the address, the CPU stops it right after the instruction
// and the console reports the stop on the event channel. The reported RIP is
// the next instruction, so the one before it is decoded, counted, and the game
// is resumed.
import { DEBUG_EVENT_SIZE, parseDebugEvent } from './ps5debug.ts';
import type { Ps5Debug, Registers, WatchKind } from './ps5debug.ts';
import type { ByteStream } from './transport.ts';
import type { GameContext } from './locations.ts';
import type { Insn } from './x86.ts';
export interface TraceHit {
/** The instruction that touched the value, or null if it could not be decoded. */
insn: Insn | null;
/** Address execution had reached when the game stopped (just past the instruction). */
rip: bigint;
count: number;
/** Registers at the most recent hit. */
regs: Registers;
}
export interface TracerDeps {
openDebugger: () => Promise<Ps5Debug>;
openEvents: () => Promise<ByteStream>;
}
const BEFORE = 15; // longest possible x86 instruction
export class Tracer {
/** Stops on its own after this many hits, so a busy value cannot freeze the game for long. */
maxHits = 400;
running = false;
total = 0;
private ctx: GameContext;
private deps: TracerDeps;
private debug: Ps5Debug | null = null;
private events: ByteStream | null = null;
private hits = new Map<bigint, TraceHit>();
private stopping = false;
private loop: Promise<void> | null = null;
private watch: { address: bigint; size: 1 | 2 | 4 | 8; kind: WatchKind } | null = null;
constructor(ctx: GameContext, deps: TracerDeps) {
this.ctx = ctx;
this.deps = deps;
}
list(): TraceHit[] {
return [...this.hits.values()].sort((a, b) => b.count - a.count);
}
/**
* Starts watching `size` bytes at `address`. `onUpdate` is called whenever
* the list changes, and once more when tracing ends (with the reason, if it
* ended by itself).
*/
async start(
address: bigint,
size: 1 | 2 | 4 | 8,
kind: WatchKind,
onUpdate: (hits: TraceHit[], ended?: string) => void,
): Promise<void> {
if (this.running) throw new Error('Already tracing');
this.hits.clear();
this.total = 0;
this.stopping = false;
try {
// The console connects back as part of attaching, so listen first.
this.events = await this.deps.openEvents();
this.debug = await this.deps.openDebugger();
await this.debug.debugAttach(this.ctx.pid);
// Watchpoints cover an aligned block; watch the one that contains the address.
const aligned = address - (address % BigInt(size));
this.watch = { address: aligned, size, kind };
await this.debug.setWatchpoint(0, true, kind, size, aligned);
} catch (e) {
await this.cleanup();
throw e;
}
this.running = true;
this.loop = this.run(onUpdate);
}
private async run(onUpdate: (hits: TraceHit[], ended?: string) => void): Promise<void> {
let ended: string | undefined;
try {
while (!this.stopping) {
const raw = await this.nextEvent();
if (this.stopping) break;
const ev = parseDebugEvent(raw);
// The debugger reports every signal the game receives, not just our
// watchpoint. Anything else is the game's own business (often a crash
// in progress); resuming would swallow it, so step aside instead.
if (ev.signal !== 5 || (ev.dr6 & 1n) === 0n) {
ended = ev.signal === 5 ? 'The game stopped for another reason, so tracing ended.' : `The game received signal ${ev.signal}, so tracing ended and let it through.`;
break;
}
const rip = ev.regs.rip;
let hit = this.hits.get(rip);
if (!hit) {
// Decode once per code location; later hits there only bump the count.
let insn: Insn | null = null;
try {
const around = await this.ctx.dbg().read(this.ctx.pid, rip - BigInt(BEFORE), BEFORE * 2);
// Normally the CPU stops after the instruction that touched the
// value, so it is the one ending at RIP. The exception is a
// repeated string instruction (memcpy, memset): the stop comes
// between repetitions, with RIP still on it.
const [here] = await this.ctx.x86.disassemble(around.subarray(BEFORE), rip, 1);
insn = here && !here.invalid && /^rep/.test(here.text) ? here : await this.ctx.x86.endingAt(around.subarray(0, BEFORE), rip);
} catch {
insn = null;
}
hit = { insn, rip, count: 0, regs: ev.regs };
this.hits.set(rip, hit);
}
hit.count++;
hit.regs = ev.regs;
this.total++;
onUpdate(this.list());
if (this.total >= this.maxHits) {
ended = `Stopped after ${this.maxHits} hits so the game is not slowed down for long.`;
break;
}
await this.debug!.debugResume();
}
} catch (e) {
if (!this.stopping) ended = e instanceof Error ? e.message : String(e);
}
await this.cleanup();
this.running = false;
this.watch = null;
onUpdate(this.list(), ended ?? (this.stopping ? undefined : 'Tracing ended'));
}
/**
* Waits for the next stop report. Also notices the debug connection going
* away (the game quit, or the console ended the session), which would
* otherwise leave this waiting forever.
*/
private nextEvent(): Promise<Uint8Array> {
const events = this.events!;
const debug = this.debug!;
return new Promise((resolve, reject) => {
const poll = setInterval(() => {
if (debug.closed) {
clearInterval(poll);
events.close('The console ended the debugging session. Is the game still running?');
}
}, 400);
events.read(DEBUG_EVENT_SIZE).then(
(raw) => {
clearInterval(poll);
resolve(raw);
},
(err) => {
clearInterval(poll);
reject(err);
},
);
});
}
/** Stops tracing and lets go of the game. Safe to call at any time. */
async stop(): Promise<void> {
if (!this.running) return;
this.stopping = true;
// Detaching resumes the game and closes the event channel, which ends the loop.
await this.cleanup();
await this.loop;
}
private async cleanup(): Promise<void> {
const debug = this.debug;
const events = this.events;
this.debug = null;
this.events = null;
if (debug && !debug.closed) {
try {
// Clear the watchpoint explicitly first. Detaching from a running game
// can skip that step on the console, and a watchpoint left armed in a
// game nobody is debugging kills it on the next hit.
if (debug.attached && this.watch) await debug.setWatchpoint(0, false, this.watch.kind, this.watch.size, this.watch.address);
if (debug.attached) await debug.debugDetach();
} catch {
// Closing the connection makes the console tear the session down anyway.
}
debug.close();
}
if (events && !events.closed) events.close();
}
}
+227
View File
@@ -0,0 +1,227 @@
// The two older community cheat formats, read into the same shape as the
// JSON one:
//
// .shn an XML "Trainer" document (PS4 Trainer / Reaper Studio)
// .mc4 the same XML, AES-encrypted and Base64-encoded, with a key every
// cheat tool ships (it only keeps the files from being edited by hand)
//
// Nothing here uses the browser's own XML parser or crypto: the page is often
// served over plain http from a console, where WebCrypto is switched off, and
// the tests run outside a browser.
import { hexToBytes } from './bytes.ts';
import { parseCheatTable } from './cheats.ts';
import type { CheatTable, Mod, Patch } from './cheats.ts';
// ---- AES-256-CBC, decryption only -------------------------------------------
const SBOX = new Uint8Array(256);
const INV_SBOX = new Uint8Array(256);
{
const rotl = (x: number, n: number) => ((x << n) | (x >> (8 - n))) & 0xff;
let p = 1;
let q = 1;
do {
p = (p ^ (p << 1) ^ (p & 0x80 ? 0x1b : 0)) & 0xff;
q ^= q << 1;
q ^= q << 2;
q ^= q << 4;
q &= 0xff;
if (q & 0x80) q ^= 0x09;
SBOX[p] = q ^ rotl(q, 1) ^ rotl(q, 2) ^ rotl(q, 3) ^ rotl(q, 4) ^ 0x63;
} while (p !== 1);
SBOX[0] = 0x63;
for (let i = 0; i < 256; i++) INV_SBOX[SBOX[i]] = i;
}
function mul(a: number, b: number): number {
let out = 0;
for (; b; b >>= 1) {
if (b & 1) out ^= a;
a = ((a << 1) ^ (a & 0x80 ? 0x1b : 0)) & 0xff;
}
return out;
}
function expandKey(key: Uint8Array): Uint8Array {
const nk = key.length / 4;
const rounds = nk + 6;
const w = new Uint8Array(16 * (rounds + 1));
w.set(key);
let rcon = 1;
for (let i = nk; i < 4 * (rounds + 1); i++) {
let t = [w[4 * i - 4], w[4 * i - 3], w[4 * i - 2], w[4 * i - 1]];
if (i % nk === 0) {
t = [SBOX[t[1]] ^ rcon, SBOX[t[2]], SBOX[t[3]], SBOX[t[0]]];
rcon = mul(rcon, 2);
} else if (nk > 6 && i % nk === 4) {
t = t.map((b) => SBOX[b]);
}
for (let j = 0; j < 4; j++) w[4 * i + j] = w[4 * (i - nk) + j] ^ t[j];
}
return w;
}
function decryptBlock(w: Uint8Array, block: Uint8Array): Uint8Array {
const rounds = w.length / 16 - 1;
const s = Uint8Array.from(block);
const addKey = (r: number) => {
for (let i = 0; i < 16; i++) s[i] ^= w[16 * r + i];
};
addKey(rounds);
for (let r = rounds - 1; r >= 0; r--) {
// Inverse ShiftRows: row n moves right by n. The state is column-major.
const t = Uint8Array.from(s);
for (let c = 0; c < 4; c++) for (let row = 0; row < 4; row++) s[4 * ((c + row) & 3) + row] = t[4 * c + row];
for (let i = 0; i < 16; i++) s[i] = INV_SBOX[s[i]];
addKey(r);
if (r === 0) break;
for (let c = 0; c < 4; c++) {
const [a, b, d, e] = [s[4 * c], s[4 * c + 1], s[4 * c + 2], s[4 * c + 3]];
s[4 * c] = mul(a, 14) ^ mul(b, 11) ^ mul(d, 13) ^ mul(e, 9);
s[4 * c + 1] = mul(a, 9) ^ mul(b, 14) ^ mul(d, 11) ^ mul(e, 13);
s[4 * c + 2] = mul(a, 13) ^ mul(b, 9) ^ mul(d, 14) ^ mul(e, 11);
s[4 * c + 3] = mul(a, 11) ^ mul(b, 13) ^ mul(d, 9) ^ mul(e, 14);
}
}
return s;
}
export function aesCbcDecrypt(key: Uint8Array, iv: Uint8Array, data: Uint8Array): Uint8Array {
if (data.length === 0 || data.length % 16 !== 0) throw new Error('The encrypted data is not a whole number of blocks');
const w = expandKey(key);
const out = new Uint8Array(data.length);
let prev = iv;
for (let off = 0; off < data.length; off += 16) {
const block = data.subarray(off, off + 16);
const plain = decryptBlock(w, block);
for (let i = 0; i < 16; i++) out[off + i] = plain[i] ^ prev[i];
prev = block;
}
const pad = out[out.length - 1];
if (pad < 1 || pad > 16) throw new Error('The encrypted data did not decode cleanly');
return out.subarray(0, out.length - pad);
}
const ascii = (s: string) => Uint8Array.from(s, (c) => c.charCodeAt(0));
// The key and IV the MC4 format has always used; every tool that reads it has them.
const MC4_KEY = ascii('304c6528f659c766110239a51cl5dd9c');
const MC4_IV = ascii('u@}kzW2u[u(8DWar');
function fromBase64(text: string): Uint8Array {
const clean = text.replace(/[^A-Za-z0-9+/]/g, '');
const bin = atob(clean + '='.repeat((4 - (clean.length % 4)) % 4));
return Uint8Array.from(bin, (c) => c.charCodeAt(0));
}
/** Turns the contents of an .mc4 file into the XML it wraps. */
export function decodeMc4(text: string): string {
let xml: string;
try {
xml = decodeText(aesCbcDecrypt(MC4_KEY, MC4_IV, fromBase64(text)));
} catch {
throw new Error('This MC4 file could not be decoded');
}
// Some tools wrote the XML into the file already escaped, quotes and all.
if (/^\s*&lt;/.test(xml)) xml = unescapeXml(xml).replace(/\\"/g, '"');
if (!/<Trainer[\s>]/i.test(xml)) throw new Error('This MC4 file could not be decoded');
return xml;
}
// ---- text ----------------------------------------------------------------------
/** File bytes to text. Trainer files come as UTF-8 or UTF-16, with or without a byte-order mark. */
export function decodeText(bytes: Uint8Array): string {
let encoding = 'utf-8';
if (bytes.length >= 2) {
if (bytes[0] === 0xff && bytes[1] === 0xfe) encoding = 'utf-16le';
else if (bytes[0] === 0xfe && bytes[1] === 0xff) encoding = 'utf-16be';
else if (bytes[0] === 0x3c && bytes[1] === 0x00) encoding = 'utf-16le';
else if (bytes[0] === 0x00 && bytes[1] === 0x3c) encoding = 'utf-16be';
}
return new TextDecoder(encoding).decode(bytes).replace(/^\uFEFF/, '');
}
const ENTITIES: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
function unescapeXml(s: string): string {
return s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (whole, body: string) => {
if (body[0] === '#') {
const code = body[1].toLowerCase() === 'x' ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : whole;
}
return ENTITIES[body.toLowerCase()] ?? whole;
});
}
// ---- the Trainer document -----------------------------------------------------------
function attributes(tag: string): Record<string, string> {
const out: Record<string, string> = {};
for (const m of tag.matchAll(/([A-Za-z_:][\w:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) out[m[1].toLowerCase()] = unescapeXml(m[2] ?? m[3] ?? '');
return out;
}
function child(xml: string, name: string): string | null {
const m = new RegExp(`<${name}\\b[^>]*>([\\s\\S]*?)</${name}>`, 'i').exec(xml);
return m ? unescapeXml(m[1]).trim() : null;
}
/** "90-90-90" or "90 90 90" to bytes. */
function dashedBytes(text: string): Uint8Array {
return hexToBytes(text.replace(/[^0-9a-f]/gi, ''));
}
/** Parses the XML inside .shn and .mc4 files. */
export function parseTrainerXml(xml: string): CheatTable {
const trainer = /<Trainer\b([^>]*)>/i.exec(xml);
if (!trainer) throw new Error('This file is not a cheat table (no <Trainer> element)');
const head = attributes(trainer[1]);
const mods: Mod[] = [];
for (const cheat of xml.matchAll(/<Cheat\b([^>]*?)(?:\/>|>([\s\S]*?)<\/Cheat>)/gi)) {
const attrs = attributes(cheat[1]);
const patches: Patch[] = [];
let unsupported: string | null = null;
for (const line of (cheat[2] ?? '').matchAll(/<Cheatline\b[^>]*>([\s\S]*?)<\/Cheatline>/gi)) {
const body = line[1];
try {
if (/^true$/i.test(child(body, 'Absolute') ?? '')) {
// A fixed address only works where games always load at the same place, which a PS5 does not do.
unsupported = 'Uses a fixed memory address';
continue;
}
if ((parseInt(child(body, 'Section') ?? '0', 10) || 0) !== 0) {
unsupported = 'Depends on a master code';
continue;
}
const offset = (child(body, 'Offset') ?? '').replace(/^0x/i, '');
if (!/^[0-9a-f]+$/i.test(offset)) throw new Error('bad offset');
patches.push({ offset: BigInt('0x' + offset), on: dashedBytes(child(body, 'ValueOn') ?? ''), off: dashedBytes(child(body, 'ValueOff') ?? '') });
} catch {
unsupported = 'Could not read this cheat';
}
}
if (patches.length === 0 && !unsupported) unsupported = 'Has no patches';
mods.push({ name: attrs.text || 'Unnamed cheat', description: (attrs.description ?? '').trim(), type: 'checkbox', patches, unsupported });
}
return {
name: head.game || 'Unknown game',
titleId: (head.cusa ?? '').toUpperCase(),
version: head.version ?? '',
process: head.process || 'eboot.bin',
credits: head.moder ? [head.moder] : [],
mods,
};
}
/** Reads a community cheat file in whichever of the three formats it is: JSON, SHN or MC4. */
export function parseAnyTable(text: string): CheatTable {
// A few files carry a stray character or two ahead of the XML, left by a mangled byte-order mark.
const trimmed = text.replace(/^\uFEFF/, '').trimStart().replace(/^[^<{[]{1,3}(?=<\?xml|<Trainer)/i, '');
if (trimmed.startsWith('{') || trimmed.startsWith('[')) return parseCheatTable(trimmed);
if (trimmed.startsWith('<')) return parseTrainerXml(trimmed);
if (/^[A-Za-z0-9+/=\s]+$/.test(trimmed) && trimmed.length >= 24) return parseTrainerXml(decodeMc4(trimmed));
throw new Error('This file is not a cheat table CheatSpecter can read (JSON, SHN, MC4 or .cspecter)');
}
+160
View File
@@ -0,0 +1,160 @@
// A WebSocket presented as a plain byte stream.
//
// The debugger speaks raw TCP, which browsers cannot open. Whatever serves this
// page (the dev bridge today, the on-console payload later) exposes /ws and
// relays binary frames to and from the debugger's TCP port unchanged. One
// WebSocket is one TCP connection, and frame boundaries carry no meaning.
export interface ByteStream {
/** Resolves with exactly `n` bytes. Only one read may be pending at a time. */
read(n: number): Promise<Uint8Array>;
write(data: Uint8Array): void;
close(reason?: string): void;
readonly closed: boolean;
/** Called once when the stream ends for any reason. */
onClose: ((reason: string) => void) | null;
}
interface Waiter {
n: number;
resolve: (b: Uint8Array) => void;
reject: (e: Error) => void;
}
export class StreamClosedError extends Error {
constructor(reason: string) {
super(reason);
this.name = 'StreamClosedError';
}
}
class WebSocketStream implements ByteStream {
onClose: ((reason: string) => void) | null = null;
closed = false;
private ws: WebSocket;
private chunks: Uint8Array[] = [];
private headOffset = 0;
private available = 0;
private waiter: Waiter | null = null;
private closeReason = '';
constructor(ws: WebSocket) {
this.ws = ws;
ws.binaryType = 'arraybuffer';
ws.onmessage = (ev: MessageEvent) => {
if (typeof ev.data === 'string') return;
const chunk = new Uint8Array(ev.data as ArrayBuffer);
if (chunk.length === 0) return;
this.chunks.push(chunk);
this.available += chunk.length;
this.pump();
};
ws.onclose = (ev: CloseEvent) => {
this.finish(ev.reason || (ev.code === 1000 ? 'Connection closed' : `Connection lost (code ${ev.code})`));
};
ws.onerror = () => {
this.finish('Connection error');
};
}
read(n: number): Promise<Uint8Array> {
if (this.waiter) return Promise.reject(new Error('Overlapping reads on one stream'));
if (n === 0) return Promise.resolve(new Uint8Array(0));
return new Promise((resolve, reject) => {
this.waiter = { n, resolve, reject };
this.pump();
});
}
write(data: Uint8Array): void {
if (this.closed) throw new StreamClosedError(this.closeReason || 'Connection closed');
this.ws.send(data);
}
close(reason = 'Closed'): void {
this.finish(reason);
try {
this.ws.close(1000);
} catch {
// already closing
}
}
private pump(): void {
const w = this.waiter;
if (!w) return;
if (this.available < w.n) {
if (this.closed) {
this.waiter = null;
w.reject(new StreamClosedError(this.closeReason));
}
return;
}
const out = new Uint8Array(w.n);
let filled = 0;
while (filled < w.n) {
const head = this.chunks[0];
const take = Math.min(head.length - this.headOffset, w.n - filled);
out.set(head.subarray(this.headOffset, this.headOffset + take), filled);
filled += take;
this.headOffset += take;
if (this.headOffset === head.length) {
this.chunks.shift();
this.headOffset = 0;
}
}
this.available -= w.n;
this.waiter = null;
w.resolve(out);
}
private finish(reason: string): void {
if (this.closed) return;
this.closed = true;
this.closeReason = reason;
this.pump();
const cb = this.onClose;
this.onClose = null;
if (cb) cb(reason);
}
}
export function openWebSocketStream(url: string, timeoutMs = 8000): Promise<ByteStream> {
return new Promise((resolve, reject) => {
let settled = false;
let ws: WebSocket;
try {
ws = new WebSocket(url);
} catch (e) {
reject(e instanceof Error ? e : new Error(String(e)));
return;
}
ws.binaryType = 'arraybuffer';
const timer = setTimeout(() => {
if (settled) return;
settled = true;
try {
ws.close();
} catch {
// ignore
}
reject(new Error('Timed out connecting'));
}, timeoutMs);
ws.onopen = () => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(new WebSocketStream(ws));
};
ws.onclose = (ev: CloseEvent) => {
if (settled) return;
settled = true;
clearTimeout(timer);
reject(new Error(ev.reason || 'Could not connect'));
};
ws.onerror = () => {
// onclose follows and carries the reason
};
});
}
+6
View File
@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
+250
View File
@@ -0,0 +1,250 @@
// x86-64 decoding, formatting and relocation, on top of the iced-x86 library.
//
// The library is passed in rather than imported so the same code runs in a
// browser worker (where it is loaded specially, see x86.worker.ts) and in the
// Node tests (where it is a plain require).
/* eslint-disable @typescript-eslint/no-explicit-any */
export type Flow = 'next' | 'jump' | 'cond' | 'call' | 'ret' | 'other';
export interface Insn {
address: bigint;
length: number;
bytes: Uint8Array;
/** Intel syntax, e.g. "mov [rcx+0x390],eax". */
text: string;
flow: Flow;
/** Branch or call destination, when it is a fixed address. */
target: bigint | null;
/** Address of the data a RIP-relative operand refers to. */
ripTarget: bigint | null;
writesMemory: boolean;
invalid: boolean;
/**
* Byte ranges inside the instruction that depend on where it is loaded
* (RIP-relative displacements, relative branch targets). A signature
* wildcards these so it still matches after the game is updated.
*/
variable: { offset: number; size: number }[];
}
export interface X86 {
/** Decodes instructions from `bytes`, which sit at `address` in the game. */
disassemble(bytes: Uint8Array, address: bigint, maxCount?: number): Insn[];
/**
* Re-encodes whole instructions so they behave the same at a new address
* (RIP-relative operands and branches are fixed up).
*/
relocate(bytes: Uint8Array, from: bigint, to: bigint): Uint8Array;
}
export function createX86(iced: any): X86 {
const { Decoder, DecoderOptions, Formatter, FormatterSyntax, FlowControl, BlockEncoder, BlockEncoderOptions, InstructionInfoFactory, OpAccess } =
iced;
const flowOf = (fc: number): Flow => {
switch (fc) {
case FlowControl.Next:
return 'next';
case FlowControl.UnconditionalBranch:
case FlowControl.IndirectBranch:
return 'jump';
case FlowControl.ConditionalBranch:
return 'cond';
case FlowControl.Return:
return 'ret';
case FlowControl.Call:
case FlowControl.IndirectCall:
return 'call';
default:
return 'other';
}
};
const WRITES = new Set<number>([OpAccess.Write, OpAccess.CondWrite, OpAccess.ReadWrite, OpAccess.ReadCondWrite]);
function disassemble(bytes: Uint8Array, address: bigint, maxCount = Infinity): Insn[] {
const decoder = new Decoder(64, bytes, DecoderOptions.None);
decoder.ip = address;
const formatter = new Formatter(FormatterSyntax.Intel);
formatter.hexPrefix = '0x';
formatter.hexSuffix = '';
formatter.uppercaseHex = true;
formatter.spaceAfterOperandSeparator = true;
formatter.ripRelativeAddresses = false; // show the address the operand refers to
formatter.showBranchSize = false;
formatter.branchLeadingZeros = false;
const factory = new InstructionInfoFactory();
const out: Insn[] = [];
try {
while (decoder.canDecode && out.length < maxCount) {
const instr = decoder.decode();
try {
const start = Number(instr.ip - address);
const length = instr.length as number;
const invalid = instr.isInvalid as boolean;
let writesMemory = false;
if (!invalid) {
const info = factory.info(instr);
try {
for (const mem of info.usedMemory()) {
if (WRITES.has(mem.access)) writesMemory = true;
mem.free();
}
} finally {
info.free();
}
}
const variable: { offset: number; size: number }[] = [];
if (!invalid) {
const co = decoder.getConstantOffsets(instr);
try {
if (instr.isIpRelMemoryOperand && co.hasDisplacement) {
variable.push({ offset: co.displacementOffset, size: co.displacementSize });
}
const direct =
instr.flowControl === FlowControl.UnconditionalBranch ||
instr.flowControl === FlowControl.ConditionalBranch ||
instr.flowControl === FlowControl.Call;
// Only 4-byte branch offsets are wildcarded; short jumps stay inside the function.
if (direct && co.hasImmediate && co.immediateSize === 4) {
variable.push({ offset: co.immediateOffset, size: co.immediateSize });
}
} finally {
co.free();
}
}
const flow = invalid ? 'other' : flowOf(instr.flowControl);
const direct = instr.flowControl === FlowControl.UnconditionalBranch || instr.flowControl === FlowControl.ConditionalBranch || instr.flowControl === FlowControl.Call;
out.push({
address: instr.ip,
length,
bytes: bytes.slice(start, start + length),
text: invalid ? '(not an instruction)' : formatter.format(instr),
flow,
target: !invalid && direct ? (instr.nearBranchTarget as bigint) : null,
ripTarget: !invalid && instr.isIpRelMemoryOperand ? (instr.ipRelMemoryAddress as bigint) : null,
writesMemory,
invalid,
variable,
});
} finally {
instr.free();
}
}
} finally {
factory.free();
formatter.free();
decoder.free();
}
return out;
}
function relocate(bytes: Uint8Array, from: bigint, to: bigint): Uint8Array {
const decoder = new Decoder(64, bytes, DecoderOptions.None);
decoder.ip = from;
const encoder = new BlockEncoder(64, BlockEncoderOptions.None);
try {
while (decoder.canDecode) {
const instr = decoder.decode();
try {
if (instr.isInvalid) throw new Error('The code at the hook site could not be decoded');
encoder.add(instr);
} finally {
instr.free();
}
}
return encoder.encode(to) as Uint8Array;
} finally {
encoder.free();
decoder.free();
}
}
return { disassemble, relocate };
}
/**
* Finds the instruction that ends exactly at `end`, given some bytes before
* it. x86 cannot be decoded backwards, so every start offset is tried and the
* decodings that land on `end` are ranked: one that writes memory wins (this
* is used to find what wrote a watched value), then the longest.
*/
export function instructionEndingAt(x86: X86, before: Uint8Array, end: bigint): Insn | null {
const base = end - BigInt(before.length);
let best: Insn | null = null;
for (let start = Math.max(0, before.length - 15); start < before.length; start++) {
const [insn] = x86.disassemble(before.subarray(start), base + BigInt(start), 1);
if (!insn || insn.invalid || insn.address + BigInt(insn.length) !== end) continue;
if (!best || (insn.writesMemory && !best.writesMemory) || (insn.writesMemory === best.writesMemory && insn.length > best.length)) {
best = insn;
}
}
return best;
}
/**
* The async face of X86 that the rest of the app uses. In the browser the
* library runs in a worker, so every call is a message round trip.
*/
export interface AsyncX86 {
disassemble(bytes: Uint8Array, address: bigint, maxCount?: number): Promise<Insn[]>;
relocate(bytes: Uint8Array, from: bigint, to: bigint): Promise<Uint8Array>;
endingAt(before: Uint8Array, end: bigint): Promise<Insn | null>;
}
export function asAsync(x86: X86): AsyncX86 {
return {
disassemble: async (bytes, address, maxCount) => x86.disassemble(bytes, address, maxCount),
relocate: async (bytes, from, to) => x86.relocate(bytes, from, to),
endingAt: async (before, end) => instructionEndingAt(x86, before, end),
};
}
/** "48 8B ?? 05" -> the bytes and a mask (1 = must match, 0 = wildcard). */
export function parsePattern(text: string): { pattern: Uint8Array; mask: Uint8Array } {
const tokens = text.trim().split(/[\s,]+/).filter(Boolean);
if (tokens.length === 0) throw new Error('Enter a byte pattern, for example: 48 8B ?? 05');
const pattern = new Uint8Array(tokens.length);
const mask = new Uint8Array(tokens.length);
tokens.forEach((t, i) => {
if (/^\?{1,2}$/.test(t)) return;
if (!/^[0-9a-fA-F]{2}$/.test(t)) throw new Error(`"${t}" is not a byte. Use two hex digits or ?? for "anything".`);
pattern[i] = parseInt(t, 16);
mask[i] = 1;
});
if (!mask.some((m) => m === 1)) throw new Error('A pattern needs at least one fixed byte');
return { pattern, mask };
}
/** Bytes plus the ranges that vary -> "89 81 ?? ?? ?? ?? C3". */
export function formatPattern(bytes: Uint8Array, wild: boolean[]): string {
return [...bytes].map((b, i) => (wild[i] ? '??' : b.toString(16).padStart(2, '0').toUpperCase())).join(' ');
}
/**
* Builds a signature for the code at an address: its bytes with the
* load-address-dependent parts wildcarded. Covers whole instructions and at
* least `minBytes`.
*/
export function signatureFromCode(insns: Insn[], minBytes: number): { text: string; length: number } {
const bytes: number[] = [];
const wild: boolean[] = [];
for (const insn of insns) {
if (insn.invalid) break;
const start = bytes.length;
for (const b of insn.bytes) {
bytes.push(b);
wild.push(false);
}
for (const v of insn.variable) for (let i = 0; i < v.size; i++) wild[start + v.offset + i] = true;
if (bytes.length >= minBytes) break;
}
// A pattern cannot end in wildcards usefully; trim them.
while (wild.length && wild[wild.length - 1]) {
wild.pop();
bytes.pop();
}
return { text: formatPattern(Uint8Array.from(bytes), wild), length: bytes.length };
}
+54
View File
@@ -0,0 +1,54 @@
// Runs the iced-x86 disassembler off the main thread.
//
// The npm package is built for Node: CommonJS, and it loads its WebAssembly
// synchronously from disk. Here the script is evaluated with small stand-ins
// for `require`, handing it the WebAssembly bytes fetched beforehand.
// Compiling this much WebAssembly synchronously is only allowed in a worker,
// which is one more reason this lives in one.
import glueSource from 'iced-x86/iced_x86.js?raw';
import wasmUrl from 'iced-x86/iced_x86_bg.wasm?url';
import { createX86, instructionEndingAt } from './x86.ts';
import type { X86 } from './x86.ts';
let ready: Promise<X86> | null = null;
function load(): Promise<X86> {
if (!ready) {
ready = (async () => {
const res = await fetch(new URL(wasmUrl, import.meta.url));
if (!res.ok) throw new Error(`Could not load the disassembler (HTTP ${res.status})`);
const wasm = new Uint8Array(await res.arrayBuffer());
const module = { exports: {} as Record<string, unknown> };
const fakeRequire = (name: string) => {
if (name === 'util') return { TextDecoder, TextEncoder };
if (name === 'path') return { join: (...parts: string[]) => parts.join('/') };
if (name === 'fs') return { readFileSync: () => wasm };
throw new Error(`Unexpected require("${name}")`);
};
new Function('module', 'exports', 'require', '__dirname', glueSource)(module, module.exports, fakeRequire, '');
return createX86(module.exports);
})();
}
return ready;
}
interface Request {
id: number;
method: 'disassemble' | 'relocate' | 'endingAt';
args: unknown[];
}
self.onmessage = async (e: MessageEvent<Request>) => {
const { id, method, args } = e.data;
try {
const x86 = await load();
let value: unknown;
if (method === 'disassemble') value = x86.disassemble(args[0] as Uint8Array, args[1] as bigint, args[2] as number | undefined);
else if (method === 'relocate') value = x86.relocate(args[0] as Uint8Array, args[1] as bigint, args[2] as bigint);
else value = instructionEndingAt(x86, args[0] as Uint8Array, args[1] as bigint);
self.postMessage({ id, value });
} catch (err) {
self.postMessage({ id, error: err instanceof Error ? err.message : String(err) });
}
};
+37
View File
@@ -0,0 +1,37 @@
// The disassembler as the app sees it: async calls answered by a worker that
// is only started (and only downloads its ~1 MB) the first time it is needed.
import type { AsyncX86, Insn } from './x86.ts';
let worker: Worker | null = null;
let nextId = 1;
const pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void }>();
function call<T>(method: string, args: unknown[]): Promise<T> {
if (!worker) {
worker = new Worker(new URL('./x86.worker.ts', import.meta.url), { type: 'module' });
worker.onmessage = (e: MessageEvent<{ id: number; value?: unknown; error?: string }>) => {
const p = pending.get(e.data.id);
pending.delete(e.data.id);
if (!p) return;
if (e.data.error) p.reject(new Error(e.data.error));
else p.resolve(e.data.value);
};
worker.onerror = (e) => {
for (const p of pending.values()) p.reject(new Error(e.message || 'The disassembler failed to start'));
pending.clear();
worker = null;
};
}
return new Promise<T>((resolve, reject) => {
const id = nextId++;
pending.set(id, { resolve: resolve as (v: unknown) => void, reject });
worker!.postMessage({ id, method, args });
});
}
export const x86: AsyncX86 = {
disassemble: (bytes, address, maxCount) => call<Insn[]>('disassemble', [bytes, address, maxCount]),
relocate: (bytes, from, to) => call<Uint8Array>('relocate', [bytes, from, to]),
endingAt: (before, end) => call<Insn | null>('endingAt', [before, end]),
};
+5
View File
@@ -0,0 +1,5 @@
import { createRoot } from 'react-dom/client';
import { App } from './ui/App.tsx';
import './styles.css';
createRoot(document.getElementById('app')!).render(<App />);
+121
View File
@@ -0,0 +1,121 @@
@import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
/* CheatSpecter is dark only: black with one yellow. Change --primary to retint it. */
:root {
--radius: 0.375rem;
--background: #070707;
--foreground: #f5f2e6;
--card: #101010;
--card-foreground: #f5f2e6;
--popover: #131312;
--popover-foreground: #f5f2e6;
--primary: #ffd400;
--primary-foreground: #0a0a0a;
--secondary: #1d1d1b;
--secondary-foreground: #f5f2e6;
--muted: #1a1a18;
--muted-foreground: #a39e90;
--accent: #262623;
--accent-foreground: #f5f2e6;
--destructive: #ff5d5d;
--border: #2b2a27;
--input: #3a3935;
--ring: #ffd400;
color-scheme: dark;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--radius-sm: calc(var(--radius) - 2px);
--radius-md: var(--radius);
--radius-lg: calc(var(--radius) + 2px);
--radius-xl: calc(var(--radius) + 4px);
--font-sans: system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
--font-mono: ui-monospace, 'SF Mono', Menlo, Consolas, 'Liberation Mono', monospace;
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground font-sans antialiased;
min-height: 100dvh;
}
}
/* ---- the ghost ---- */
.ghost-float {
animation: ghost-bob 2.6s ease-in-out infinite;
}
.ghost-look .ghost-pupils {
animation: ghost-look 5s ease-in-out infinite;
}
@keyframes ghost-bob {
50% {
transform: translateY(-4px);
}
}
@keyframes ghost-look {
0%,
42%,
100% {
transform: translateX(0);
}
50%,
92% {
transform: translateX(-5px);
}
}
/* ---- scan progress: a ghost eating a row of pellets ---- */
.pellet-runner {
transition: left 0.35s linear;
}
.pellet-track-indeterminate .pellet-runner {
animation: ghost-patrol 1.8s ease-in-out infinite alternate;
}
@keyframes ghost-patrol {
from {
left: 0;
}
to {
left: calc(100% - 28px);
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation: none !important;
transition: none !important;
}
}
+240
View File
@@ -0,0 +1,240 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { ChevronRightIcon, RefreshCwIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Spinner } from '@/components/kibo-ui/spinner';
import { Session, discoverConsoles, fetchServerInfo } from '../lib/session.ts';
import type { ServerInfo, Target } from '../lib/session.ts';
import { loadJson, saveJson } from '../lib/storage.ts';
import { Ghost, Notice, Wordmark, errorText } from './bits.tsx';
import { ConsoleView } from './ConsoleView.tsx';
type Phase =
| { name: 'boot' }
| { name: 'unavailable'; reason: string }
| { name: 'pick'; error?: string }
| { name: 'connecting'; label: string }
| { name: 'connected'; session: Session };
export function App() {
const [phase, setPhase] = useState<Phase>({ name: 'boot' });
const [info, setInfo] = useState<ServerInfo | null>(null);
const sessionRef = useRef<Session | null>(null);
const connect = useCallback(async (target: Target | null, opts: { quiet?: boolean } = {}) => {
setPhase({ name: 'connecting', label: target ? target.label || target.host : 'your PS5' });
try {
const session = await Session.connect(target);
sessionRef.current = session;
session.onLost = (reason) => {
sessionRef.current = null;
setPhase({ name: 'pick', error: `Disconnected: ${reason}` });
};
if (target) saveJson('lastTarget', target);
setPhase({ name: 'connected', session });
} catch (e) {
setPhase({ name: 'pick', error: opts.quiet ? undefined : errorText(e) });
}
}, []);
useEffect(() => {
let cancelled = false;
fetchServerInfo()
.then((i) => {
if (cancelled) return;
setInfo(i);
if (i.mode === 'console') {
// Served from the PS5 itself: there is only one console to talk to.
void connect(null);
return;
}
const last = loadJson<Target | null>('lastTarget', null);
if (last) void connect(last, { quiet: true });
else setPhase({ name: 'pick' });
})
.catch((e) => {
if (!cancelled) setPhase({ name: 'unavailable', reason: errorText(e) });
});
return () => {
cancelled = true;
};
}, [connect]);
const disconnect = () => {
const s = sessionRef.current;
sessionRef.current = null;
if (s) {
s.onLost = null;
s.close();
}
setPhase({ name: 'pick' });
};
return (
<div className="mx-auto max-w-3xl px-4 pt-4 pb-[calc(2rem+env(safe-area-inset-bottom))]">
{phase.name === 'connected' ? (
<ConsoleView session={phase.session} localCheats={info?.mode === 'bridge'} onConsole={info?.mode === 'console'} onDisconnect={disconnect} />
) : (
<div className="flex flex-col gap-4">
<header className="flex items-center py-1">
<Wordmark />
</header>
{phase.name === 'boot' && (
<p className="flex items-center gap-2 text-sm text-muted-foreground">
<Spinner className="size-4" /> Starting…
</p>
)}
{phase.name === 'unavailable' && (
<Notice kind="error">
CheatSpecter has to be opened from the bridge or the console that serves it, not as a file. ({phase.reason})
</Notice>
)}
{phase.name === 'connecting' && (
<div className="flex flex-col items-center gap-3 py-10 text-center">
<Ghost size={72} floaty />
<h2 className="text-xl font-semibold">Connecting to {phase.label}…</h2>
</div>
)}
{phase.name === 'pick' && (
<Picker info={info} error={phase.error} onPick={(t) => void connect(t)} consoleMode={info?.mode === 'console'} />
)}
</div>
)}
<p className="mt-6 text-center text-xs text-muted-foreground">
CheatSpecter {info?.version ?? ''} · for single-player games you own
</p>
</div>
);
}
function ConsoleRow(props: { title: string; detail: string; mono?: boolean; onClick: () => void }) {
return (
<Button variant="outline" className="h-auto w-full justify-start gap-3 px-4 py-3 text-left" onClick={props.onClick}>
<span className="size-2.5 shrink-0 rounded-full bg-primary" />
<span className="flex min-w-0 flex-1 flex-col">
<span className="font-semibold">{props.title}</span>
<span className={'truncate text-xs font-normal text-muted-foreground' + (props.mono ? ' font-mono' : '')}>{props.detail}</span>
</span>
<span className="flex items-center gap-1 text-primary">
Connect <ChevronRightIcon />
</span>
</Button>
);
}
function Picker(props: { info: ServerInfo | null; error?: string; consoleMode: boolean; onPick: (t: Target | null) => void }) {
const [found, setFound] = useState<Target[] | null>(null);
const [searching, setSearching] = useState(false);
const [ip, setIp] = useState(() => loadJson<Target | null>('lastTarget', null)?.host ?? '');
const demo = props.info?.demo ?? null;
const search = useCallback(async () => {
setSearching(true);
try {
setFound(await discoverConsoles());
} catch {
setFound([]);
} finally {
setSearching(false);
}
}, []);
useEffect(() => {
if (!props.consoleMode) void search();
}, [props.consoleMode, search]);
if (props.consoleMode) {
return (
<Card>
<CardContent className="flex flex-col gap-4">
{props.error && <Notice kind="error">{props.error}</Notice>}
<p className="text-sm text-muted-foreground">
The debugger is not answering. Load ps5debug-NG on the console, then try again.
</p>
<Button className="self-start" onClick={() => props.onPick(null)}>
Try again
</Button>
</CardContent>
</Card>
);
}
const list = (found ?? []).filter((t) => !demo || t.port !== demo.port || t.host !== demo.host);
const validIp = /^\d{1,3}(\.\d{1,3}){3}$/.test(ip.trim());
return (
<div className="flex flex-col gap-4">
<div className="flex flex-col items-center gap-2 px-2 pt-6 pb-2 text-center">
<Ghost size={72} floaty look />
<h2 className="text-2xl font-bold tracking-tight">Find your PS5</h2>
<p className="text-sm text-muted-foreground">
Load ps5debug-NG on the console first. It shows a "loaded" notification when it is ready.
</p>
</div>
{props.error && <Notice kind="error">{props.error}</Notice>}
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-2">
<CardTitle>On your network</CardTitle>
<Button variant="outline" size="sm" onClick={() => void search()} disabled={searching}>
{searching ? <Spinner className="size-4" /> : <RefreshCwIcon />}
{searching ? 'Looking…' : 'Look again'}
</Button>
</CardHeader>
<CardContent className="flex flex-col gap-2">
{list.map((t) => (
<ConsoleRow key={t.host + t.port} title={t.label ?? 'PS5'} detail={t.host} mono onClick={() => props.onPick(t)} />
))}
{demo && (
<ConsoleRow
title={demo.label ?? 'Demo console'}
detail="A pretend PS5 for trying things out"
onClick={() => props.onPick(demo)}
/>
)}
{found !== null && list.length === 0 && !searching && (
<p className="text-sm text-muted-foreground">
No console answered. Check that the PS5 is on the same network and the debugger is loaded, or enter its address
below.
</p>
)}
{found === null && <p className="text-sm text-muted-foreground">Looking for consoles…</p>}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Enter the address yourself</CardTitle>
<CardDescription>On the PS5: Settings → Network → View Connection Status.</CardDescription>
</CardHeader>
<CardContent>
<form
className="flex flex-col gap-2"
onSubmit={(e) => {
e.preventDefault();
if (validIp) props.onPick({ host: ip.trim(), port: 744, label: 'PS5' });
}}
>
<Label htmlFor="ip">PS5 IP address</Label>
<div className="flex gap-2">
<Input
id="ip"
className="font-mono"
inputMode="decimal"
placeholder="192.168.1.20"
value={ip}
onChange={(e) => setIp(e.target.value)}
/>
<Button type="submit" disabled={!validIp}>
Connect
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
);
}
+416
View File
@@ -0,0 +1,416 @@
import { Fragment, useCallback, useEffect, useRef, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Dropzone, DropzoneEmptyState } from '@/components/kibo-ui/dropzone';
import { Spinner } from '@/components/kibo-ui/spinner';
import { ONLINE_SOURCES, findTables, importTable, loadTable } from '../lib/catalog.ts';
import type { CatalogEntry, CatalogResult } from '../lib/catalog.ts';
import { applyMod, findImageBase, readModState } from '../lib/cheats.ts';
import type { CheatTable, ImageBase, Mod, ModState } from '../lib/cheats.ts';
import { fmtAddr } from '../lib/bytes.ts';
import type { Game, Session } from '../lib/session.ts';
import { isOwnTableText, parseOwnTable } from '../lib/table.ts';
import { decodeText } from '../lib/trainer.ts';
import { Ghost, Notice, errorText } from './bits.tsx';
import { OwnCheats } from './OwnCheats.tsx';
import { useWorkbench } from './workbench.tsx';
interface Loaded {
entry: CatalogEntry;
table: CheatTable;
pid: number;
base: ImageBase;
}
const entryKey = (e: CatalogEntry) => `${e.sourceId}/${e.file}`;
export function CheatsTab(props: { session: Session; game: Game; localCheats: boolean; onGameName: (name: string) => void }) {
const { session, game } = props;
const wb = useWorkbench();
const [importNote, setImportNote] = useState<string | null>(null);
const [catalog, setCatalog] = useState<CatalogResult | null>(null);
const [catalogError, setCatalogError] = useState<string | null>(null);
const [selected, setSelected] = useState<CatalogEntry | null>(null);
const [loaded, setLoaded] = useState<Loaded | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [states, setStates] = useState<ModState[]>([]);
const [busy, setBusy] = useState<number | null>(null);
const [rowError, setRowError] = useState<{ index: number; text: string } | null>(null);
const [importError, setImportError] = useState<string | null>(null);
// Bytes that were in memory before a cheat was forced on, so "off" can put
// back what was really there instead of the table's guess.
const originals = useRef(new Map<number, Uint8Array[]>());
const alive = useRef(true);
useEffect(() => () => void (alive.current = false), []);
const refreshCatalog = useCallback(
async (preferFile?: string) => {
setCatalogError(null);
try {
const result = await findTables(game.titleId, game.version, { includeLocal: props.localCheats });
if (!alive.current) return;
setCatalog(result);
const named = result.entries.find((e) => e.gameName);
if (named) props.onGameName(named.gameName);
const pick =
(preferFile && result.entries.find((e) => e.file === preferFile)) ||
result.entries.find((e) => e.exact) ||
// With no version to match on, or a single candidate, opening it is
// harmless: every cheat is verified against memory before use.
(result.entries.length === 1 || !game.version ? result.entries[0] : null) ||
null;
setSelected((cur) => cur ?? pick);
} catch (e) {
if (alive.current) setCatalogError(errorText(e));
}
},
[game.titleId, game.version, props.localCheats],
);
useEffect(() => {
void refreshCatalog();
}, [refreshCatalog]);
// Load the selected table and work out where the game is in memory.
useEffect(() => {
if (!selected) return;
let cancelled = false;
setLoaded(null);
setLoadError(null);
setStates([]);
setRowError(null);
originals.current.clear();
setLoading(true);
(async () => {
const table = await loadTable(selected);
let pid = game.pid;
if (table.process && table.process.toLowerCase() !== 'eboot.bin') {
// A few tables patch a second executable the game launches.
const proc = (await session.main.processList()).find((p) => p.name.toLowerCase() === table.process.toLowerCase());
if (!proc) throw new Error(`This table is for "${table.process}", which is not running right now.`);
pid = proc.pid;
}
const base = findImageBase(await session.main.maps(pid), table.process);
if (!base) throw new Error('Could not read where the game is loaded in memory.');
if (cancelled) return;
if (table.name) props.onGameName(table.name);
setLoaded({ entry: selected, table, pid, base });
const next: ModState[] = table.mods.map(() => 'unknown');
setStates(next.slice());
for (let i = 0; i < table.mods.length; i++) {
next[i] = await readModState(session.main, pid, base.address, table.mods[i]);
if (cancelled) return;
// Batch the re-renders a little on long tables.
if (i % 8 === 7 || i === table.mods.length - 1) setStates(next.slice());
}
})()
.catch((e) => {
if (!cancelled) setLoadError(errorText(e));
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [selected, game.pid, session]);
const setState = (index: number, s: ModState) =>
setStates((prev) => {
const next = prev.slice();
next[index] = s;
return next;
});
const toggle = async (index: number, on: boolean, force = false) => {
if (!loaded) return;
const mod = loaded.table.mods[index];
setBusy(index);
setRowError(null);
try {
// Look again right before writing; the game may have changed things.
const now = await readModState(session.main, loaded.pid, loaded.base.address, mod);
if (now === 'mismatch' && !force) {
setState(index, 'mismatch');
return;
}
const saved = originals.current.get(index);
if (!on && saved) {
for (let p = 0; p < mod.patches.length; p++) {
await session.main.write(loaded.pid, loaded.base.address + mod.patches[p].offset, saved[p]);
}
originals.current.delete(index);
setState(index, await readModState(session.main, loaded.pid, loaded.base.address, mod));
return;
}
if (on && now === 'mismatch' && mod.type === 'checkbox') {
const before: Uint8Array[] = [];
for (const patch of mod.patches) {
before.push(await session.main.read(loaded.pid, loaded.base.address + patch.offset, patch.on.length));
}
originals.current.set(index, before);
}
await applyMod(session.main, loaded.pid, loaded.base.address, mod, on);
const after = await readModState(session.main, loaded.pid, loaded.base.address, mod);
setState(index, after === 'unknown' ? 'unknown' : after);
if (mod.type === 'checkbox' && after !== (on ? 'on' : 'off')) {
setRowError({ index, text: 'The console accepted the write, but the game memory did not change.' });
}
} catch (e) {
setRowError({ index, text: errorText(e) });
} finally {
setBusy(null);
}
};
// One of your own cheats was just switched, and it may patch the same code
// a table entry does. Re-read the table's switches so they tell the truth.
const wasBusy = useRef(false);
useEffect(() => {
const finished = wasBusy.current && wb.busy === null;
wasBusy.current = wb.busy !== null;
if (!finished || !loaded) return;
let cancelled = false;
(async () => {
const next: ModState[] = [];
for (const mod of loaded.table.mods) {
next.push(await readModState(session.main, loaded.pid, loaded.base.address, mod));
if (cancelled) return;
}
setStates(next);
})().catch(() => undefined);
return () => {
cancelled = true;
};
}, [wb.busy, loaded, session]);
const onImport = async (file: File) => {
setImportError(null);
setImportNote(null);
try {
// Read as bytes: SHN files are sometimes UTF-16, which a plain text read would garble.
const text = decodeText(new Uint8Array(await file.arrayBuffer()));
if (isOwnTableText(text)) {
// A CheatSpecter table: its entries join "Your cheats".
const incoming = parseOwnTable(text);
if (incoming.titleId && incoming.titleId !== game.titleId.toUpperCase()) {
setImportError(`That table is for ${incoming.titleId} and the running game is ${game.titleId}, so it was not imported.`);
return;
}
wb.setTable((t) => ({ ...t, name: t.name || incoming.name, entries: [...t.entries, ...incoming.entries] }));
const gated = incoming.entries.filter((e) => e.unreviewed).length;
setImportNote(
`Added ${incoming.entries.length} to your cheats.` +
(gated ? ` ${gated} can run code in the game and ${gated === 1 ? 'needs' : 'need'} a look before first use: press Review.` : '') +
(incoming.version && game.version && incoming.version !== game.version ? ` It was made on v${incoming.version}; you are running v${game.version}.` : ''),
);
return;
}
const table = importTable(file.name, text);
if (table.titleId !== game.titleId.toUpperCase()) {
setImportError(`Saved, but that table is for ${table.titleId} and the running game is ${game.titleId}.`);
return;
}
setSelected(null);
await refreshCatalog(file.name);
} catch (err) {
setImportError(errorText(err));
}
};
const entries = catalog?.entries ?? [];
const mismatched = loaded && game.version && !loaded.entry.exact;
return (
<div className="flex flex-col gap-4">
<OwnCheats />
{catalogError && <Notice kind="error">Could not look up cheats: {catalogError}</Notice>}
{catalog && catalog.failed.length > 0 && (
<Notice kind="warn">
Could not reach {catalog.failed.map((f) => f.source).join(' or ')}. This device needs internet access to download
cheat tables; ones you have used before still work.
</Notice>
)}
{catalog && catalog.stale.length > 0 && catalog.failed.length === 0 && (
<Notice>Offline: showing the saved copy of {catalog.stale.join(' and ')}.</Notice>
)}
{!catalog && !catalogError && (
<p className="flex items-center gap-2 text-sm text-muted-foreground">
<Spinner className="size-4" /> Looking for cheats for {game.titleId}…
</p>
)}
{catalog && entries.length === 0 && (
<Card>
<CardContent className="flex flex-col items-center gap-2 py-6 text-center">
<Ghost size={56} className="text-muted-foreground" />
<h2 className="text-lg font-semibold">No ready-made cheats for this game</h2>
<p className="text-sm text-muted-foreground">
Nothing for {game.titleId} in the online collections. You can import a table file below, or make your own starting
from <strong className="text-foreground">Find</strong>.
</p>
</CardContent>
</Card>
)}
{entries.length > 0 && (
<Card>
<CardContent className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<Label htmlFor="table">Cheat table</Label>
<Select
value={selected ? entryKey(selected) : ''}
onValueChange={(key) => setSelected(entries.find((x) => entryKey(x) === key) ?? null)}
>
<SelectTrigger id="table" className="w-full">
<SelectValue placeholder="Choose a table…" />
</SelectTrigger>
<SelectContent>
{entries.map((e) => (
<SelectItem key={entryKey(e)} value={entryKey(e)}>
v{e.version} · {e.sourceName} · {e.format.toUpperCase()}
{e.exact ? ' · matches your game' : ''}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{!selected && game.version && (
<Notice kind="warn">
None of these tables is for v{game.version}, the version you are running. You can try one: cheats that do not
match your game are detected and left off.
</Notice>
)}
{mismatched && (
<Notice kind="warn">
This table is for v{loaded.entry.version}; you are running v{game.version}. Cheats that do not match your game
are detected and left off.
</Notice>
)}
{loading && !loaded && (
<p className="flex items-center gap-2 text-sm text-muted-foreground">
<Spinner className="size-4" /> Loading table…
</p>
)}
{loadError && <Notice kind="error">{loadError}</Notice>}
{loaded && (
<>
<ul className="divide-y">
{loaded.table.mods.map((mod, i) => (
<ModRow
key={i}
mod={mod}
state={states[i] ?? 'unknown'}
busy={busy === i}
locked={busy !== null && busy !== i}
error={rowError?.index === i ? rowError.text : null}
onToggle={(on, force) => void toggle(i, on, force)}
/>
))}
</ul>
{loaded.table.mods.length === 0 && <p className="text-sm text-muted-foreground">This table has no cheats in it.</p>}
<details className="text-xs text-muted-foreground">
<summary className="cursor-pointer">Details</summary>
<p className="mt-2">
{loaded.table.credits.length > 0 && <>Made by {loaded.table.credits.join(', ')}. </>}
File <span className="font-mono">{loaded.entry.file}</span> from {loaded.entry.sourceName}. Game loaded at{' '}
<span className="font-mono">{fmtAddr(loaded.base.address)}</span> ({loaded.base.from}), process{' '}
<span className="font-mono">{loaded.table.process}</span>, pid {loaded.pid}.
</p>
</details>
</>
)}
</CardContent>
</Card>
)}
<Dropzone
accept={{ 'application/json': ['.cspecter', '.json'], 'application/xml': ['.shn', '.xml'], 'text/plain': ['.mc4'] }}
maxFiles={1}
className="p-5"
onDrop={(files) => files[0] && void onImport(files[0])}
onError={(e) => setImportError(e.message)}
>
<DropzoneEmptyState>
<div className="flex flex-col items-center gap-1 text-center">
<p className="text-sm font-medium">Import a cheat table</p>
<p className="text-xs font-normal text-wrap text-muted-foreground">
Drop a .cspecter, .json, .shn or .mc4 file here, or click to choose one.
</p>
</div>
</DropzoneEmptyState>
</Dropzone>
{importError && <Notice kind="error">{importError}</Notice>}
{importNote && <Notice>{importNote}</Notice>}
<p className="text-xs text-muted-foreground">
Tables are downloaded by this device from{' '}
{ONLINE_SOURCES.map((s, i) => (
<Fragment key={s.id}>
{i > 0 && ' and '}
<a className="text-primary underline underline-offset-2" href={s.home} target="_blank" rel="noreferrer">
{s.name}
</a>
</Fragment>
))}
.
</p>
</div>
);
}
function ModRow(props: {
mod: Mod;
state: ModState;
busy: boolean;
locked: boolean;
error: string | null;
onToggle: (on: boolean, force: boolean) => void;
}) {
const { mod, state } = props;
const unusable = !!mod.unsupported;
const mismatch = state === 'mismatch';
return (
<li className="flex items-center gap-3 py-3 first:pt-0 last:pb-0">
<div className="min-w-0 flex-1">
<div className={'font-medium break-words' + (unusable || mismatch ? ' text-muted-foreground' : '')}>{mod.name}</div>
{mod.description && <div className="text-sm text-muted-foreground">{mod.description}</div>}
{unusable && <div className="text-sm text-muted-foreground">Not supported yet: {mod.unsupported}</div>}
{mismatch && !unusable && (
<div className="mt-1 flex flex-wrap items-center gap-2 text-sm text-primary">
Does not match this version of the game, so it was left alone.
<Button variant="outline" size="xs" disabled={props.busy || props.locked} onClick={() => props.onToggle(true, true)}>
Apply anyway
</Button>
</div>
)}
{props.error && (
<div className="text-sm text-destructive" role="alert">
{props.error}
</div>
)}
</div>
{props.busy && <Spinner className="size-4 text-muted-foreground" />}
{mod.type === 'button' ? (
<Button variant="outline" size="sm" disabled={unusable || props.busy || props.locked} onClick={() => props.onToggle(true, true)}>
Apply
</Button>
) : (
<Switch
aria-label={mod.name}
checked={state === 'on'}
disabled={unusable || mismatch || props.locked || props.busy}
onCheckedChange={(on) => props.onToggle(on, false)}
/>
)}
</li>
);
}
+444
View File
@@ -0,0 +1,444 @@
// The game's code: a disassembly view, a pattern search, and the tracer that
// answers "what writes to this address?". Every instruction can be turned
// into a cheat from here.
import { useCallback, useEffect, useRef, useState } from 'react';
import { ChevronLeftIcon, ChevronRightIcon, MoreHorizontalIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Spinner } from '@/components/kibo-ui/spinner';
import { cn } from '@/lib/utils';
import { bytesToHex, fmtAddr } from '../lib/bytes.ts';
import { findPattern, imageRange, parseAddress } from '../lib/locations.ts';
import { codeLocation, nopEntry } from '../lib/make.ts';
import { newId } from '../lib/table.ts';
import { Tracer } from '../lib/tracer.ts';
import type { TraceHit } from '../lib/tracer.ts';
import { signatureFromCode } from '../lib/x86.ts';
import type { Insn } from '../lib/x86.ts';
import { Notice, errorText } from './bits.tsx';
import { useWorkbench } from './workbench.tsx';
const WINDOW = 320; // bytes read per page
export function CodeTab() {
return (
<div className="flex flex-col gap-4">
<TracePanel />
<Listing />
</div>
);
}
// ---- what writes to this address ---------------------------------------------------
function TracePanel() {
const wb = useWorkbench();
const { ctx, session } = wb;
const [text, setText] = useState('');
const [size, setSize] = useState('4');
const [kind, setKind] = useState<'write' | 'readwrite'>('write');
const [running, setRunning] = useState(false);
const [starting, setStarting] = useState(false);
const [hits, setHits] = useState<TraceHit[]>([]);
const [note, setNote] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [busyRow, setBusyRow] = useState<bigint | null>(null);
const tracer = useRef<Tracer | null>(null);
const stop = useCallback(async () => {
await tracer.current?.stop();
setRunning(false);
}, []);
const start = useCallback(
async (address: bigint, bytes: 1 | 2 | 4 | 8, mode: 'write' | 'readwrite') => {
setError(null);
setNote(null);
setHits([]);
setStarting(true);
try {
await tracer.current?.stop();
const t = new Tracer(ctx, { openDebugger: () => session.openDebugger(), openEvents: () => session.openEvents() });
tracer.current = t;
await t.start(address, bytes, mode, (list, ended) => {
setHits(list.map((h) => ({ ...h })));
if (ended !== undefined || !t.running) {
setRunning(false);
if (ended) setNote(ended);
}
});
setRunning(true);
} catch (e) {
setError(errorText(e));
setRunning(false);
} finally {
setStarting(false);
}
},
[ctx, session],
);
// Another tab asked for a trace ("Find what writes to this").
useEffect(() => {
const req = wb.trace;
if (!req) return;
setText(fmtAddr(req.address));
setSize(String(req.size));
setKind(req.kind);
void start(req.address, req.size, req.kind);
}, [wb.trace, start]);
// Never leave the game attached when this goes away.
useEffect(() => () => void tracer.current?.stop(), []);
const submit = async () => {
try {
await start(await parseAddress(ctx, text), Number(size) as 1 | 2 | 4 | 8, kind);
} catch (e) {
setError(errorText(e));
}
};
const disable = async (insn: Insn) => {
setBusyRow(insn.address);
try {
// Tracing and patching the same code at once is asking for trouble.
await stop();
await wb.addEntry(await nopEntry(ctx, insn));
wb.setTab('cheats');
} catch (e) {
setError(errorText(e));
} finally {
setBusyRow(null);
}
};
return (
<Card>
<CardHeader>
<CardTitle>What touches a value</CardTitle>
<CardDescription>
Watches an address and lists the instructions that change it. The one that lowers your ammo is the one to disable for
infinite ammo. The game pauses for an instant at each hit.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<form
className="grid grid-cols-2 gap-2 sm:grid-cols-[1fr_130px_190px_auto]"
onSubmit={(e) => {
e.preventDefault();
if (!running && !starting) void submit();
}}
>
<Input className="col-span-2 font-mono sm:col-span-1" aria-label="Address to watch" placeholder="Address of the value" value={text} disabled={running || starting} onChange={(e) => setText(e.target.value)} />
<Select value={size} onValueChange={setSize} disabled={running || starting}>
<SelectTrigger className="w-full" aria-label="Size of the value">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="1">1 byte</SelectItem>
<SelectItem value="2">2 bytes</SelectItem>
<SelectItem value="4">4 bytes</SelectItem>
<SelectItem value="8">8 bytes</SelectItem>
</SelectContent>
</Select>
<Select value={kind} onValueChange={(k) => setKind(k as 'write' | 'readwrite')} disabled={running || starting}>
<SelectTrigger className="w-full" aria-label="What to catch">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="write">Writes to it</SelectItem>
<SelectItem value="readwrite">Reads or writes it</SelectItem>
</SelectContent>
</Select>
{running ? (
<Button type="button" variant="outline" className="col-span-2 sm:col-span-1" onClick={() => void stop()}>
Stop
</Button>
) : (
<Button type="submit" className="col-span-2 sm:col-span-1" disabled={starting || !text.trim()}>
{starting ? <Spinner className="size-4" /> : null}
Watch
</Button>
)}
</form>
{running && (
<p className="flex items-center gap-2 text-sm text-muted-foreground" aria-live="polite">
<Spinner className="size-4" /> Watching. Now make the value change in the game.
</p>
)}
{error && <Notice kind="error">{error}</Notice>}
{note && <Notice>{note}</Notice>}
{hits.length > 0 && (
<ul className="divide-y" aria-label="Instructions that touched the value">
{hits.map((h) => (
<li key={h.rip.toString(16)} className="flex flex-wrap items-center gap-x-3 gap-y-1 py-2">
<span className="w-12 shrink-0 text-right font-mono text-sm text-primary" title="Times hit">
×{h.count}
</span>
<span className="min-w-0 flex-1 max-sm:basis-[calc(100%-4rem)]">
<span className="block font-mono text-sm break-words">{h.insn ? h.insn.text : '(could not decode)'}</span>
<span className="block font-mono text-xs text-muted-foreground">{fmtAddr(h.insn ? h.insn.address : h.rip)}</span>
</span>
<span className="flex gap-2 max-sm:ml-[3.75rem]">
<Button variant="outline" size="sm" onClick={() => wb.showCode(h.insn ? h.insn.address : h.rip)}>
Show
</Button>
{h.insn && (
<Button size="sm" disabled={busyRow !== null} onClick={() => void disable(h.insn!)}>
{busyRow === h.insn.address ? <Spinner className="size-4" /> : null}
Disable it
</Button>
)}
</span>
</li>
))}
</ul>
)}
</CardContent>
</Card>
);
}
// ---- disassembly --------------------------------------------------------------------
function Listing() {
const wb = useWorkbench();
const { ctx } = wb;
const [text, setText] = useState('');
const [pattern, setPattern] = useState('');
const [start, setStart] = useState<bigint | null>(null);
const [insns, setInsns] = useState<Insn[] | null>(null);
const [image, setImage] = useState<{ start: bigint; end: bigint } | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [note, setNote] = useState<string | null>(null);
const [focus, setFocus] = useState<bigint | null>(null);
const [reload, setReload] = useState(0);
const go = useCallback((address: bigint) => {
setStart(address);
setFocus(address);
setText(fmtAddr(address));
setError(null);
setNote(null);
}, []);
useEffect(() => {
if (wb.codeAt !== null) go(wb.codeAt);
}, [wb.codeAt, go]);
// First visit: open at the start of the game's code.
useEffect(() => {
if (wb.tab !== 'code' || start !== null) return;
let cancelled = false;
imageRange(ctx)
.then((r) => !cancelled && go(r.start))
.catch((e) => !cancelled && setError(errorText(e)));
return () => {
cancelled = true;
};
}, [wb.tab, start, ctx, go]);
useEffect(() => {
if (start === null || wb.tab !== 'code') return;
let cancelled = false;
setLoading(true);
(async () => {
try {
const [bytes, range] = await Promise.all([ctx.dbg().read(ctx.pid, start, WINDOW), imageRange(ctx)]);
const list = await ctx.x86.disassemble(bytes, start, 40);
// The last instruction may be cut off by the end of the window.
if (list.length > 1 && list[list.length - 1].invalid) list.pop();
if (cancelled) return;
setImage(range);
setInsns(list);
setError(null);
} catch (e) {
if (!cancelled) setError(errorText(e));
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => {
cancelled = true;
};
// wb.busy changes when a cheat is switched, which may have rewritten this code.
}, [start, ctx, wb.tab, wb.busy, reload]);
const label = (address: bigint) =>
image && address >= image.start && address < image.end ? `game+${(address - image.start).toString(16).toUpperCase()}` : fmtAddr(address);
const submit = async () => {
try {
go(await parseAddress(ctx, text));
} catch (e) {
setError(errorText(e));
}
};
const search = async () => {
setError(null);
setNote(null);
setLoading(true);
try {
const match = await findPattern(ctx, pattern, 'code');
if (!match) setNote('That pattern is not in the game\'s code.');
else {
go(match.address);
if (!match.unique) setNote('That pattern matches in more than one place; this is the first. Add more bytes to make it unique.');
}
} catch (e) {
setError(errorText(e));
} finally {
setLoading(false);
}
};
const act = async (fn: () => Promise<void>) => {
setError(null);
setNote(null);
try {
await fn();
} catch (e) {
setError(errorText(e));
}
};
const disable = (insn: Insn) =>
act(async () => {
await wb.addEntry(await nopEntry(ctx, insn));
setNote(`Added "Skip ${insn.text}" to your cheats and switched it on.`);
setReload((n) => n + 1);
});
const hook = (insn: Insn) =>
act(async () => {
wb.edit({ id: newId(), type: 'inject', name: '', at: await codeLocation(ctx, insn.address), code: '', placement: 'before' }, true);
});
const copySignature = (index: number) =>
act(async () => {
const sig = signatureFromCode(insns!.slice(index), 12).text;
const match = await findPattern(ctx, sig, 'code');
setPattern(sig);
try {
await navigator.clipboard.writeText(sig);
setNote(`Copied: ${sig}${match && !match.unique ? ' (matches in more than one place; it needs more bytes)' : ''}`);
} catch {
setNote(`Signature: ${sig}`);
}
});
const last = insns && insns.length ? insns[insns.length - 1] : null;
return (
<Card>
<CardHeader>
<CardTitle>Code</CardTitle>
<CardDescription>The game's instructions. Use the menu on any line to disable it, hook it, or follow where it leads.</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<div className="grid gap-3 sm:grid-cols-2">
<form
className="flex flex-col gap-2"
onSubmit={(e) => {
e.preventDefault();
void submit();
}}
>
<Label htmlFor="code-addr">Go to</Label>
<div className="flex gap-2">
<Input id="code-addr" className="min-w-0 font-mono" placeholder="Address, or game+1A2B3C" value={text} onChange={(e) => setText(e.target.value)} />
<Button type="submit">Go</Button>
</div>
</form>
<form
className="flex flex-col gap-2"
onSubmit={(e) => {
e.preventDefault();
void search();
}}
>
<Label htmlFor="code-pattern">Find a byte pattern</Label>
<div className="flex gap-2">
<Input id="code-pattern" className="min-w-0 font-mono" placeholder="89 81 ?? ?? 00 00" value={pattern} onChange={(e) => setPattern(e.target.value)} />
<Button type="submit" variant="outline" disabled={!pattern.trim() || loading}>
Find
</Button>
</div>
</form>
</div>
{error && <Notice kind="error">{error}</Notice>}
{note && <Notice>{note}</Notice>}
{insns && (
<>
<div className="overflow-x-auto">
<table className="w-full font-mono text-xs sm:text-sm" aria-label="Disassembly">
<tbody>
{insns.map((insn, i) => (
<tr key={insn.address.toString(16)} className={cn('border-b last:border-0', insn.address === focus && 'bg-accent')}>
<td className="py-1 pr-3 whitespace-nowrap text-muted-foreground">{label(insn.address)}</td>
<td className="py-1 pr-3 whitespace-nowrap text-muted-foreground/70 max-md:hidden">{bytesToHex(insn.bytes, ' ')}</td>
<td className={cn('w-full py-1 pr-2', insn.invalid && 'text-muted-foreground', (insn.flow === 'call' || insn.flow === 'jump' || insn.flow === 'cond') && 'text-primary')}>
{insn.text}
</td>
<td className="py-0.5 text-right">
{!insn.invalid && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-xs" aria-label={`Actions for ${insn.text}`}>
<MoreHorizontalIcon />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onSelect={() => void disable(insn)}>Disable this instruction</DropdownMenuItem>
<DropdownMenuItem onSelect={() => void hook(insn)}>Run my own code here…</DropdownMenuItem>
<DropdownMenuSeparator />
{insn.target !== null && <DropdownMenuItem onSelect={() => go(insn.target!)}>Follow to {label(insn.target)}</DropdownMenuItem>}
{insn.ripTarget !== null && (
<DropdownMenuItem onSelect={() => wb.showMemory(insn.ripTarget!)}>Show the data it uses</DropdownMenuItem>
)}
<DropdownMenuItem onSelect={() => void copySignature(i)}>Copy a signature for this spot</DropdownMenuItem>
<DropdownMenuItem onSelect={() => wb.showMemory(insn.address)}>Show as bytes</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" disabled={start === null} onClick={() => start !== null && go(start - 0x80n)}>
<ChevronLeftIcon /> Earlier
</Button>
<Button variant="outline" size="sm" disabled={!last} onClick={() => last && go(last.address + BigInt(last.length))}>
Later <ChevronRightIcon />
</Button>
{loading && <Spinner className="size-4 text-muted-foreground" />}
<span className="text-xs text-muted-foreground max-sm:hidden">
Going earlier can land mid-instruction; if the lines look wrong, step a little further back.
</span>
</div>
</>
)}
{!insns && loading && (
<p className="flex items-center gap-2 text-sm text-muted-foreground">
<Spinner className="size-4" /> Loading the disassembler…
</p>
)}
</CardContent>
</Card>
);
}
+349
View File
@@ -0,0 +1,349 @@
import { useEffect, useState } from "react";
import { LibraryIcon, TriangleAlertIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
Banner,
BannerClose,
BannerIcon,
BannerTitle,
} from "@/components/kibo-ui/banner";
import { Pill } from "@/components/kibo-ui/pill";
import { Spinner } from "@/components/kibo-ui/spinner";
import {
Status,
StatusIndicator,
StatusLabel,
} from "@/components/kibo-ui/status";
import { cachedMeta, fetchTitleMeta, iconUrl } from "../lib/library.ts";
import type { TitleMeta } from "../lib/library.ts";
import { formatFirmware } from "../lib/session.ts";
import type { Game, Session } from "../lib/session.ts";
import { Ghost, Notice, Wordmark, errorText } from "./bits.tsx";
import { CheatsTab } from "./CheatsTab.tsx";
import { ScannerTab } from "./ScannerTab.tsx";
import { MemoryTab } from "./MemoryTab.tsx";
import { CodeTab } from "./CodeTab.tsx";
import { EntryEditor } from "./EntryEditor.tsx";
import { LibraryView } from "./LibraryView.tsx";
import { WorkbenchProvider, useWorkbench } from "./workbench.tsx";
import type { TabId } from "./workbench.tsx";
const POLL_MS = 3000;
function sameGame(a: Game | null, b: Game | null): boolean {
if (!a || !b) return a === b;
return a.pid === b.pid && a.titleId === b.titleId && a.version === b.version;
}
export function ConsoleView(props: {
session: Session;
localCheats: boolean;
onConsole: boolean;
onDisconnect: () => void;
}) {
const { session } = props;
const [game, setGame] = useState<Game | null>(null);
const [checked, setChecked] = useState(false);
const [error, setError] = useState<string | null>(null);
/** The name a cheat table gives the game; used when the console cannot be asked. */
const [catalogName, setCatalogName] = useState("");
/** The game's own name and platform, from the console's metadata. */
const [meta, setMeta] = useState<TitleMeta | null>(null);
const [libraryOpen, setLibraryOpen] = useState(false);
useEffect(() => {
let stopped = false;
let timer: ReturnType<typeof setTimeout> | undefined;
let failures = 0;
const poll = async () => {
try {
const g = await session.currentGame();
if (stopped) return;
failures = 0;
setGame((prev) => (sameGame(prev, g) ? prev : g));
setError(null);
} catch (e) {
if (stopped) return;
// One miss is usually a connection being reopened; say nothing unless it repeats.
if (++failures >= 2) setError(errorText(e));
} finally {
if (!stopped) {
setChecked(true);
timer = setTimeout(poll, POLL_MS);
}
}
};
void poll();
return () => {
stopped = true;
clearTimeout(timer);
};
}, [session]);
// A new game means a new name to look up.
const titleId = game?.titleId;
useEffect(() => {
setCatalogName("");
setMeta(titleId ? cachedMeta(titleId) : null);
if (!titleId) return;
let cancelled = false;
// Needs the CheatSpecter payload on the console; without it the table's name is used.
fetchTitleMeta(session.target, titleId)
.then((m) => !cancelled && m && setMeta(m))
.catch(() => {});
return () => {
cancelled = true;
};
}, [session, titleId, game?.pid]);
// The library has done its job once the game it started is on screen.
useEffect(() => setLibraryOpen(false), [titleId]);
const displayName = meta?.name || catalogName;
const brand = session.branding.brand.replace(/\s*\[[^\]]*\]\s*$/, "");
const gameKey = game ? `${game.pid}:${game.titleId}:${game.version}` : "none";
const isDemo = session.target?.label === "Demo console";
return (
<div className="flex flex-col gap-4">
<header className="flex flex-wrap items-center gap-x-3 gap-y-2 py-1">
<Wordmark />
<Status
status="online"
className="max-sm:hidden"
title={session.branding.brand}
>
<StatusIndicator />
<StatusLabel>
PS5{session.firmware ? " " + formatFirmware(session.firmware) : ""}
{isDemo ? " · demo" : ""}
</StatusLabel>
</Status>
{game && (
<Button
variant="outline"
size="sm"
onClick={() => setLibraryOpen(true)}
>
<LibraryIcon /> Games
</Button>
)}
<Button variant="ghost" size="sm" onClick={props.onDisconnect}>
Disconnect
</Button>
</header>
{error && <Notice kind="error">{error}</Notice>}
{!game ? (
<>
<Card>
<CardContent className="flex flex-col items-center gap-2 py-8 text-center text-muted-foreground">
<Ghost size={64} floaty />
{checked ? (
<>
<h2 className="text-lg font-semibold text-foreground">
No game running
</h2>
<p className="text-sm">
Start a game on your PS5 and it will show up here.
</p>
</>
) : (
<p className="flex items-center gap-2 text-sm">
<Spinner className="size-4" /> Checking what is running…
</p>
)}
{brand && <p className="font-mono text-xs">{brand}</p>}
</CardContent>
</Card>
{checked && (
<Card>
<CardHeader>
<CardTitle>Your games</CardTitle>
</CardHeader>
<CardContent>
<LibraryView
target={session.target}
onConsole={props.onConsole}
running={null}
runningName=""
/>
</CardContent>
</Card>
)}
</>
) : (
<>
<Card className="border-primary/60">
<CardContent className="flex items-center gap-4">
<GameLogo
key={game.titleId}
src={iconUrl(session.target, game.titleId)}
/>
<div className="flex min-w-0 flex-1 flex-col gap-2">
<span className="text-xs tracking-wide text-muted-foreground uppercase">
Now playing
</span>
<span className="text-xl leading-tight font-bold break-words">
{displayName || game.titleId}
</span>
<div className="flex flex-wrap gap-1.5">
{meta && (
<Pill
className={
meta.platform === "PS5"
? "border-primary/60 text-xs text-primary"
: "text-xs"
}
variant="outline"
>
{meta.platform}
</Pill>
)}
<Pill className="font-mono text-xs">{game.titleId}</Pill>
<Pill className="font-mono text-xs">
{game.version ? `v${game.version}` : "version unknown"}
</Pill>
<Pill className="font-mono text-xs">pid {game.pid}</Pill>
</div>
</div>
</CardContent>
</Card>
{!session.extended && (
<Banner inset>
<BannerIcon icon={TriangleAlertIcon} />
<BannerTitle>
This debugger does not report the game's version, so
CheatSpecter cannot tell which cheat table matches. Each cheat
is still checked against the game's memory before it is applied.
ps5debug-NG reports the version.
</BannerTitle>
<BannerClose />
</Banner>
)}
{/* Keyed by game, so everything tied to one game is rebuilt when another starts. */}
<WorkbenchProvider
key={gameKey}
session={session}
game={game}
gameName={displayName}
>
<GameTabs
localCheats={props.localCheats}
onGameName={setCatalogName}
/>
</WorkbenchProvider>
<Dialog open={libraryOpen} onOpenChange={setLibraryOpen}>
<DialogContent className="max-h-[90dvh] grid-cols-[minmax(0,1fr)] overflow-y-auto sm:max-w-xl">
<DialogHeader>
<DialogTitle>Your games</DialogTitle>
<DialogDescription>
Everything installed on this PS5. Starting another game closes
the one that is running.
</DialogDescription>
</DialogHeader>
{libraryOpen && (
<LibraryView
target={session.target}
onConsole={props.onConsole}
running={game}
runningName={displayName}
/>
)}
</DialogContent>
</Dialog>
</>
)}
</div>
);
}
/** The game's own icon, as the console shows it. Takes no space until it has loaded, and none if there is none. */
function GameLogo(props: { src: string }) {
const [state, setState] = useState<"loading" | "ok" | "missing">("loading");
if (state === "missing") return null;
return (
<img
src={props.src}
alt=""
className={
state === "ok"
? "size-20 shrink-0 rounded-md border object-cover sm:size-24"
: "hidden"
}
onLoad={() => setState("ok")}
onError={() => setState("missing")}
/>
);
}
function GameTabs(props: {
localCheats: boolean;
onGameName: (name: string) => void;
}) {
const wb = useWorkbench();
return (
<>
<Tabs
value={wb.tab}
onValueChange={(t) => wb.setTab(t as TabId)}
className="gap-4"
>
<TabsList className="w-full">
<TabsTrigger value="cheats">Cheats</TabsTrigger>
<TabsTrigger value="find">Find</TabsTrigger>
<TabsTrigger value="memory">Memory</TabsTrigger>
<TabsTrigger value="code">Code</TabsTrigger>
</TabsList>
{/* All stay mounted so a running scan, trace or loaded table survives switching tabs. */}
<TabsContent
value="cheats"
forceMount
className="data-[state=inactive]:hidden"
>
<CheatsTab
session={wb.session}
game={wb.game}
localCheats={props.localCheats}
onGameName={props.onGameName}
/>
</TabsContent>
<TabsContent
value="find"
forceMount
className="data-[state=inactive]:hidden"
>
<ScannerTab session={wb.session} game={wb.game} />
</TabsContent>
<TabsContent
value="memory"
forceMount
className="data-[state=inactive]:hidden"
>
<MemoryTab />
</TabsContent>
<TabsContent
value="code"
forceMount
className="data-[state=inactive]:hidden"
>
<CodeTab />
</TabsContent>
</Tabs>
<EntryEditor />
</>
);
}
+367
View File
@@ -0,0 +1,367 @@
// The dialog for creating or changing one entry in your own cheat table.
import { useState } from 'react';
import { PlusIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import { hexToBytes } from '../lib/bytes.ts';
import type { Location } from '../lib/locations.ts';
import { VALUE_KINDS, encodeValue, valueKind } from '../lib/scanner.ts';
import { SCRIPT_REFERENCE } from '../lib/script.ts';
import { patchSites } from '../lib/table.ts';
import type { Entry, PatchSite } from '../lib/table.ts';
import { parsePattern } from '../lib/x86.ts';
import { Notice, errorText } from './bits.tsx';
import { useWorkbench } from './workbench.tsx';
const TITLES: Record<Entry['type'], { title: string; help: string }> = {
patch: { title: 'Patch', help: 'Replaces bytes of the game with others while it is switched on. Most cheats are this: a few bytes that turn an instruction into "do nothing".' },
value: { title: 'Value', help: 'Sets a number in the game, once or held in place.' },
inject: { title: 'Injected code', help: 'Redirects a point in the game through your own assembly, for changes a simple patch cannot express.' },
call: { title: 'Function call', help: 'Calls one of the game\'s own functions, such as the one that gives an item.' },
script: { title: 'Script', help: 'A few lines of JavaScript with logic: watch a value, react to it, switch other cheats.' },
};
const LOCATION_KINDS: { id: Location['kind']; label: string }[] = [
{ id: 'signature', label: 'Byte pattern in the code' },
{ id: 'module', label: 'Offset into the game' },
{ id: 'pointer', label: 'Pointer path' },
{ id: 'address', label: 'Raw address (this session only)' },
];
function blankLocation(kind: Location['kind']): Location {
switch (kind) {
case 'signature':
return { kind, pattern: '', offset: 0 };
case 'module':
return { kind, offset: '' };
case 'pointer':
return { kind, base: '', offsets: ['0x0'] };
case 'address':
return { kind, address: '' };
}
}
function checkHex(text: string, what: string): void {
if (!/^(0x)?[0-9a-fA-F]+$/.test(text.trim())) throw new Error(`${what} must be a hex number`);
}
function checkLocation(loc: Location): void {
switch (loc.kind) {
case 'signature':
parsePattern(loc.pattern);
if (!Number.isInteger(loc.offset)) throw new Error('The distance from the pattern must be a whole number');
break;
case 'module':
checkHex(loc.offset, 'The offset');
break;
case 'pointer':
checkHex(loc.base, 'The base offset');
if (loc.offsets.length === 0) throw new Error('A pointer path needs at least one offset');
loc.offsets.forEach((o) => checkHex(o.replace(/^-/, ''), 'Each pointer offset'));
break;
case 'address':
checkHex(loc.address, 'The address');
break;
}
}
function LocationFields(props: { label: string; value: Location; onChange: (loc: Location) => void; kinds?: Location['kind'][] }) {
const loc = props.value;
const kinds = LOCATION_KINDS.filter((k) => !props.kinds || props.kinds.includes(k.id));
return (
<div className="flex flex-col gap-2 rounded-md border p-3">
<Label>{props.label}</Label>
<Select value={loc.kind} onValueChange={(k) => props.onChange(blankLocation(k as Location['kind']))}>
<SelectTrigger className="w-full" aria-label={`${props.label}: how it is found`}>
<SelectValue />
</SelectTrigger>
<SelectContent>
{kinds.map((k) => (
<SelectItem key={k.id} value={k.id}>
{k.label}
</SelectItem>
))}
</SelectContent>
</Select>
{loc.kind === 'signature' && (
<>
<Input className="font-mono" aria-label="Byte pattern" placeholder="89 81 ?? ?? 00 00" value={loc.pattern} onChange={(e) => props.onChange({ ...loc, pattern: e.target.value })} />
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span className="shrink-0">Bytes past the match</span>
<Input className="w-24 font-mono" aria-label="Bytes past the match" inputMode="numeric" value={String(loc.offset)} onChange={(e) => props.onChange({ ...loc, offset: parseInt(e.target.value, 10) || 0 })} />
</div>
<p className="text-xs text-muted-foreground">Use ?? for bytes that can be anything. Keeps working after most game updates.</p>
</>
)}
{loc.kind === 'module' && (
<>
<Input className="font-mono" aria-label="Offset" placeholder="1A2B3C" value={loc.offset} onChange={(e) => props.onChange({ ...loc, offset: e.target.value })} />
<p className="text-xs text-muted-foreground">Hex distance from the start of the game's executable. Breaks when the game is updated.</p>
</>
)}
{loc.kind === 'pointer' && (
<>
<Input className="font-mono" aria-label="Base offset" placeholder="Base offset, e.g. 2F4A10" value={loc.base} onChange={(e) => props.onChange({ ...loc, base: e.target.value })} />
<Input
className="font-mono"
aria-label="Pointer offsets"
placeholder="Offsets, e.g. 0x8, 0x340"
value={loc.offsets.join(', ')}
onChange={(e) => props.onChange({ ...loc, offsets: e.target.value.split(/[\s,]+/).filter(Boolean) })}
/>
<p className="text-xs text-muted-foreground">Reads the pointer stored at game+base, then follows each offset. For values that move every launch.</p>
</>
)}
{loc.kind === 'address' && (
<Input className="font-mono" aria-label="Address" placeholder="880012340" value={loc.address} onChange={(e) => props.onChange({ ...loc, address: e.target.value })} />
)}
</div>
);
}
export function EntryEditor() {
const wb = useWorkbench();
const editing = wb.editing;
if (!editing) return null;
// Remount per entry so the form state starts from that entry.
return <EditorDialog key={editing.entry.id} entry={editing.entry} isNew={editing.isNew} />;
}
function EditorDialog(props: { entry: Entry; isNew: boolean }) {
const wb = useWorkbench();
const [draft, setDraft] = useState<Entry>(props.entry);
const [error, setError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const info = TITLES[draft.type];
const set = (patch: Partial<Entry>) => setDraft((d) => ({ ...d, ...patch }) as Entry);
const save = async () => {
setError(null);
try {
if (!draft.name.trim()) throw new Error('Give it a name');
switch (draft.type) {
case 'patch':
patchSites(draft).forEach((site, i) => {
const which = i === 0 ? '' : ` for place ${i + 1}`;
checkLocation(site.at);
if (hexToBytes(site.on).length === 0) throw new Error(`Enter the bytes to write${which}`);
if (site.off && hexToBytes(site.off).length === 0) throw new Error(`The original bytes${which} are not valid hex`);
});
break;
case 'value':
checkLocation(draft.at);
encodeValue(valueKind(draft.valueType), draft.value);
break;
case 'inject':
checkLocation(draft.at);
break;
case 'call':
checkLocation(draft.fn);
if (draft.args.length > 6) throw new Error('A call takes at most six arguments');
draft.args.forEach((a) => BigInt(a.trim()));
break;
case 'script':
if (!draft.code.trim()) throw new Error('The script is empty');
break;
}
} catch (e) {
setError(e instanceof SyntaxError ? 'One of the numbers is not valid' : errorText(e));
return;
}
setSaving(true);
try {
const entry = { ...draft, name: draft.name.trim(), unreviewed: undefined } as Entry;
if (props.isNew) {
await wb.addEntry(entry, { enable: false });
} else {
// Undo the old version before replacing it, so nothing is left applied that can no longer be switched off.
const old = wb.table.entries.find((e) => e.id === entry.id);
if (old && wb.runner.isOn(old.id)) await wb.runner.disable(old).catch(() => undefined);
wb.setTable((t) => ({ ...t, entries: t.entries.map((e) => (e.id === entry.id ? entry : e)) }));
}
wb.closeEditor();
} finally {
setSaving(false);
}
};
return (
<Dialog open onOpenChange={(open) => !open && wb.closeEditor()}>
<DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-xl">
<DialogHeader>
<DialogTitle>
{props.isNew ? 'New' : 'Edit'}: {info.title}
</DialogTitle>
<DialogDescription>{info.help}</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<Label htmlFor="entry-name">Name</Label>
<Input id="entry-name" value={draft.name} placeholder="Infinite ammo" onChange={(e) => set({ name: e.target.value })} />
</div>
{draft.type === 'patch' && (
<>
<LocationFields label="Where" value={draft.at} onChange={(at) => set({ at })} />
<div className="flex flex-col gap-2">
<Label htmlFor="entry-on">Bytes when on</Label>
<Input id="entry-on" className="font-mono" placeholder="90 90 90" value={draft.on} onChange={(e) => set({ on: e.target.value })} />
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="entry-off">Original bytes (optional)</Label>
<Input id="entry-off" className="font-mono" placeholder="FF 4B 28" value={draft.off ?? ''} onChange={(e) => set({ off: e.target.value || undefined })} />
<p className="text-xs text-muted-foreground">If given, the patch is refused when the game does not contain these bytes there, which catches a wrong game version.</p>
</div>
{(draft.more ?? []).map((site, i) => {
const change = (next: Partial<PatchSite>) =>
set({ more: (draft.more ?? []).map((x, k) => (k === i ? { ...x, ...next } : x)) } as Partial<Entry>);
return (
<div key={i} className="flex flex-col gap-3 rounded-md border border-dashed p-3">
<div className="flex items-center justify-between">
<span className="text-sm font-medium">Place {i + 2}</span>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => {
const rest = (draft.more ?? []).filter((_, k) => k !== i);
set({ more: rest.length ? rest : undefined } as Partial<Entry>);
}}
>
Remove
</Button>
</div>
<LocationFields label="Where" value={site.at} onChange={(at) => change({ at })} />
<Input className="font-mono" aria-label={`Bytes when on, place ${i + 2}`} placeholder="Bytes when on" value={site.on} onChange={(e) => change({ on: e.target.value })} />
<Input
className="font-mono"
aria-label={`Original bytes, place ${i + 2}`}
placeholder="Original bytes (optional)"
value={site.off ?? ''}
onChange={(e) => change({ off: e.target.value || undefined })}
/>
</div>
);
})}
<div>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => set({ more: [...(draft.more ?? []), { at: { kind: 'signature', pattern: '', offset: 0 }, on: '' }] } as Partial<Entry>)}
>
<PlusIcon /> Add another place
</Button>
<p className="mt-1.5 text-xs text-muted-foreground">For a cheat that has to change the game in more than one spot. One switch turns them all on and off together.</p>
</div>
</>
)}
{draft.type === 'value' && (
<>
<LocationFields label="Where" value={draft.at} onChange={(at) => set({ at })} kinds={['pointer', 'module', 'address']} />
<div className="grid grid-cols-2 gap-3">
<div className="flex flex-col gap-2">
<Label htmlFor="entry-type">Type</Label>
<Select value={draft.valueType} onValueChange={(valueType) => set({ valueType })}>
<SelectTrigger id="entry-type" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
{VALUE_KINDS.map((k) => (
<SelectItem key={k.id} value={k.id}>
{k.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="entry-value">Value</Label>
<Input id="entry-value" className="font-mono" value={draft.value} onChange={(e) => set({ value: e.target.value })} />
</div>
</div>
<label className="flex items-center gap-3 text-sm">
<Switch checked={draft.freeze} onCheckedChange={(freeze) => set({ freeze })} />
Hold it at this value (a switch) instead of setting it once (a button)
</label>
</>
)}
{draft.type === 'inject' && (
<>
<LocationFields label="Hook where" value={draft.at} onChange={(at) => set({ at })} kinds={['signature', 'module', 'address']} />
<div className="flex flex-col gap-2">
<Label htmlFor="entry-place">The game's own instructions at that spot</Label>
<Select value={draft.placement} onValueChange={(placement) => set({ placement: placement as 'before' | 'after' | 'replace' })}>
<SelectTrigger id="entry-place" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="before">Run after my code</SelectItem>
<SelectItem value="after">Run before my code</SelectItem>
<SelectItem value="replace">Do not run (my code replaces them)</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="entry-asm">Assembly (x86-64, Intel syntax)</Label>
<Textarea id="entry-asm" className="min-h-32 font-mono text-sm" spellCheck={false} placeholder={'mov dword ptr [rcx+0x390], 999'} value={draft.code} onChange={(e) => set({ code: e.target.value })} />
<p className="text-xs text-muted-foreground">Assembled on the console when switched on. Do not end with a jump back; that is added for you.</p>
<p className="text-xs text-muted-foreground">
The game keeps running while the hook is written. Switch it on at a quiet moment (a pause menu), not while that
code is busy.
</p>
</div>
</>
)}
{draft.type === 'call' && (
<>
<LocationFields label="Function" value={draft.fn} onChange={(fn) => set({ fn })} kinds={['signature', 'module', 'address']} />
<div className="flex flex-col gap-2">
<Label htmlFor="entry-args">Arguments</Label>
<Input id="entry-args" className="font-mono" placeholder="0x1F, 1" value={draft.args.join(', ')} onChange={(e) => set({ args: e.target.value.split(/[\s,]+/).filter(Boolean) })} />
<p className="text-xs text-muted-foreground">Up to six whole numbers, decimal or 0x hex, in the order the function takes them.</p>
<p className="text-xs text-muted-foreground">
The function has to return within about two seconds. If it returns -1 the console takes that as a failure and
calls it again, up to seven times, so avoid functions that can.
</p>
</div>
</>
)}
{draft.type === 'script' && (
<div className="flex flex-col gap-2">
<Label htmlFor="entry-code">Script</Label>
<Textarea id="entry-code" className="min-h-48 font-mono text-sm" spellCheck={false} value={draft.code} onChange={(e) => set({ code: e.target.value })} />
<details className="text-xs text-muted-foreground">
<summary className="cursor-pointer">What a script can do</summary>
<pre className="mt-2 overflow-x-auto rounded-md bg-muted p-3 font-mono leading-relaxed">{SCRIPT_REFERENCE}</pre>
</details>
</div>
)}
{error && <Notice kind="error">{error}</Notice>}
</div>
<DialogFooter>
<Button variant="outline" onClick={wb.closeEditor}>
Cancel
</Button>
<Button disabled={saving} onClick={() => void save()}>
Save
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+243
View File
@@ -0,0 +1,243 @@
// The console's game library: what is installed, for which PlayStation, how
// big, and a button to start it.
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { PlayIcon, RefreshCwIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Pill } from '@/components/kibo-ui/pill';
import { Spinner } from '@/components/kibo-ui/spinner';
import { LibraryUnavailable, cachedMeta, fetchLibrary, fetchTitleMeta, formatSize, iconUrl, launchTitle } from '../lib/library.ts';
import type { LibraryTitle, TitleMeta } from '../lib/library.ts';
import type { Game, Target } from '../lib/session.ts';
import { Ghost, Notice, errorText } from './bits.tsx';
const SEARCH_FROM = 8;
type State =
| { name: 'loading' }
| { name: 'unavailable' }
| { name: 'error'; text: string }
| { name: 'ready'; titles: LibraryTitle[] };
function TitleIcon(props: { target: Target | null; id: string }) {
const [broken, setBroken] = useState(false);
return (
<div className="flex size-12 shrink-0 items-center justify-center overflow-hidden rounded-md border bg-muted">
{broken ? (
<Ghost size={26} className="opacity-50" />
) : (
<img src={iconUrl(props.target, props.id)} alt="" loading="lazy" className="size-full object-cover" onError={() => setBroken(true)} />
)}
</div>
);
}
export function LibraryView(props: {
target: Target | null;
/** True when the page is served by the PS5 itself. */
onConsole: boolean;
running: Game | null;
runningName: string;
/** Called once the console has accepted a request to start a game. */
onStarted?: () => void;
}) {
const { target, running } = props;
const [state, setState] = useState<State>({ name: 'loading' });
const [metas, setMetas] = useState<Record<string, TitleMeta>>({});
const [query, setQuery] = useState('');
const [confirm, setConfirm] = useState<LibraryTitle | null>(null);
const [starting, setStarting] = useState<string | null>(null);
const [startError, setStartError] = useState<string | null>(null);
const [startedId, setStartedId] = useState<string | null>(null);
const generation = useRef(0);
const load = useCallback(async () => {
const mine = ++generation.current;
setState({ name: 'loading' });
try {
const titles = await fetchLibrary(target);
if (mine !== generation.current) return;
const known: Record<string, TitleMeta> = {};
for (const t of titles) {
const cached = cachedMeta(t.id);
if (cached) known[t.id] = cached;
}
setMetas(known);
setState({ name: 'ready', titles });
// Names come one file per game; a few at a time keeps the console responsive.
const queue = [...titles];
const worker = async () => {
for (let t = queue.shift(); t; t = queue.shift()) {
if (mine !== generation.current) return;
const id = t.id;
const meta = await fetchTitleMeta(target, id, t.platform).catch(() => null);
if (meta && mine === generation.current) setMetas((prev) => ({ ...prev, [id]: meta }));
}
};
await Promise.all([worker(), worker(), worker(), worker()]);
} catch (e) {
if (mine !== generation.current) return;
setState(e instanceof LibraryUnavailable ? { name: 'unavailable' } : { name: 'error', text: errorText(e) });
}
}, [target]);
useEffect(() => {
void load();
return () => {
generation.current++;
};
}, [load]);
// The game that was asked for is now the one running: nothing left to say.
useEffect(() => {
if (startedId && running?.titleId === startedId) setStartedId(null);
}, [running?.titleId, startedId]);
const rows = useMemo(() => {
if (state.name !== 'ready') return [];
const needle = query.trim().toLowerCase();
return state.titles
.map((t) => ({ title: t, name: metas[t.id]?.name ?? '' }))
.filter((r) => !needle || r.name.toLowerCase().includes(needle) || r.title.id.toLowerCase().includes(needle))
.sort((a, b) => (a.name || a.title.id).localeCompare(b.name || b.title.id));
}, [state, metas, query]);
const start = async (title: LibraryTitle) => {
setConfirm(null);
setStartError(null);
setStartedId(null);
setStarting(title.id);
try {
await launchTitle(target, title.id);
setStartedId(title.id);
props.onStarted?.();
} catch (e) {
setStartError(
e instanceof LibraryUnavailable
? 'The CheatSpecter payload on the console stopped answering. Send cheatspecter.elf to the PS5 again.'
: `${metas[title.id]?.name ?? title.id} did not start. ${errorText(e)}`,
);
} finally {
setStarting(null);
}
};
if (state.name === 'loading') {
return (
<p className="flex items-center gap-2 py-2 text-sm text-muted-foreground">
<Spinner className="size-4" /> Reading the game library…
</p>
);
}
if (state.name === 'unavailable') {
return (
<Notice>
{props.onConsole
? 'This console is running an older CheatSpecter payload without the game library. Send the new cheatspecter.elf to the PS5 to see your games here.'
: 'To see your games here, show their names and start them from this page, send payload/cheatspecter.elf to the PS5 (the same way you load ps5debug). Everything else works without it.'}{' '}
<button type="button" className="underline underline-offset-2" onClick={() => void load()}>
Check again
</button>
</Notice>
);
}
if (state.name === 'error') {
return (
<Notice kind="error">
The game library could not be read. {state.text}{' '}
<button type="button" className="underline underline-offset-2" onClick={() => void load()}>
Try again
</button>
</Notice>
);
}
const confirmName = confirm ? (metas[confirm.id]?.name ?? confirm.id) : '';
return (
<div className="flex min-w-0 flex-col gap-3">
<div className="flex items-center gap-2">
{state.titles.length >= SEARCH_FROM ? (
<Input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search your games" aria-label="Search your games" className="h-9" />
) : (
<span className="mr-auto text-sm text-muted-foreground">
{state.titles.length} {state.titles.length === 1 ? 'game' : 'games'}
</span>
)}
<Button variant="outline" size="sm" className="ml-auto shrink-0" onClick={() => void load()}>
<RefreshCwIcon /> Refresh
</Button>
</div>
{startError && <Notice kind="error">{startError}</Notice>}
{startedId && <Notice>Starting {metas[startedId]?.name ?? startedId}. It will appear here as soon as it is running.</Notice>}
{state.titles.length === 0 ? (
<p className="py-4 text-center text-sm text-muted-foreground">The console did not report any installed games.</p>
) : rows.length === 0 ? (
<p className="py-4 text-center text-sm text-muted-foreground">No game matches that search.</p>
) : (
<ul className="flex flex-col divide-y rounded-md border">
{rows.map(({ title, name }) => {
const isRunning = running?.titleId === title.id;
const size = formatSize(title.size);
return (
<li key={title.id} className="flex items-center gap-3 p-2.5">
<TitleIcon target={target} id={title.id} />
<div className="flex min-w-0 flex-1 flex-col gap-1">
<span className="truncate font-medium" title={name || title.id}>
{name || title.id}
</span>
<div className="flex flex-wrap gap-1.5">
<Pill className={title.platform === 'PS5' ? 'border-primary/60 text-xs text-primary' : 'text-xs'} variant="outline">
{title.platform}
</Pill>
<Pill className="font-mono text-xs">{title.id}</Pill>
{size && (
<Pill className="text-xs" title={title.path}>
{title.partial ? `over ${size}` : size}
</Pill>
)}
</div>
</div>
{isRunning ? (
<span className="shrink-0 px-2 text-sm font-medium text-primary">Running</span>
) : (
<Button
size="sm"
variant="outline"
className="shrink-0"
disabled={starting !== null}
onClick={() => (running ? setConfirm(title) : void start(title))}
aria-label={`Start ${name || title.id}`}
>
{starting === title.id ? <Spinner className="size-4" /> : <PlayIcon />} Start
</Button>
)}
</li>
);
})}
</ul>
)}
<Dialog open={confirm !== null} onOpenChange={(open) => !open && setConfirm(null)}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Start {confirmName}?</DialogTitle>
<DialogDescription>
This closes {props.runningName || running?.titleId || 'the running game'} first. Anything it has not saved is lost, and cheats
that are switched on go with it.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setConfirm(null)}>
Keep playing
</Button>
<Button onClick={() => confirm && void start(confirm)}>Close it and start</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
+326
View File
@@ -0,0 +1,326 @@
// A live hex view of the game's memory, with a panel that reads the selected
// bytes as the usual number types and lets them be changed.
import { useCallback, useEffect, useRef, useState } from 'react';
import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { cn } from '@/lib/utils';
import { fmtAddr, hexToBytes, view } from '../lib/bytes.ts';
import { imageRange, parseAddress } from '../lib/locations.ts';
import { valueEntry } from '../lib/make.ts';
import { PROT } from '../lib/ps5debug.ts';
import { VALUE_KINDS, decodeValue, encodeValue, valueKind } from '../lib/scanner.ts';
import { Notice, errorText } from './bits.tsx';
import { useWorkbench } from './workbench.tsx';
const REFRESH_MS = 1000;
function useColumns(): number {
const [cols, setCols] = useState(() => (typeof window !== 'undefined' && window.innerWidth < 640 ? 8 : 16));
useEffect(() => {
const mq = window.matchMedia('(min-width: 640px)');
const update = () => setCols(mq.matches ? 16 : 8);
update();
mq.addEventListener('change', update);
return () => mq.removeEventListener('change', update);
}, []);
return cols;
}
export function MemoryTab() {
const wb = useWorkbench();
const { ctx } = wb;
const cols = useColumns();
const length = cols * 16;
const [text, setText] = useState('');
const [base, setBase] = useState<bigint | null>(null);
const [data, setData] = useState<Uint8Array | null>(null);
const [changed, setChanged] = useState<Set<number>>(new Set());
const [selected, setSelected] = useState(0);
const [error, setError] = useState<string | null>(null);
const [kindId, setKindId] = useState('u32');
const [newValue, setNewValue] = useState('');
const [newBytes, setNewBytes] = useState('');
const [writeError, setWriteError] = useState<string | null>(null);
const previous = useRef<Uint8Array | null>(null);
const go = useCallback(
(address: bigint, select = true) => {
// Rows start on a 16-byte boundary so addresses are easy to read down the side.
const start = address & ~0xfn;
setBase(start);
setText(fmtAddr(address));
if (select) setSelected(Number(address - start));
previous.current = null;
setData(null);
setError(null);
},
[],
);
// Another tab asked to show an address.
useEffect(() => {
if (wb.memoryAt !== null) go(wb.memoryAt);
}, [wb.memoryAt, go]);
// First visit with nothing chosen: open at the game's static data, or its start.
useEffect(() => {
if (wb.tab !== 'memory' || base !== null) return;
let cancelled = false;
(async () => {
try {
const range = await imageRange(ctx);
const maps = await ctx.maps();
const dataMap = maps.find((m) => m.start >= range.start && m.start < range.end && m.prot & PROT.WRITE && !(m.prot & PROT.EXEC));
if (!cancelled) go(dataMap ? dataMap.start : range.start, false);
} catch (e) {
if (!cancelled) setError(errorText(e));
}
})();
return () => {
cancelled = true;
};
}, [wb.tab, base, ctx, go]);
// Keep the view current while the tab is open.
useEffect(() => {
if (wb.tab !== 'memory' || base === null) return;
let stopped = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const tick = async () => {
try {
const bytes = await ctx.dbg().read(ctx.pid, base, length);
if (stopped) return;
const prev = previous.current;
const diff = new Set<number>();
if (prev && prev.length === bytes.length) for (let i = 0; i < bytes.length; i++) if (prev[i] !== bytes[i]) diff.add(i);
previous.current = bytes;
setChanged(diff);
setData(bytes);
setError(null);
} catch (e) {
if (!stopped) setError(errorText(e));
}
if (!stopped) timer = setTimeout(tick, REFRESH_MS);
};
void tick();
return () => {
stopped = true;
clearTimeout(timer);
};
}, [wb.tab, base, length, ctx]);
const submit = async () => {
try {
go(await parseAddress(ctx, text));
} catch (e) {
setError(errorText(e));
}
};
const sel = Math.min(selected, length - 1);
const selAddress = base !== null ? base + BigInt(sel) : null;
const kind = valueKind(kindId);
const at = (size: number) => (data && sel + size <= data.length ? data.subarray(sel, sel + size) : null);
const pointer = at(8) ? view(at(8)!).getBigUint64(0, true) : null;
const looksLikePointer = pointer !== null && pointer > 0x10000n && pointer < 0x0000800000000000n;
const write = async (bytes: Uint8Array) => {
if (selAddress === null) return;
setWriteError(null);
try {
await ctx.dbg().write(ctx.pid, selAddress, bytes);
previous.current = null;
} catch (e) {
setWriteError(errorText(e));
}
};
const writeValue = () => {
try {
void write(encodeValue(kind, newValue));
} catch (e) {
setWriteError(errorText(e));
}
};
const writeRaw = () => {
try {
const bytes = hexToBytes(newBytes);
if (bytes.length === 0) throw new Error('Enter some bytes, for example: 90 90 90');
void write(bytes);
} catch (e) {
setWriteError(errorText(e));
}
};
const rows = data ? Array.from({ length: data.length / cols }, (_, r) => r) : [];
return (
<div className="flex flex-col gap-4">
<Card>
<CardHeader>
<CardTitle>Memory</CardTitle>
<CardDescription>The game's memory as it is right now. Bytes that just changed are highlighted. Click one to read or change it.</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<form
className="flex gap-2"
onSubmit={(e) => {
e.preventDefault();
void submit();
}}
>
<Input className="font-mono" aria-label="Address" placeholder="Address, or game+1A2B3C" value={text} onChange={(e) => setText(e.target.value)} />
<Button type="submit">Go</Button>
<Button type="button" variant="outline" size="icon" aria-label="Previous page" disabled={base === null} onClick={() => base !== null && go(base - BigInt(length), false)}>
<ChevronLeftIcon />
</Button>
<Button type="button" variant="outline" size="icon" aria-label="Next page" disabled={base === null} onClick={() => base !== null && go(base + BigInt(length), false)}>
<ChevronRightIcon />
</Button>
</form>
{error && <Notice kind="error">{error}</Notice>}
{data && base !== null && (
<div className="overflow-x-auto">
<table className="font-mono text-xs leading-6 sm:text-sm" aria-label="Memory bytes">
<tbody>
{rows.map((r) => (
<tr key={r}>
<td className="pr-3 text-muted-foreground select-none">{(base + BigInt(r * cols)).toString(16).toUpperCase()}</td>
<td className="whitespace-nowrap">
{Array.from({ length: cols }, (_, c) => {
const i = r * cols + c;
return (
<button
key={c}
type="button"
aria-label={`Byte at ${fmtAddr(base + BigInt(i))}`}
aria-pressed={i === sel}
className={cn(
'rounded-sm px-[3px] hover:bg-accent',
c === 8 && 'ml-2',
data[i] === 0 && 'text-muted-foreground/60',
changed.has(i) && 'text-primary',
i >= sel && i < sel + kind.size && 'bg-accent',
i === sel && 'bg-primary text-primary-foreground hover:bg-primary',
)}
onClick={() => setSelected(i)}
>
{data[i].toString(16).padStart(2, '0').toUpperCase()}
</button>
);
})}
</td>
<td className="pl-3 whitespace-pre text-muted-foreground select-none max-sm:hidden">
{Array.from({ length: cols }, (_, c) => {
const b = data[r * cols + c];
return b >= 0x20 && b < 0x7f ? String.fromCharCode(b) : '.';
}).join('')}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
{data && selAddress !== null && (
<Card>
<CardHeader>
<CardTitle className="font-mono">{fmtAddr(selAddress)}</CardTitle>
<CardDescription>What the bytes starting here mean as each kind of number.</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 font-mono text-sm sm:grid-cols-[auto_1fr_auto_1fr]">
{['u8', 'u16', 'u32', 'u64', 'i32', 'float', 'double'].map((id) => {
const k = valueKind(id);
const bytes = at(k.size);
return [
<dt key={id + 'k'} className="text-muted-foreground">
{k.label}
</dt>,
<dd key={id + 'v'} className="truncate">
{bytes ? decodeValue(k, bytes) : '—'}
</dd>,
];
})}
<dt className="text-muted-foreground">Pointer</dt>
<dd className="flex items-center gap-2 truncate">
{pointer !== null ? fmtAddr(pointer) : '—'}
{looksLikePointer && (
<Button variant="outline" size="xs" onClick={() => go(pointer!)}>
Follow
</Button>
)}
</dd>
</dl>
<div className="grid gap-3 sm:grid-cols-2">
<div className="flex flex-col gap-2">
<Label htmlFor="mem-value">Change it as a number</Label>
<div className="flex gap-2">
<Select value={kindId} onValueChange={setKindId}>
<SelectTrigger className="w-36 shrink-0" aria-label="Number type">
<SelectValue />
</SelectTrigger>
<SelectContent>
{VALUE_KINDS.map((k) => (
<SelectItem key={k.id} value={k.id}>
{k.label}
</SelectItem>
))}
</SelectContent>
</Select>
<Input id="mem-value" className="min-w-0 font-mono" value={newValue} onChange={(e) => setNewValue(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && writeValue()} />
<Button variant="outline" disabled={!newValue.trim()} onClick={writeValue}>
Write
</Button>
</div>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="mem-bytes">Or as raw bytes</Label>
<div className="flex gap-2">
<Input id="mem-bytes" className="min-w-0 font-mono" placeholder="90 90 90" value={newBytes} onChange={(e) => setNewBytes(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && writeRaw()} />
<Button variant="outline" disabled={!newBytes.trim()} onClick={writeRaw}>
Write
</Button>
</div>
</div>
</div>
{writeError && <Notice kind="error">{writeError}</Notice>}
<div className="flex flex-wrap gap-2">
<Button variant="outline" size="sm" onClick={() => wb.startTrace(selAddress, kind.size as 1 | 2 | 4 | 8, 'write')}>
Find what writes to this
</Button>
<Button
variant="outline"
size="sm"
onClick={async () => {
const bytes = at(kind.size);
if (!bytes) return;
const entry = await valueEntry(ctx, selAddress, kind, decodeValue(kind, bytes));
await wb.addEntry(entry, { enable: false });
wb.edit(entry, false);
}}
>
Save to your cheats
</Button>
<Button variant="outline" size="sm" onClick={() => wb.showCode(selAddress)}>
View as code
</Button>
</div>
</CardContent>
</Card>
)}
</div>
);
}
+273
View File
@@ -0,0 +1,273 @@
// "Your cheats": the user's own table, as switches and buttons.
import { useState } from 'react';
import { MoreHorizontalIcon, PlusIcon, SaveIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Switch } from '@/components/ui/switch';
import { Spinner } from '@/components/kibo-ui/spinner';
import { describeEntry, exportCommunityTable, isAction, newId } from '../lib/table.ts';
import { Ps5StorageUnavailable, deviceFileText, saveToDevice, tableFileName } from '../lib/tablestore.ts';
import type { Entry } from '../lib/table.ts';
import { Notice } from './bits.tsx';
import { useWorkbench } from './workbench.tsx';
const SCRIPT_TEMPLATE = `// Keep health topped up. Change the address to your own.
const health = await cs.pointer("game+10100", 0x340);
while (true) {
if ((await cs.read(health, "u32")) < 50) await cs.write(health, "u32", 100);
await cs.sleep(250);
}
`;
function blank(type: Entry['type']): Entry {
const base = { id: newId(), name: '' };
switch (type) {
case 'patch':
return { ...base, type, at: { kind: 'signature', pattern: '', offset: 0 }, on: '' };
case 'value':
return { ...base, type, at: { kind: 'pointer', base: '', offsets: ['0x0'] }, valueType: 'u32', value: '', freeze: true };
case 'inject':
return { ...base, type, at: { kind: 'signature', pattern: '', offset: 0 }, code: '', placement: 'before' };
case 'call':
return { ...base, type, fn: { kind: 'module', offset: '' }, args: [] };
case 'script':
return { ...base, type, code: SCRIPT_TEMPLATE };
}
}
export function OwnCheats() {
const wb = useWorkbench();
const { table, runner } = wb;
const [notice, setNotice] = useState<string | null>(null);
const [warning, setWarning] = useState<string | null>(null);
const { ps5 } = wb;
const fileName = tableFileName(wb.game.titleId, wb.game.version);
const say = (text: string | null, warn: string | null = null) => {
setNotice(text);
setWarning(warn);
};
const saveOnPs5 = async () => {
say(null);
try {
await wb.saveToPs5();
say(`Saved on your PS5 as ${fileName}. It loads by itself whenever this game is running, and your changes are saved to it as you make them.`);
} catch (e) {
say(
null,
e instanceof Ps5StorageUnavailable
? 'Saving on the PS5 needs the CheatSpecter payload running on the console. Send payload/cheatspecter.elf to the PS5 (the same way you load ps5debug), then save again. "Save to this device" works without it.'
: `The PS5 did not save the file. ${e instanceof Error ? e.message : String(e)}`,
);
}
};
const saveOnDevice = async () => {
say(null);
const full = wb.fileTable();
const text = deviceFileText(full);
const left = full.entries.length - (JSON.parse(text) as { cheats: unknown[] }).cheats.length;
try {
const name = await saveToDevice(fileName, text);
if (name) {
say(
`Saved as ${name}. Drop that file onto this page to load it again.` +
(left ? ` ${left} ${left === 1 ? 'cheat uses' : 'cheats use'} a raw memory address, which only means something until the game restarts, so ${left === 1 ? 'it was' : 'they were'} left out.` : ''),
);
}
} catch (e) {
say(null, `The file could not be saved. ${e instanceof Error ? e.message : String(e)}`);
}
};
const exportCommunity = async () => {
const out = exportCommunityTable(wb.fileTable());
if (out.included === 0) {
say('None of your cheats can be written in the GoldHEN format. It only supports patches at a fixed offset with known original bytes.');
return;
}
const name = await saveToDevice(`${wb.game.titleId}_${wb.game.version || 'unknown'}.json`, out.text, 'GoldHEN / etaHEN cheats');
if (name) say(out.skipped ? `Exported ${out.included}. ${out.skipped} could not be written in that format and were left out.` : `Exported as ${name}.`);
};
const where =
ps5.status === 'saved'
? `Saved on your PS5 as ${fileName}.`
: ps5.status === 'saving'
? 'Saving to your PS5…'
: 'Kept in this browser for now. Use Save to put them in a file on your PS5 or this device.';
return (
<Card>
<CardHeader className="flex flex-row items-start justify-between gap-2">
<div className="flex flex-col gap-1.5">
<CardTitle>Your cheats</CardTitle>
<CardDescription>
{table.entries.length === 0
? 'Cheats you make or import appear here. The quickest way to make one: find a value, ask what writes to it, and disable that.'
: where}
</CardDescription>
</div>
<div className="flex shrink-0 gap-2">
{table.entries.length > 0 && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm">
<SaveIcon /> Save
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onSelect={() => void saveOnPs5()}>Save to PS5</DropdownMenuItem>
<DropdownMenuItem onSelect={() => void saveOnDevice()}>Save to this device…</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={() => void exportCommunity()}>Export for GoldHEN / etaHEN (simple patches)</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button size="sm">
<PlusIcon /> New
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>Write one by hand</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={() => wb.edit(blank('patch'), true)}>Patch</DropdownMenuItem>
<DropdownMenuItem onSelect={() => wb.edit(blank('value'), true)}>Value</DropdownMenuItem>
<DropdownMenuItem onSelect={() => wb.edit(blank('inject'), true)}>Injected code</DropdownMenuItem>
<DropdownMenuItem onSelect={() => wb.edit(blank('call'), true)}>Function call</DropdownMenuItem>
<DropdownMenuItem onSelect={() => wb.edit(blank('script'), true)}>Script</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</CardHeader>
{(table.entries.length > 0 || notice || warning || wb.saveFailed || ps5.status === 'failed') && (
<CardContent className="flex flex-col gap-3">
{wb.saveFailed && ps5.status !== 'saved' && ps5.status !== 'saving' && (
<Notice kind="warn">This browser would not keep your cheats (its storage is full or blocked). Use Save before closing the page.</Notice>
)}
{ps5.status === 'failed' && !warning && (
<Notice kind="warn">Your last changes did not reach the file on the PS5{ps5.error ? ` (${ps5.error})` : ''}. Use Save to try again.</Notice>
)}
{ps5.loadedFrom && (
<Notice>
These were loaded from the file you saved for v{ps5.loadedFrom} of this game. Check they still work, then use Save to PS5 to keep a
file for this version.
</Notice>
)}
{warning && <Notice kind="warn">{warning}</Notice>}
{runner.freezeError && <Notice kind="warn">Could not keep a held value in place: {runner.freezeError}</Notice>}
{notice && <Notice>{notice}</Notice>}
<ul className="divide-y">
{table.entries.map((entry) => (
<EntryRow key={entry.id} entry={entry} />
))}
</ul>
</CardContent>
)}
</Card>
);
}
function EntryRow(props: { entry: Entry }) {
const wb = useWorkbench();
const { entry } = props;
const [reviewing, setReviewing] = useState(false);
const on = wb.runner.isOn(entry.id);
const busy = wb.busy === entry.id;
const locked = wb.busy !== null && !busy;
const error = wb.errors[entry.id];
const result = wb.runner.result(entry.id);
const log = wb.logs[entry.id];
const mismatch = error?.includes('not what this cheat expects');
const code = entry.type === 'script' || entry.type === 'inject' ? entry.code : entry.type === 'call' ? describeEntry(entry) : '';
return (
<li className="flex flex-col gap-2 py-3 first:pt-0 last:pb-0">
<div className="flex items-center gap-3">
<div className="min-w-0 flex-1">
<div className="font-medium break-words">{entry.name}</div>
<div className="truncate font-mono text-xs text-muted-foreground" title={describeEntry(entry)}>
{describeEntry(entry)}
</div>
</div>
{busy && <Spinner className="size-4 text-muted-foreground" />}
{entry.unreviewed ? (
<Button variant="outline" size="sm" onClick={() => setReviewing((r) => !r)}>
Review
</Button>
) : isAction(entry) ? (
<Button variant="outline" size="sm" disabled={busy || locked} onClick={() => void wb.toggle(entry, true)}>
Run
</Button>
) : (
<Switch aria-label={entry.name} checked={on} disabled={busy || locked} onCheckedChange={(next) => void wb.toggle(entry, next)} />
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm" aria-label={`More for ${entry.name}`}>
<MoreHorizontalIcon />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onSelect={() => wb.edit(entry, false)}>Edit</DropdownMenuItem>
{wb.runner.address(entry.id) !== undefined && entry.type !== 'value' && (
<DropdownMenuItem onSelect={() => wb.showCode(wb.runner.address(entry.id)!)}>Show in Code</DropdownMenuItem>
)}
{wb.runner.address(entry.id) !== undefined && entry.type === 'value' && (
<DropdownMenuItem onSelect={() => wb.showMemory(wb.runner.address(entry.id)!)}>Show in Memory</DropdownMenuItem>
)}
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onSelect={() => void wb.removeEntry(entry)}>
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{entry.unreviewed && reviewing && (
<div className="flex flex-col gap-2">
<Notice kind="warn">
This came from a file and can run code in your game. Read it before allowing it. Only allow cheats from people you trust.
</Notice>
<pre className="max-h-64 overflow-auto rounded-md bg-muted p-3 font-mono text-xs whitespace-pre-wrap">{code}</pre>
<Button
className="self-start"
size="sm"
onClick={() => wb.setTable((t) => ({ ...t, entries: t.entries.map((e) => (e.id === entry.id ? ({ ...e, unreviewed: undefined } as Entry) : e)) }))}
>
I have read it; allow this cheat
</Button>
</div>
)}
{error && (
<div className="flex flex-wrap items-center gap-2 text-sm text-destructive" role="alert">
{error}
{mismatch && (
<Button variant="outline" size="xs" onClick={() => void wb.toggle(entry, true, true)}>
Apply anyway
</Button>
)}
</div>
)}
{result && !error && <div className="font-mono text-xs text-muted-foreground">{result}</div>}
{log && log.length > 0 && (
<pre className="max-h-40 overflow-auto rounded-md bg-muted p-2 font-mono text-xs whitespace-pre-wrap" aria-label={`Output of ${entry.name}`}>
{log.join('\n')}
</pre>
)}
</li>
);
}
+126
View File
@@ -0,0 +1,126 @@
// "Make it survive restarts": looks for a pointer path from the game's
// executable to a value found on the heap, and saves the value with it.
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Spinner } from '@/components/kibo-ui/spinner';
import { fmtAddr } from '../lib/bytes.ts';
import { describeLocation, moduleLocation } from '../lib/locations.ts';
import { valueEntry } from '../lib/make.ts';
import { findPointerPaths } from '../lib/pointerscan.ts';
import type { PointerPath } from '../lib/pointerscan.ts';
import type { ValueKind } from '../lib/scanner.ts';
import { Notice, errorText } from './bits.tsx';
import { useWorkbench } from './workbench.tsx';
export function PointerFinder(props: { address: bigint; kind: ValueKind; value: string; onClose: () => void }) {
const wb = useWorkbench();
const [depth, setDepth] = useState('3');
const [running, setRunning] = useState(false);
const [status, setStatus] = useState('');
const [paths, setPaths] = useState<PointerPath[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [isStatic, setIsStatic] = useState(false);
const search = async () => {
setError(null);
setPaths(null);
setRunning(true);
try {
if (await moduleLocation(wb.ctx, props.address)) {
// Already inside the executable: its offset is all that is needed.
setIsStatic(true);
return;
}
setPaths(await findPointerPaths(wb.ctx, props.address, { maxDepth: Number(depth) }, setStatus));
} catch (e) {
setError(errorText(e));
} finally {
setRunning(false);
setStatus('');
}
};
const use = async (path?: PointerPath) => {
const entry = await valueEntry(wb.ctx, props.address, props.kind, props.value, path?.location);
await wb.addEntry(entry, { enable: false });
props.onClose();
wb.edit(entry, false);
};
return (
<Dialog open onOpenChange={(open) => !open && !running && props.onClose()}>
<DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-xl">
<DialogHeader>
<DialogTitle>Make it survive restarts</DialogTitle>
<DialogDescription>
{fmtAddr(props.address)} will be somewhere else the next time the game starts. This looks for a chain of pointers,
starting from a fixed spot in the game, that leads to it every time.
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-4">
<div className="flex items-end gap-3">
<div className="flex flex-1 flex-col gap-2">
<Label htmlFor="ptr-depth">How deep to look</Label>
<Select value={depth} onValueChange={setDepth} disabled={running}>
<SelectTrigger id="ptr-depth" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="1">1 pointer (fastest)</SelectItem>
<SelectItem value="2">2 pointers</SelectItem>
<SelectItem value="3">3 pointers</SelectItem>
<SelectItem value="4">4 pointers (slow)</SelectItem>
</SelectContent>
</Select>
</div>
<Button disabled={running} onClick={() => void search()}>
{running ? <Spinner className="size-4" /> : null}
{running ? 'Searching…' : 'Search'}
</Button>
</div>
{running && <p className="text-sm text-muted-foreground">{status || 'Starting…'} Each level scans the game's memory again.</p>}
{error && <Notice kind="error">{error}</Notice>}
{isStatic && (
<Notice>
This value is inside the game's executable, so it does not move.{' '}
<Button size="xs" className="ml-1" onClick={() => void use()}>
Save it
</Button>
</Notice>
)}
{paths && paths.length === 0 && (
<Notice kind="warn">
No path found at this depth. Try one level deeper, or find what writes to the value and patch that code instead,
which does not depend on where the value lives.
</Notice>
)}
{paths && paths.length > 0 && (
<>
<p className="text-sm text-muted-foreground">
{paths.length} found, shortest first. Not every path is real: restart the game and check the cheat still shows the
right value. If it does not, try the next one.
</p>
<ul className="divide-y">
{paths.map((p, i) => (
<li key={i} className="flex items-center gap-3 py-2">
<span className="min-w-0 flex-1 font-mono text-xs break-all">{describeLocation(p.location)}</span>
<Button variant="outline" size="sm" onClick={() => void use(p)}>
Use
</Button>
</li>
))}
</ul>
</>
)}
</div>
</DialogContent>
</Dialog>
);
}
+559
View File
@@ -0,0 +1,559 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { LockIcon, LockOpenIcon, MoreHorizontalIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { cn } from '@/lib/utils';
import {
COMPARE_KINDS,
AUTO_KIND,
AutoScan,
ScanSession,
SnapshotScan,
VALUE_KINDS,
compareKind,
decodeValue,
encodeValue,
scannableRegions,
valueKind,
} from '../lib/scanner.ts';
import type { Scan, ScanHit, ScanProgress, ValueKind } from '../lib/scanner.ts';
import { valueEntry } from '../lib/make.ts';
import { TURBO } from '../lib/ps5debug.ts';
import { bytesEqual, concat, fmtAddr, fmtBytes } from '../lib/bytes.ts';
import type { Game, Session } from '../lib/session.ts';
import { Notice, PelletTrack, errorText } from './bits.tsx';
import { PointerFinder } from './PointerFinder.tsx';
import { useWorkbench } from './workbench.tsx';
const SHOWN = 60;
const LIVE_MS = 1000;
const FREEZE_MS = 250;
interface Frozen {
address: bigint;
kind: ValueKind;
bytes: Uint8Array;
}
/** One row: an address read as one type. An Auto search can list the same address under two types. */
const rowKey = (a: bigint, kind: ValueKind) => `${a.toString(16)}:${kind.id}`;
export function ScannerTab(props: { session: Session; game: Game }) {
const { session, game } = props;
const wb = useWorkbench();
const [pointerFor, setPointerFor] = useState<{ address: bigint; kind: ValueKind; value: string } | null>(null);
const [kindId, setKindId] = useState('u32');
const [compareId, setCompareId] = useState('exact');
const [value, setValue] = useState('');
const [value2, setValue2] = useState('');
const [running, setRunning] = useState(false);
const [progress, setProgress] = useState<ScanProgress | null>(null);
const [scope, setScope] = useState('');
const [error, setError] = useState<string | null>(null);
const [hits, setHits] = useState<ScanHit[]>([]);
const [matches, setMatches] = useState<number | null>(null);
const [live, setLive] = useState<Map<string, Uint8Array>>(new Map());
const [frozen, setFrozen] = useState<Map<string, Frozen>>(new Map());
const [edits, setEdits] = useState<Map<string, string>>(new Map());
const [rowError, setRowError] = useState<string | null>(null);
const [freezeError, setFreezeError] = useState<string | null>(null);
const scanRef = useRef<Scan | null>(null);
const frozenRef = useRef(frozen);
frozenRef.current = frozen;
const hitsRef = useRef(hits);
hitsRef.current = hits;
const started = matches !== null;
const kind = started && scanRef.current ? scanRef.current.kind : kindId === AUTO_KIND.id ? AUTO_KIND : valueKind(kindId);
const auto = kind.id === AUTO_KIND.id;
// "Unknown" keeps its list on the console, one type at a time, so it is not offered with Auto.
const compares = COMPARE_KINDS.filter((c) => (started ? c.id !== 'unknown' : c.first && !(auto && c.id === 'unknown')));
const compare = compareKind(compares.some((c) => c.id === compareId) ? compareId : 'exact');
const buildValue = (): Uint8Array => {
// Auto reads the typed text once per type, inside the scan.
if (compare.inputs === 0 || auto) return new Uint8Array(0);
const a = encodeValue(kind, value);
if (compare.inputs === 1) return a;
return concat(a, encodeValue(kind, value2));
};
const run = async (first: boolean) => {
setError(null);
setRowError(null);
let encoded: Uint8Array;
try {
encoded = buildValue();
} catch (e) {
setError(errorText(e));
return;
}
setRunning(true);
setProgress(null);
try {
if (first) {
const regions = scannableRegions(await session.scan.maps(game.pid));
if (regions.length === 0) throw new Error('The game has no writable memory to scan. Is it still running?');
const total = regions.reduce((n, r) => n + r.length, 0);
setScope(`Searching ${fmtBytes(total)} of game memory`);
let scan: Scan;
if (compare.id === 'unknown') {
// Every value is a candidate, so the list has to stay on the console.
const need = TURBO.ENGINE_SNAPSHOT | TURBO.ENGINE_SNAPSHOT_SEGMENTS;
if (((await session.scan.turboCaps()) & need) !== need) {
throw new Error('This debugger cannot search for an unknown value. Search for a number you can see instead.');
}
setScope(`Taking a snapshot of ${fmtBytes(total)} of game memory`);
scan = new SnapshotScan(() => session.scan, game.pid, kind);
} else if (auto) {
const all = new AutoScan(() => session.scan, game.pid);
all.input(value, value2);
scan = all;
} else {
scan = new ScanSession(() => session.scan, game.pid, kind);
}
await scan.first(regions, compare, encoded, setProgress);
scanRef.current = scan;
} else {
const scan = scanRef.current;
if (!scan) return;
setScope(`Checking ${scan.matches.toLocaleString()} candidates`);
if (scan instanceof AutoScan) scan.input(value, value2);
await scan.next(compare, encoded, setProgress);
}
const scan = scanRef.current!;
setMatches(scan.matches);
setHits(await scan.hits(SHOWN));
setLive(new Map());
setEdits(new Map());
} catch (e) {
setError(errorText(e));
if (first) {
scanRef.current = null;
setMatches(null);
setHits([]);
}
} finally {
setRunning(false);
setProgress(null);
}
};
// Free a snapshot held on the console when the tab goes away.
useEffect(() => () => void scanRef.current?.end(), []);
const reset = () => {
void scanRef.current?.end();
scanRef.current = null;
setMatches(null);
setHits([]);
setLive(new Map());
setEdits(new Map());
setError(null);
setRowError(null);
setCompareId('exact');
};
// Keep the visible values current.
useEffect(() => {
if (!started) return;
let stopped = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const tick = async () => {
const rows = hitsRef.current;
const scan = scanRef.current;
if (scan && rows.length && document.visibilityState === 'visible') {
try {
const next = new Map<string, Uint8Array>();
for (const h of rows) {
if (stopped) return;
next.set(rowKey(h.address, h.kind ?? scan.kind), await session.main.read(game.pid, h.address, (h.kind ?? scan.kind).size));
}
if (!stopped) setLive(next);
} catch {
// The session's own handlers report a lost connection.
}
}
if (!stopped) timer = setTimeout(tick, LIVE_MS);
};
void tick();
return () => {
stopped = true;
clearTimeout(timer);
};
}, [started, session, game.pid]);
// Keep frozen values pinned by rewriting them several times a second.
useEffect(() => {
let stopped = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const tick = async () => {
const list = [...frozenRef.current.values()];
if (list.length) {
try {
await session.main.writeMulti(
game.pid,
list.map((f) => ({ address: f.address, data: f.bytes })),
);
if (!stopped) setFreezeError(null);
} catch (e) {
if (!stopped) setFreezeError(`Could not keep ${list.length === 1 ? 'the value' : 'some values'} frozen: ${errorText(e)}`);
}
} else if (!stopped) {
setFreezeError(null);
}
if (!stopped) timer = setTimeout(tick, FREEZE_MS);
};
void tick();
return () => {
stopped = true;
clearTimeout(timer);
};
}, [session, game.pid]);
const writeValue = useCallback(
async (address: bigint, k: ValueKind, text: string): Promise<Uint8Array | null> => {
setRowError(null);
try {
const bytes = encodeValue(k, text);
await session.main.write(game.pid, address, bytes);
setLive((prev) => new Map(prev).set(rowKey(address, k), bytes));
return bytes;
} catch (e) {
setRowError(errorText(e));
return null;
}
},
[session, game.pid],
);
const toggleFreeze = async (address: bigint, current: Uint8Array, kind: ValueKind) => {
const key = rowKey(address, kind);
if (frozen.has(key)) {
const next = new Map(frozen);
next.delete(key);
setFrozen(next);
return;
}
// Freeze at whatever is typed in the box, otherwise at the current value.
const typed = edits.get(key)?.trim();
let bytes = current;
if (typed) {
const written = await writeValue(address, kind, typed);
if (!written) return;
bytes = written;
}
setFrozen(new Map(frozen).set(key, { address, kind, bytes }));
};
const setEdit = (key: string, text: string) => setEdits((prev) => new Map(prev).set(key, text));
const watchSize = (k: ValueKind) => k.size as 1 | 2 | 4 | 8;
const rowMenu = (address: bigint, k: ValueKind, current: Uint8Array): RowMenu => ({
onWrites: () => wb.startTrace(address, watchSize(k), 'write'),
onReads: () => wb.startTrace(address, watchSize(k), 'readwrite'),
onMemory: () => wb.showMemory(address),
onSave: async () => {
const entry = await valueEntry(wb.ctx, address, k, decodeValue(k, current));
await wb.addEntry(entry, { enable: false });
wb.edit(entry, false);
},
onPointer: () => setPointerFor({ address, kind: k, value: decodeValue(k, current) }),
});
const autoDropped = started && scanRef.current instanceof AutoScan ? scanRef.current.dropped : [];
const hitKeys = new Set(hits.map((h) => rowKey(h.address, h.kind ?? kind)));
const pinned = [...frozen.values()].filter((f) => !hitKeys.has(rowKey(f.address, f.kind)));
if (!session.extended) {
return (
<Notice kind="warn">
Finding values needs ps5debug-NG. The debugger on this console does not advertise the scan commands CheatSpecter
uses, and sending them to a payload that does not know them would hang the connection.
</Notice>
);
}
return (
<div className="flex flex-col gap-4">
<Card>
<CardHeader>
<CardTitle>Find a value</CardTitle>
<CardDescription>
{started
? 'Change the value in the game (take damage, spend money), then narrow down until a few addresses are left.'
: 'Type what the game shows right now, such as your health or money, and search for it. For a bar with no number, choose "Unknown".'}
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="grid grid-cols-2 gap-3 sm:grid-cols-[170px_190px_1fr]">
<div className="flex flex-col gap-2">
<Label htmlFor="kind">Type</Label>
<Select value={kind.id} disabled={started || running} onValueChange={setKindId}>
<SelectTrigger id="kind" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
{[AUTO_KIND, ...VALUE_KINDS].map((k) => (
<SelectItem key={k.id} value={k.id}>
{k.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="cmp">{started ? 'Value now is' : 'Value is'}</Label>
<Select value={compare.id} disabled={running} onValueChange={setCompareId}>
<SelectTrigger id="cmp" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
{compares.map((c) => (
<SelectItem key={c.id} value={c.id}>
{c.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="col-span-2 flex flex-col gap-2 sm:col-span-1">
<Label htmlFor="val">Value</Label>
<div className="flex items-center gap-2">
<Input
id="val"
className="font-mono"
inputMode="decimal"
placeholder={compare.inputs === 0 ? 'not needed' : kind.float ? '99.5' : '100'}
value={compare.inputs === 0 ? '' : value}
disabled={running || compare.inputs === 0}
onChange={(e) => setValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !running) void run(!started);
}}
/>
{compare.inputs === 2 && (
<>
<span className="text-sm text-muted-foreground">and</span>
<Input
className="font-mono"
inputMode="decimal"
aria-label="Upper value"
value={value2}
disabled={running}
onChange={(e) => setValue2(e.target.value)}
/>
</>
)}
</div>
</div>
</div>
<div className="flex flex-wrap items-center gap-2">
{!started ? (
<Button disabled={running} onClick={() => void run(true)}>
{running ? 'Searching…' : 'Search'}
</Button>
) : (
<>
<Button disabled={running || matches === 0} onClick={() => void run(false)}>
{running ? 'Narrowing…' : 'Narrow down'}
</Button>
<Button variant="outline" disabled={running} onClick={reset}>
New search
</Button>
</>
)}
{started && !running && (
<span className="text-sm text-muted-foreground max-sm:basis-full" aria-live="polite">
<strong className="text-foreground">{matches!.toLocaleString()}</strong> {matches === 1 ? 'match' : 'matches'}
{matches! > hits.length ? `, showing the first ${hits.length}` : ''}
</span>
)}
</div>
{running && (
<div>
<PelletTrack fraction={progress ? progress.fraction : null} label="Scan progress" />
<p className="text-sm text-muted-foreground" aria-live="polite">
{scope}
{progress?.detail ? ` ${progress.detail}` : ''}
{progress ? ` · ${progress.matches.toLocaleString()} matches so far` : ''}
</p>
</div>
)}
{auto && !started && !running && (
<p className="text-sm text-muted-foreground">
Auto looks for the number as 4 bytes, a float and a double, one after another, so the first search takes about three times
as long. Each result says which type it is.
</p>
)}
{autoDropped.length > 0 && !running && (
<Notice>
Left out of this search: {autoDropped.map((d) => `${d.kind.label.toLowerCase()} (${d.reason})`).join(', ')}. To search one of
those, start again and pick that type.
</Notice>
)}
{error && <Notice kind="error">{error}</Notice>}
{started && !running && matches === 0 && (
<Notice kind="warn">
Nothing left. The value may be stored differently than it looks (try Float, or 2 bytes), or it changed between
scans. Start a new search.
</Notice>
)}
</CardContent>
</Card>
{pointerFor && <PointerFinder {...pointerFor} onClose={() => setPointerFor(null)} />}
{(hits.length > 0 || pinned.length > 0) && (
<Card>
<CardContent className="flex flex-col gap-3">
{rowError && <Notice kind="error">{rowError}</Notice>}
{freezeError && <Notice kind="warn">{freezeError}</Notice>}
<Table>
<TableHeader className="max-sm:hidden">
<TableRow>
<TableHead>Address</TableHead>
<TableHead>Value</TableHead>
<TableHead>Change to</TableHead>
<TableHead className="w-24 text-right">Freeze</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{pinned.map((f) => (
<HitRow
key={'p' + rowKey(f.address, f.kind)}
address={f.address}
kind={f.kind}
scanned={f.bytes}
current={f.bytes}
frozen
edit={edits.get(rowKey(f.address, f.kind)) ?? ''}
onEdit={(t) => setEdit(rowKey(f.address, f.kind), t)}
onSet={() => void writeValue(f.address, f.kind, edits.get(rowKey(f.address, f.kind)) ?? '')}
onFreeze={() => void toggleFreeze(f.address, f.bytes, f.kind)}
menu={rowMenu(f.address, f.kind, f.bytes)}
/>
))}
{hits.map((h) => {
// An Auto search mixes types, so each row says which one it is.
const rowKind = h.kind ?? kind;
const key = rowKey(h.address, rowKind);
const f = frozen.get(key);
const current = f ? f.bytes : (live.get(key) ?? h.value);
return (
<HitRow
key={key}
address={h.address}
kind={rowKind}
showKind={auto}
scanned={h.value}
current={current}
frozen={!!f}
edit={edits.get(key) ?? ''}
onEdit={(t) => setEdit(key, t)}
onSet={async () => {
const bytes = await writeValue(h.address, rowKind, edits.get(key) ?? '');
// A frozen row keeps being rewritten, so move the freeze to the new value.
if (bytes && f) setFrozen(new Map(frozen).set(key, { ...f, bytes }));
}}
onFreeze={() => void toggleFreeze(h.address, current, rowKind)}
menu={rowMenu(h.address, rowKind, current)}
/>
);
})}
</TableBody>
</Table>
</CardContent>
</Card>
)}
</div>
);
}
interface RowMenu {
onWrites: () => void;
onReads: () => void;
onMemory: () => void;
onSave: () => void;
onPointer: () => void;
}
function HitRow(props: {
menu: RowMenu;
address: bigint;
kind: ValueKind;
showKind?: boolean;
scanned: Uint8Array;
current: Uint8Array;
frozen: boolean;
edit: string;
onEdit: (text: string) => void;
onSet: () => void;
onFreeze: () => void;
}) {
const changed = !bytesEqual(props.scanned, props.current);
return (
// On phones each result is a two-line block: address and value, then the controls.
<TableRow className="max-sm:flex max-sm:flex-wrap max-sm:items-center max-sm:py-2">
<TableCell className="font-mono text-xs max-sm:basis-1/2 sm:text-sm">{fmtAddr(props.address)}</TableCell>
<TableCell className={cn('font-mono max-sm:basis-1/2 max-sm:text-right', changed && 'text-primary')}>
{decodeValue(props.kind, props.current)}
{props.showKind && <span className="ml-2 font-sans text-xs text-muted-foreground">{props.kind.label}</span>}
</TableCell>
<TableCell className="max-sm:min-w-0 max-sm:flex-1">
<div className="flex items-center gap-2">
<Input
className="h-8 min-w-0 font-mono sm:w-32"
inputMode="decimal"
aria-label={`New value for ${fmtAddr(props.address)}`}
value={props.edit}
onChange={(e) => props.onEdit(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') props.onSet();
}}
/>
<Button variant="outline" size="sm" disabled={props.edit.trim() === ''} onClick={props.onSet}>
Set
</Button>
</div>
</TableCell>
<TableCell className="text-right whitespace-nowrap max-sm:shrink-0">
<Button
variant={props.frozen ? 'default' : 'outline'}
size="icon-sm"
aria-pressed={props.frozen}
aria-label={props.frozen ? 'Unfreeze' : 'Freeze'}
title={props.frozen ? 'Unfreeze' : 'Freeze this value'}
onClick={props.onFreeze}
>
{props.frozen ? <LockIcon /> : <LockOpenIcon />}
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm" className="ml-1" aria-label={`More for ${fmtAddr(props.address)}`}>
<MoreHorizontalIcon />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onSelect={props.menu.onWrites}>Find what writes to this</DropdownMenuItem>
<DropdownMenuItem onSelect={props.menu.onReads}>Find what reads or writes this</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={props.menu.onSave}>Save to your cheats</DropdownMenuItem>
<DropdownMenuItem onSelect={props.menu.onPointer}>Make it survive restarts…</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={props.menu.onMemory}>Show in Memory</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
);
}
+89
View File
@@ -0,0 +1,89 @@
// Small shared pieces: the ghost, the pellet progress track, notices.
import type { ReactNode } from 'react';
import { CircleAlertIcon, InfoIcon, TriangleAlertIcon } from 'lucide-react';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { cn } from '@/lib/utils';
export function Ghost(props: { size?: number; floaty?: boolean; look?: boolean; className?: string }) {
const size = props.size ?? 32;
return (
<svg
className={cn('block shrink-0 text-primary', props.floaty && 'ghost-float', props.look && 'ghost-look', props.className)}
width={size}
height={size}
viewBox="0 0 64 64"
aria-hidden="true"
>
<path fill="currentColor" d="M10 34C10 19 19.5 8 32 8s22 11 22 26v22l-7.3-6.5L39.3 56 32 49.5 24.7 56l-7.4-6.5L10 56Z" />
<ellipse cx="24" cy="30" rx="5.5" ry="6.5" fill="#fff" />
<ellipse cx="40" cy="30" rx="5.5" ry="6.5" fill="#fff" />
<g className="ghost-pupils">
<circle cx="26.5" cy="31" r="3" fill="#0a0a0a" />
<circle cx="42.5" cy="31" r="3" fill="#0a0a0a" />
</g>
</svg>
);
}
export function Wordmark() {
return (
<div className="mr-auto flex min-w-0 items-center gap-2.5">
<Ghost size={30} look />
<h1 className="text-xl font-bold tracking-tight">
Cheat<span className="text-primary">Specter</span>
</h1>
</div>
);
}
const PELLETS = 22;
/** Progress as a ghost eating its way along a row of pellets. `fraction` null = unknown. */
export function PelletTrack(props: { fraction: number | null; label: string }) {
const known = props.fraction !== null;
const f = known ? Math.max(0, Math.min(1, props.fraction as number)) : 0;
const eaten = Math.floor(f * PELLETS);
return (
<div
className={cn('relative my-1 h-[34px]', !known && 'pellet-track-indeterminate')}
role="progressbar"
aria-label={props.label}
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={known ? Math.round(f * 100) : undefined}
>
<div className="absolute inset-x-3.5 inset-y-0 flex items-center justify-between">
{Array.from({ length: PELLETS }, (_, i) => (
<i key={i} className={cn('size-1.5 rounded-full bg-primary transition-opacity', known && i < eaten && 'opacity-15')} />
))}
</div>
<div className="pellet-runner absolute top-[3px]" style={known ? { left: `calc(${f * 100}% - ${f * 28}px)` } : undefined}>
<Ghost size={28} />
</div>
</div>
);
}
export function Notice(props: { kind?: 'error' | 'warn' | 'info'; children: ReactNode; className?: string }) {
const kind = props.kind ?? 'info';
const Icon = kind === 'error' ? CircleAlertIcon : kind === 'warn' ? TriangleAlertIcon : InfoIcon;
return (
<Alert
variant={kind === 'error' ? 'destructive' : 'default'}
role={kind === 'error' ? 'alert' : 'status'}
className={cn(
kind === 'error' && 'border-destructive/50',
kind === 'warn' && 'border-primary/40 [&>svg]:text-primary',
props.className,
)}
>
<Icon />
<AlertDescription className={cn(kind !== 'error' && 'text-foreground/90')}>{props.children}</AlertDescription>
</Alert>
);
}
export function errorText(e: unknown): string {
return e instanceof Error ? e.message : String(e);
}
+337
View File
@@ -0,0 +1,337 @@
// State shared by every tab while one game is running: the game context, the
// user's own cheat table and the runner that applies it, plus "go and show
// this address" navigation between tabs.
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import { createGameContext } from '../lib/locations.ts';
import type { GameContext } from '../lib/locations.ts';
import { startScript } from '../lib/script.ts';
import type { Game, Session } from '../lib/session.ts';
import { TableRunner, loadOwnTable, saveOwnTable } from '../lib/table.ts';
import { Ps5StorageUnavailable, fileVersion, listPs5Tables, loadPs5Table, pickVersion, savePs5Table } from '../lib/tablestore.ts';
import type { Entry, OwnTable } from '../lib/table.ts';
import { x86 } from '../lib/x86client.ts';
import { errorText } from './bits.tsx';
export type TabId = 'cheats' | 'find' | 'memory' | 'code';
export interface TraceRequest {
address: bigint;
size: 1 | 2 | 4 | 8;
kind: 'write' | 'readwrite';
/** Changes with every request so the same address can be traced twice. */
nonce: number;
}
export interface Workbench {
session: Session;
game: Game;
ctx: GameContext;
runner: TableRunner;
table: OwnTable;
/** Entry id -> last error from switching it. */
errors: Record<string, string>;
/** Entry id -> output lines (scripts). */
logs: Record<string, string[]>;
/** Entry id currently being switched. */
busy: string | null;
/** True when the browser refused to keep its working copy of the table. */
saveFailed: boolean;
/** Where the table stands with its file on the console. */
ps5: Ps5Save;
/** Writes the table to the console now, and keeps that file up to date from then on. */
saveToPs5: () => Promise<void>;
/** The table as it should be written to a file: current game version, and the game's name. */
fileTable: () => OwnTable;
setTable: (update: (t: OwnTable) => OwnTable) => void;
/** Adds an entry and, unless told otherwise, switches it on. */
addEntry: (entry: Entry, opts?: { enable?: boolean }) => Promise<void>;
toggle: (entry: Entry, on: boolean, force?: boolean) => Promise<void>;
removeEntry: (entry: Entry) => Promise<void>;
tab: TabId;
setTab: (tab: TabId) => void;
memoryAt: bigint | null;
codeAt: bigint | null;
trace: TraceRequest | null;
showMemory: (address: bigint) => void;
showCode: (address: bigint) => void;
startTrace: (address: bigint, size: 1 | 2 | 4 | 8, kind: 'write' | 'readwrite') => void;
/** Entry being edited in the editor dialog (a draft, or an existing entry). */
editing: { entry: Entry; isNew: boolean } | null;
edit: (entry: Entry, isNew: boolean) => void;
closeEditor: () => void;
}
export interface Ps5Save {
/**
* checking: looking for a saved file. unavailable: the payload is not on the console.
* none: nothing saved for this game version. saved / saving / failed: a file exists and is kept in step.
*/
status: 'checking' | 'unavailable' | 'none' | 'saved' | 'saving' | 'failed';
/** The folder on the console. */
folder: string;
/** Set when the cheats shown were loaded from a file saved for another game version. */
loadedFrom?: string;
error?: string;
}
function errorMessage(e: unknown): string {
return e instanceof Error ? e.message : String(e);
}
/** Edits are written to the console this long after the last one. */
const PS5_SAVE_DELAY_MS = 600;
const Ctx = createContext<Workbench | null>(null);
export function useWorkbench(): Workbench {
const wb = useContext(Ctx);
if (!wb) throw new Error('useWorkbench outside its provider');
return wb;
}
export function WorkbenchProvider(props: { session: Session; game: Game; gameName: string; children: ReactNode }) {
const { session, game } = props;
const gameNameRef = useRef(props.gameName);
gameNameRef.current = props.gameName;
const [table, setTableState] = useState<OwnTable>(() => loadOwnTable(game.titleId, game.version));
const [, setVersion] = useState(0);
const bump = useCallback(() => setVersion((v) => v + 1), []);
const [errors, setErrors] = useState<Record<string, string>>({});
const [logs, setLogs] = useState<Record<string, string[]>>({});
const [busy, setBusy] = useState<string | null>(null);
const [saveFailed, setSaveFailed] = useState(false);
const [tab, setTab] = useState<TabId>('cheats');
const [memoryAt, setMemoryAt] = useState<bigint | null>(null);
const [codeAt, setCodeAt] = useState<bigint | null>(null);
const [trace, setTrace] = useState<TraceRequest | null>(null);
const [editing, setEditing] = useState<{ entry: Entry; isNew: boolean } | null>(null);
const tableRef = useRef(table);
tableRef.current = table;
const ctx = useMemo(
() =>
createGameContext({
pid: game.pid,
dbg: () => session.main,
scanDbg: () => session.scan,
x86,
// The console drops a connection after an assembler error, so each
// assembly gets its own and a typo cannot take the main one with it.
assemble: async (base, text) => {
const dbg = await session.openDebugger();
try {
return await dbg.assemble(base, text);
} finally {
if (!dbg.closed) dbg.close();
}
},
}),
[session, game.pid],
);
const runnerRef = useRef<TableRunner | null>(null);
const runner = useMemo(() => {
const r: TableRunner = new TableRunner(ctx, {
onLog: (id, line) => setLogs((prev) => ({ ...prev, [id]: [...(prev[id] ?? []).slice(-199), line] })),
startScript: (entry, log) =>
startScript(
ctx,
{
setEntry: async (name, on) => {
const target = tableRef.current.entries.find((e) => e.name === name);
if (!target) throw new Error(`There is no entry called "${name}"`);
if (target.id === entry.id) throw new Error('A script cannot switch itself');
if (target.unreviewed) throw new Error(`"${name}" has not been reviewed yet`);
if (on) await r.enable(target);
else await r.disable(target);
bump();
},
},
entry.code,
log,
(error) => {
r.scriptEnded(entry.id);
log(error ? `Stopped with an error: ${error}` : 'Finished.');
bump();
},
),
});
runnerRef.current = r;
return r;
}, [ctx, bump]);
useEffect(() => () => runner.dispose(), [runner]);
// ---- the file on the console ----
const [ps5, setPs5] = useState<Ps5Save>({ status: 'checking', folder: '' });
/** A file for this game version exists on the console, so edits go to it. */
const linked = useRef(false);
/** The user has changed or switched something, so a late-arriving file must not replace it. */
const touched = useRef(false);
const saveTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const fileTable = useCallback((): OwnTable => {
const t = tableRef.current;
return { ...t, titleId: game.titleId, version: game.version, name: t.name || gameNameRef.current };
}, [game.titleId, game.version]);
const writeToPs5 = useCallback(async () => {
clearTimeout(saveTimer.current);
saveTimer.current = undefined;
setPs5((p) => ({ ...p, status: 'saving', error: undefined }));
try {
await savePs5Table(session.target, fileTable());
linked.current = true;
setPs5((p) => ({ folder: p.folder, status: 'saved' }));
} catch (e) {
if (e instanceof Ps5StorageUnavailable) {
linked.current = false;
setPs5((p) => ({ folder: p.folder, status: 'unavailable' }));
} else {
setPs5((p) => ({ ...p, status: 'failed', error: errorMessage(e) }));
}
throw e;
}
}, [session, fileTable]);
// On start: look in the console's cheats folder and load what is saved for this game.
useEffect(() => {
let cancelled = false;
(async () => {
try {
const found = await listPs5Tables(session.target, game.titleId);
if (cancelled) return;
const version = pickVersion(found.versions, game.version);
const saved = version ? await loadPs5Table(session.target, game.titleId, version) : null;
if (cancelled) return;
if (!saved || !version) {
setPs5({ status: 'none', folder: found.folder });
return;
}
const exact = version === fileVersion(game.version);
if (touched.current) {
// The user got there first; their edits stand, and go to the file if it is this version's.
linked.current = exact;
setPs5({ status: exact ? 'saved' : 'none', folder: found.folder });
if (exact) void writeToPs5().catch(() => {});
return;
}
linked.current = exact;
const next: OwnTable = { ...saved, titleId: game.titleId };
setTableState(next);
saveOwnTable(next);
setPs5({ status: exact ? 'saved' : 'none', folder: found.folder, loadedFrom: exact ? undefined : version });
} catch (e) {
if (cancelled) return;
setPs5(e instanceof Ps5StorageUnavailable ? { status: 'unavailable', folder: '' } : { status: 'failed', folder: '', error: errorMessage(e) });
}
})();
return () => {
cancelled = true;
// An edit still waiting to be written goes out now rather than being lost.
if (saveTimer.current !== undefined) void writeToPs5().catch(() => {});
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [session, game.titleId, game.version]);
const setTable = useCallback(
(update: (t: OwnTable) => OwnTable) => {
touched.current = true;
setTableState((prev) => {
const next = update(prev);
tableRef.current = next;
setSaveFailed(!saveOwnTable(next));
return next;
});
if (linked.current) {
clearTimeout(saveTimer.current);
saveTimer.current = setTimeout(() => void writeToPs5().catch(() => {}), PS5_SAVE_DELAY_MS);
}
},
[writeToPs5],
);
const toggle = useCallback(
async (entry: Entry, on: boolean, force = false) => {
touched.current = true;
setBusy(entry.id);
setErrors((prev) => {
const { [entry.id]: _gone, ...rest } = prev;
return rest;
});
try {
if (on) {
if (entry.type === 'script') setLogs((prev) => ({ ...prev, [entry.id]: [] }));
await runner.enable(entry, { force });
} else await runner.disable(entry);
} catch (e) {
setErrors((prev) => ({ ...prev, [entry.id]: errorText(e) }));
} finally {
setBusy(null);
bump();
}
},
[runner, bump],
);
const addEntry = useCallback(
async (entry: Entry, opts: { enable?: boolean } = {}) => {
setTable((t) => ({ ...t, entries: [...t.entries, entry] }));
if (opts.enable !== false && !entry.unreviewed) await toggle(entry, true);
},
[setTable, toggle],
);
const removeEntry = useCallback(
async (entry: Entry) => {
// Undo it first; a deleted switch that is still on could never be turned off.
await runner.disable(entry).catch(() => undefined);
setTable((t) => ({ ...t, entries: t.entries.filter((e) => e.id !== entry.id) }));
},
[runner, setTable],
);
const value: Workbench = {
session,
game,
ctx,
runner,
table,
errors,
logs,
busy,
saveFailed,
ps5,
saveToPs5: writeToPs5,
fileTable,
setTable,
addEntry,
toggle,
removeEntry,
tab,
setTab,
memoryAt,
codeAt,
trace,
showMemory: (address) => {
setMemoryAt(address);
setTab('memory');
},
showCode: (address) => {
setCodeAt(address);
setTab('code');
},
startTrace: (address, size, kind) => {
setTrace({ address, size, kind, nonce: Date.now() });
setTab('code');
},
editing,
edit: (entry, isNew) => setEditing({ entry, isNew }),
closeEditor: () => setEditing(null),
};
return <Ctx.Provider value={value}>{props.children}</Ctx.Provider>;
}
+121
View File
@@ -0,0 +1,121 @@
// The community cheat formats: JSON, SHN (XML) and MC4 (encrypted XML), and
// how the three repositories' index files are read.
import test from 'node:test';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import { ONLINE_SOURCES, parseIndexLine } from '../src/lib/catalog.ts';
import { aesCbcDecrypt, decodeMc4, decodeText, parseAnyTable, parseTrainerXml } from '../src/lib/trainer.ts';
import { bytesToHex } from '../src/lib/bytes.ts';
const XML = `<?xml version="1.0" encoding="utf-8"?>
<Trainer xmlns:xsd="http://w3.org" Game="Harbor &amp; Lights" Moder="Somebody" Cusa="PPSA07391" Version="01.009.000" Process="eboot.bin">
<Genres Name="Action"/>
<Cheat Text="Infinite Health">
<Cheatline><Offset>26CD7A8</Offset><Section>0</Section><ValueOn>E9-26-27-7A-01-90</ValueOn><ValueOff>C4-81-7A-11-04-27</ValueOff></Cheatline>
<Cheatline>
<Offset>3E6FED3</Offset>
<Section>0</Section>
<ValueOn>40-F6-C7-02</ValueOn>
<ValueOff>00-00-00-00</ValueOff>
</Cheatline>
</Cheat>
<Cheat Text="Needs a master code"><Cheatline><Offset>10</Offset><Section>14</Section><ValueOn>01</ValueOn><ValueOff>00</ValueOff></Cheatline></Cheat>
<Cheat Text="Fixed address"><Cheatline><Absolute>True</Absolute><Offset>400000</Offset><Section>0</Section><ValueOn>01</ValueOn><ValueOff>00</ValueOff></Cheatline></Cheat>
<Cheat Text="Only a name">
</Cheat>
</Trainer>`;
const KEY = Buffer.from('304c6528f659c766110239a51cl5dd9c');
const IV = Buffer.from('u@}kzW2u[u(8DWar');
const toMc4 = (text) => {
const c = crypto.createCipheriv('aes-256-cbc', KEY, IV);
return Buffer.concat([c.update(Buffer.from(text, 'utf8')), c.final()]).toString('base64');
};
test('AES decryption agrees with a known implementation', () => {
for (const size of [1, 15, 16, 17, 100, 4096]) {
const plain = crypto.randomBytes(size);
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
const c = crypto.createCipheriv('aes-256-cbc', key, iv);
const sealed = Buffer.concat([c.update(plain), c.final()]);
assert.equal(Buffer.from(aesCbcDecrypt(key, iv, sealed)).toString('hex'), plain.toString('hex'));
}
assert.throws(() => aesCbcDecrypt(KEY, IV, new Uint8Array(15)), /whole number of blocks/);
});
test('reads an SHN table', () => {
const t = parseTrainerXml(XML);
assert.equal(t.name, 'Harbor & Lights');
assert.equal(t.titleId, 'PPSA07391');
assert.equal(t.version, '01.009.000');
assert.deepEqual(t.credits, ['Somebody']);
assert.deepEqual(t.mods.map((m) => [m.name, m.patches.length, m.unsupported]), [
['Infinite Health', 2, null],
['Needs a master code', 0, 'Depends on a master code'],
['Fixed address', 0, 'Uses a fixed memory address'],
['Only a name', 0, 'Has no patches'],
]);
const [first, second] = t.mods[0].patches;
assert.equal(first.offset, 0x26cd7a8n);
assert.equal(bytesToHex(first.on).toLowerCase(), 'e926277a0190');
assert.equal(bytesToHex(first.off).toLowerCase(), 'c4817a110427');
assert.equal(second.offset, 0x3e6fed3n);
});
test('reads an MC4 table, including the escaped variant some tools wrote', () => {
assert.equal(decodeMc4(toMc4(XML)), XML);
assert.equal(parseAnyTable(toMc4(XML)).mods[0].patches.length, 2);
const escaped = XML.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '\\&quot;');
const t = parseAnyTable(toMc4(escaped));
assert.equal(t.titleId, 'PPSA07391');
assert.equal(t.mods[0].patches.length, 2);
assert.throws(() => parseAnyTable('bm90IGEgdGFibGUgYXQgYWxsIGJ1dCBsb25nIGVub3VnaA=='), /could not be decoded/);
});
test('tells the formats apart by content, whatever the file is called', () => {
const json = JSON.stringify({ name: 'G', id: 'ppsa07391', version: '01.009.000', mods: [{ name: 'A', type: 'checkbox', memory: [{ offset: '10', on: '90', off: '00' }] }] });
assert.equal(parseAnyTable(json).titleId, 'PPSA07391');
assert.equal(parseAnyTable('' + XML).titleId, 'PPSA07391');
assert.equal(parseAnyTable('?' + XML).titleId, 'PPSA07391', 'a mangled byte-order mark ahead of the XML');
assert.throws(() => parseAnyTable('hello there'), /not a cheat table/);
});
test('decodes UTF-16 files', () => {
const le = Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(XML, 'utf16le')]);
assert.equal(parseAnyTable(decodeText(le)).name, 'Harbor & Lights');
assert.equal(parseAnyTable(decodeText(Buffer.from(XML, 'utf16le'))).name, 'Harbor & Lights', 'without a byte-order mark');
assert.equal(decodeText(Buffer.from('plain', 'utf8')), 'plain');
});
test('index lines from all three repositories', () => {
assert.deepEqual(parseIndexLine('PPSA11386_01.018.000_86df452e.mc4=007 First Light'), {
file: 'PPSA11386_01.018.000_86df452e.mc4',
titleId: 'PPSA11386',
version: '01.018.000',
gameName: '007 First Light',
format: 'mc4',
});
assert.equal(parseIndexLine('CUSA07713_15.21.shn=Monster Hunter World Iceborne').format, 'shn');
assert.equal(parseIndexLine('CUSA02882_01.00_bh1hd.elf_2.json=Resident Evil Origins Collection').version, '01.00');
// The .mc4.xml files only list names; the cheats are in the .mc4 next to them.
assert.equal(parseIndexLine('CUSA27430_01.19.mc4.xml=Skul The Hero Slayer').file, 'CUSA27430_01.19.mc4');
// An index that repeats the file name instead of naming the game.
assert.equal(parseIndexLine('PPSA02474_01.000.500.mc4=PPSA02474_01.000.500').gameName, '');
assert.equal(parseIndexLine('README.md'), null);
assert.equal(parseIndexLine('CUSA00002_01.00.elf=x'), null);
});
test('the three community repositories are the sources', () => {
assert.deepEqual(ONLINE_SOURCES.map((s) => s.home), [
'https://github.com/etaHEN/PS5_Cheats',
'https://github.com/GoldHEN/GoldHEN_Cheat_Repository',
'https://github.com/TeeKay87/HEN-Cheats-Collection',
]);
const urls = ONLINE_SOURCES.flatMap((s) => s.indexes.map((i) => i.indexUrl));
assert.ok(urls.includes('https://raw.githubusercontent.com/TeeKay87/HEN-Cheats-Collection/master/cheats/mc4.txt'));
assert.ok(urls.includes('https://raw.githubusercontent.com/GoldHEN/GoldHEN_Cheat_Repository/main/shn.txt'));
assert.ok(urls.every((u) => u.startsWith('https://raw.githubusercontent.com/')));
});
+155
View File
@@ -0,0 +1,155 @@
// Game metadata parsing, the .cspecter file format, and the bridge's
// pass-through to the payload on the console.
import test from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import { startBridge } from '../bridge/server.mjs';
import { buildParamJson, buildSfo } from '../bridge/demo-library.mjs';
import { formatSize, parseParamJson, parseParamSfo, parseSfo } from '../src/lib/library.ts';
import { emptyTable, exportOwnTable, isOwnTableText, parseOwnTable, saveFileText } from '../src/lib/table.ts';
import { fileVersion, pickVersion, tableFileName } from '../src/lib/tablestore.ts';
test('reads a PS5 game name in the game\'s default language', () => {
assert.deepEqual(parseParamJson(buildParamJson('PPSA07391', 'Harbor Lights', '01.009.000')), {
name: 'Harbor Lights',
version: '01.009.000',
platform: 'PS5',
});
const multi = JSON.stringify({
localizedParameters: { defaultLanguage: 'ja-JP', 'en-US': { titleName: 'English' }, 'ja-JP': { titleName: '日本語' } },
});
assert.equal(parseParamJson(multi).name, '日本語');
const noDefault = JSON.stringify({ localizedParameters: { 'fr-FR': { titleName: 'Français' } } });
assert.equal(parseParamJson(noDefault).name, 'Français');
assert.equal(parseParamJson('{"localizedParameters":{}}'), null);
assert.equal(parseParamJson('not json'), null);
assert.equal(parseParamJson('[]'), null);
});
test('reads a PS4 param.sfo and survives damaged ones', () => {
const sfo = buildSfo({ TITLE: 'Old Favourite ™', TITLE_ID: 'CUSA12345', APP_VER: '01.07', PARENTAL_LEVEL: 5 });
assert.deepEqual(parseSfo(sfo), { APP_VER: '01.07', PARENTAL_LEVEL: 5, TITLE: 'Old Favourite ™', TITLE_ID: 'CUSA12345' });
assert.deepEqual(parseParamSfo(sfo), { name: 'Old Favourite ™', version: '01.07', platform: 'PS4' });
assert.equal(parseParamSfo(new Uint8Array(4)), null);
assert.equal(parseParamSfo(new TextEncoder().encode('{"this":"is json, not an sfo"}')), null);
for (let cut = 0; cut < sfo.length; cut += 7) assert.doesNotThrow(() => parseParamSfo(sfo.subarray(0, cut)));
const lying = sfo.slice();
new DataView(lying.buffer).setUint32(16, 0xffffffff, true); // claims four billion entries
assert.equal(parseParamSfo(lying), null);
});
test('sizes read the way a console shows them', () => {
assert.equal(formatSize(0), '');
assert.equal(formatSize(512), '512 B');
assert.equal(formatSize(1536), '1.5 KB');
assert.equal(formatSize(41.6 * 1024 ** 3), '41.6 GB');
assert.equal(formatSize(150 * 1024 ** 3), '150 GB');
});
const sample = () => {
const t = emptyTable('PPSA07391', '01.009.000', 'Harbor Lights');
t.entries.push({ id: 'a', name: 'Infinite ammo', type: 'patch', at: { kind: 'module', offset: '0x2040' }, on: '909090', off: 'FF4B28', note: '' });
t.entries.push({ id: 'b', name: 'Give gold', type: 'call', fn: { kind: 'module', offset: '0x4100' }, args: [] });
t.entries.push({ id: 'c', name: 'Looked at', type: 'script', code: 'await cs.sleep(1);' });
t.entries.push({ id: 'd', name: 'Not looked at', type: 'script', code: 'await cs.sleep(1);', unreviewed: true });
t.entries.push({ id: 'e', name: 'Session only', type: 'value', at: { kind: 'address', address: '0x880000000' }, valueType: 'u32', value: '1', freeze: false });
return t;
};
test('a .cspecter file is minified JSON with a proper header', () => {
const text = saveFileText(sample());
const doc = JSON.parse(text);
assert.deepEqual(Object.keys(doc), ['format', 'formatVersion', 'game', 'cheats']);
assert.equal(doc.format, 'cheatspecter');
assert.equal(doc.formatVersion, 1);
assert.deepEqual(doc.game, { name: 'Harbor Lights', titleId: 'PPSA07391', version: '01.009.000' });
// Nothing session-only, nothing empty.
assert.deepEqual(doc.cheats[0], { name: 'Infinite ammo', type: 'patch', at: { kind: 'module', offset: '0x2040' }, on: '909090', off: 'FF4B28' });
assert.deepEqual(doc.cheats[1], { name: 'Give gold', type: 'call', fn: { kind: 'module', offset: '0x4100' }, reviewed: true });
assert.equal(text, JSON.stringify(doc), 'written minified');
assert.deepEqual(parseOwnTable(JSON.stringify(doc, null, 2), { own: true }).entries.length, doc.cheats.length, 'a hand-formatted file still loads');
assert.ok(isOwnTableText(text));
});
test('a saved file comes back as it was; a shared one has to be reviewed', () => {
const own = parseOwnTable(saveFileText(sample()), { own: true });
assert.deepEqual(own.entries.map((e) => [e.name, e.unreviewed]), [
['Infinite ammo', undefined],
['Give gold', undefined],
['Looked at', undefined],
['Not looked at', true],
['Session only', undefined],
]);
assert.deepEqual(own.entries[1].args, []);
assert.equal(new Set(own.entries.map((e) => e.id)).size, 5);
// The same bytes arriving as someone else's file: "reviewed" in the file counts for nothing.
const foreign = parseOwnTable(saveFileText(sample()));
assert.deepEqual(foreign.entries.filter((e) => e.unreviewed).map((e) => e.name), ['Give gold', 'Looked at', 'Not looked at']);
const shared = JSON.parse(exportOwnTable(sample()));
assert.deepEqual(shared.cheats.map((c) => c.name), ['Infinite ammo', 'Give gold', 'Looked at', 'Not looked at']);
assert.ok(shared.cheats.every((c) => !('reviewed' in c) && !('id' in c)));
});
test('older exports and newer formats are handled deliberately', () => {
const legacy = JSON.stringify({ format: 'cheatspecter/1', titleId: 'ppsa07391', version: '01.000.000', name: 'Old', entries: sample().entries });
const t = parseOwnTable(legacy);
assert.equal(t.titleId, 'PPSA07391');
assert.equal(t.entries.length, 5);
assert.throws(() => parseOwnTable(JSON.stringify({ format: 'cheatspecter', formatVersion: 2, game: {}, cheats: [] })), /newer CheatSpecter/);
assert.throws(() => parseOwnTable(JSON.stringify({ format: 'cheatspecter', formatVersion: 1, game: {} })), /no cheats/);
});
test('file names carry the title ID and game version', () => {
assert.equal(tableFileName('PPSA18605', '01.009.000'), 'PPSA18605-01.009.000.cspecter');
assert.equal(tableFileName('PPSA18605', ''), 'PPSA18605-unknown.cspecter');
assert.equal(fileVersion('../../etc'), 'etc');
assert.equal(pickVersion(['01.002.000', '01.010.000', '01.009.000'], '01.009.000'), '01.009.000');
assert.equal(pickVersion(['01.002.000', '01.010.000', '01.009.000'], '01.011.000'), '01.010.000');
assert.equal(pickVersion([], '01.000.000'), null);
});
test('the bridge passes library and cheat-file requests on to the console, and only those', async () => {
// Stands in for the payload on a console.
const seen = [];
const payload = http.createServer((req, res) => {
const chunks = [];
req.on('data', (c) => chunks.push(c));
req.on('end', () => {
seen.push(`${req.method} ${req.url} ${Buffer.concat(chunks).toString()}`.trim());
res.writeHead(req.method === 'PUT' ? 204 : 200, { 'content-type': 'application/json' });
res.end(req.method === 'PUT' ? undefined : '{"titles":[]}');
});
});
await new Promise((r) => payload.listen(0, '127.0.0.1', r));
const bridge = startBridge({ port: 0, host: '127.0.0.1', eventPort: null, payloadPort: payload.address().port });
await bridge.ready;
const base = `http://127.0.0.1:${bridge.server.address().port}`;
try {
assert.deepEqual(await (await fetch(`${base}/api/library?host=127.0.0.1`)).json(), { titles: [] });
assert.equal((await fetch(`${base}/api/tables/PPSA07391/01.009.000?host=127.0.0.1`, { method: 'PUT', body: 'hello' })).status, 204);
assert.equal((await fetch(`${base}/api/launch/PPSA07391?host=127.0.0.1`, { method: 'POST' })).status, 200);
assert.deepEqual(seen, ['GET /api/library', 'PUT /api/tables/PPSA07391/01.009.000 hello', 'POST /api/launch/PPSA07391']);
// Not a console on the local network, not a path the payload has, not this page's origin.
assert.equal((await fetch(`${base}/api/library?host=example.com`)).status, 400);
assert.equal((await fetch(`${base}/api/library?host=8.8.8.8`)).status, 400);
assert.equal((await fetch(`${base}/api/appmeta/PPSA07391/..%2F..%2Fetc?host=127.0.0.1`)).status, 400);
assert.equal((await fetch(`${base}/api/launch/PPSA07391?host=127.0.0.1`)).status, 405);
const foreign = await fetch(`${base}/api/launch/PPSA07391?host=127.0.0.1`, { method: 'POST', headers: { origin: 'http://evil.example' } });
assert.equal(foreign.status, 403);
assert.equal(seen.length, 3);
// No payload on that console.
payload.close();
payload.closeAllConnections();
const gone = await fetch(`${base}/api/library?host=127.0.0.1`);
assert.equal(gone.status, 502);
} finally {
await bridge.close();
payload.close();
}
});
+181
View File
@@ -0,0 +1,181 @@
// The MCP server, built as it ships and driven over stdin/stdout, against the
// on-console payload (built for this computer) and the mock console.
// Skipped when there is no C compiler or the web app is not built.
import test, { after, before } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import net from 'node:net';
import os from 'node:os';
import path from 'node:path';
import readline from 'node:readline';
import { execFileSync, spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { startMock, GAME } from '../mock/mock-ps5.mjs';
import { buildParamJson } from '../bridge/demo-library.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const BIN = path.join(ROOT, 'payload/build/cheatspecter-host');
const PORT = 18944;
const MOCK = 17650;
const EVENTS = 17966;
const FAKE_ROOT = fs.mkdtempSync(path.join(os.tmpdir(), 'cs-mcp-'));
let skip = false;
try {
if (!fs.existsSync(path.join(ROOT, 'dist/index.html'))) throw new Error('dist missing');
execFileSync(process.execPath, [path.join(ROOT, 'scripts/build-payload.mjs'), 'host'], { stdio: 'pipe' });
execFileSync(process.execPath, [path.join(ROOT, 'scripts/build-mcp.mjs')], { stdio: 'pipe' });
} catch {
skip = 'needs a C compiler and a built web app (npm run build)';
}
const meta = path.join(FAKE_ROOT, `system_data/priv/appmeta/${GAME.titleId}`);
fs.mkdirSync(meta, { recursive: true });
fs.writeFileSync(path.join(meta, 'param.json'), buildParamJson(GAME.titleId, 'Specter Run', GAME.version));
fs.mkdirSync(path.join(FAKE_ROOT, `user/app/${GAME.titleId}`), { recursive: true });
fs.writeFileSync(path.join(FAKE_ROOT, `user/app/${GAME.titleId}/app.pkg`), Buffer.alloc(2048));
let mock, payload, server, nextId = 1;
const waiting = new Map();
const rpc = (method, params) =>
new Promise((resolve, reject) => {
const id = nextId++;
waiting.set(id, { resolve, reject });
server.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
});
/** Calls a tool and returns its text; throws if the tool reported an error. */
const call = async (name, args = {}) => {
const res = await rpc('tools/call', { name, arguments: args });
const text = res.content.map((c) => c.text).join('\n');
if (res.isError) throw new Error(text);
return text;
};
before(async () => {
if (skip) return;
mock = startMock({ tcpPort: MOCK, udpPort: 0, tick: false, eventPort: EVENTS });
await mock.ready;
payload = spawn(BIN, [], { env: { ...process.env, CS_PORT: String(PORT), CS_DEBUGGER_PORT: String(MOCK), CS_EVENT_PORT: String(EVENTS), CS_ROOT: FAKE_ROOT }, stdio: 'ignore' });
for (let i = 0; ; i++) {
const ok = await new Promise((resolve) => {
const s = net.connect(PORT, '127.0.0.1');
s.once('connect', () => (s.destroy(), resolve(true)));
s.once('error', () => resolve(false));
});
if (ok) break;
if (i > 100) throw new Error('payload did not start');
await new Promise((r) => setTimeout(r, 30));
}
server = spawn(process.execPath, [path.join(ROOT, 'mcp/build/server/index.mjs')], {
env: { ...process.env, CHEATSPECTER_HOST: '', CHEATSPECTER_PORT: String(PORT) },
stdio: ['pipe', 'pipe', 'ignore'],
});
readline.createInterface({ input: server.stdout }).on('line', (line) => {
const msg = JSON.parse(line);
const w = waiting.get(msg.id);
if (!w) return;
waiting.delete(msg.id);
if (msg.error) w.reject(new Error(msg.error.message));
else w.resolve(msg.result);
});
});
after(async () => {
if (server) server.kill();
if (payload) payload.kill();
if (mock) await mock.close();
fs.rmSync(FAKE_ROOT, { recursive: true, force: true });
});
test('speaks the protocol and lists its tools', { skip }, async () => {
const init = await rpc('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '0' } });
assert.equal(init.protocolVersion, '2025-06-18');
assert.equal(init.serverInfo.name, 'cheatspecter');
server.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');
assert.deepEqual(await rpc('ping'), {});
const { tools } = await rpc('tools/list');
assert.ok(tools.length >= 15);
for (const t of tools) {
assert.match(t.name, /^[a-z_]+$/);
assert.ok(t.description.length > 20);
assert.equal(t.inputSchema.type, 'object');
}
await assert.rejects(rpc('no/such'), /Method not found/);
// The packaged manifest lists the same tools.
const manifest = JSON.parse(fs.readFileSync(path.join(ROOT, 'mcp/build/manifest.json'), 'utf8'));
assert.deepEqual(manifest.tools.map((t) => t.name), tools.map((t) => t.name));
});
test('explains what to do before a console address is set, then connects', { skip }, async () => {
await assert.rejects(call('list_games'), /No PS5 address is set/);
const status = await call('console_status', { host: '127.0.0.1' });
assert.match(status, /Running: Specter Run \(PPSA99999, version 01\.000\.000, pid 91\)/);
assert.match(status, /No cheats saved/);
assert.match(await call('list_games'), /PPSA99999 {2}PS5 +2\.0 KB {2}Specter Run/);
assert.match(await call('list_modules'), /eboot\.bin|executable/);
});
test('reads, writes and searches memory', { skip }, async () => {
const ammo = '0x' + (GAME.heapBase + BigInt(GAME.vars.ammo)).toString(16);
assert.match(await call('read_memory', { address: ammo, as: 'u32' }), / 30$/);
assert.match(await call('read_memory', { address: 'game+0x2040', length: 3 }), /FF 4B 28/);
assert.match(await call('write_memory', { address: ammo, value: '4242', type: 'u32' }), /now 92 10 00 00$/);
const first = await call('scan_start', { type: 'auto', value: '4242' });
assert.match(first, /matches after pass 1/);
assert.match(first, new RegExp(`${ammo.toUpperCase().replace('0X', '0x')} 4242 \\(u32\\)`));
await call('write_memory', { address: ammo, value: '4200', type: 'u32' });
const second = await call('scan_next', { compare: 'exact', value: '4200' });
assert.match(second, /^1 matches after pass 2/);
assert.match(await call('scan_status'), /was 4200 now 4200/);
await assert.rejects(call('scan_start', { type: 'u32', value: 'abc' }), /not a whole number/);
await call('write_memory', { address: ammo, value: '30', type: 'u32' });
});
test('finds code, disassembles it, and turns it into a saved switch', { skip }, async () => {
const found = await call('find_pattern', { pattern: 'FF 4B 28' });
assert.match(found, /\+0x2040\) unique/);
const listing = await call('disassemble', { address: 'game+0x2040', count: 1 });
assert.match(listing, /dec dword ptr \[rbx\+0x28\]/);
await assert.rejects(call('add_cheat', { cheat: { name: 'Nonsense', type: 'teleport' } }), /not a cheat CheatSpecter understands/);
const saved = await call('add_cheat', {
cheat: { name: 'Infinite ammo', type: 'patch', note: 'Shots are free.', at: { kind: 'signature', pattern: 'FF 4B 28', offset: 0 }, on: '909090', off: 'FF4B28' },
});
assert.match(saved, /Saved "Infinite ammo"/);
// It is the same file the web app loads.
const file = path.join(FAKE_ROOT, 'data/cheatspecter/cheats/PPSA99999-01.000.000.cspecter');
const doc = JSON.parse(fs.readFileSync(file, 'utf8'));
assert.equal(doc.format, 'cheatspecter');
assert.equal(doc.game.name, 'Specter Run');
assert.equal(doc.cheats[0].name, 'Infinite ammo');
assert.match(await call('list_cheats'), /\[off\] Infinite ammo: Patch at/);
assert.equal(await call('set_cheat', { name: 'Infinite ammo', on: true }), '"Infinite ammo" is on.');
assert.match(await call('read_memory', { address: 'game+0x2040', length: 3 }), /90 90 90/);
assert.match(await call('list_cheats'), /\[ON\] Infinite ammo/);
assert.equal(await call('set_cheat', { name: 'infinite AMMO', on: false }), '"Infinite ammo" is off.');
assert.match(await call('read_memory', { address: 'game+0x2040', length: 3 }), /FF 4B 28/);
await call('add_cheat', { cheat: { name: 'Wrong build', type: 'patch', at: { kind: 'module', offset: '0x2040' }, on: '909090', off: 'AABBCC' } });
await assert.rejects(call('set_cheat', { name: 'Wrong build', on: true }), /does not match this version of the game/);
assert.equal(await call('remove_cheat', { name: 'Wrong build' }), 'Removed "Wrong build".');
await assert.rejects(call('set_cheat', { name: 'Wrong build', on: true }), /no cheat called/);
});
test('watches a value and names the instruction that writes it', { skip }, async () => {
const health = '0x' + (GAME.heapBase + BigInt(GAME.vars.health)).toString(16);
// The mock's game "runs" one step per tick; keep it ticking while the watch is armed.
const ticking = setInterval(() => mock.tick(), 60);
try {
const report = await call('watch', { address: health, size: 4, seconds: 4, max_hits: 3 });
assert.match(report, /hits from 1 place in the code/);
assert.match(report, /\+0x1000\) x\d/);
assert.match(report, /mov \[rcx\+0x390\], eax/);
assert.match(report, /rax=/);
} finally {
clearInterval(ticking);
}
});
+351
View File
@@ -0,0 +1,351 @@
// The on-console payload, built for this computer and pointed at the mock
// console. Skipped when there is no C compiler or the web app is not built.
import test, { after, before } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import net from 'node:net';
import os from 'node:os';
import path from 'node:path';
import { execFileSync, spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { startMock, GAME } from '../mock/mock-ps5.mjs';
import { buildParamJson, buildSfo } from '../bridge/demo-library.mjs';
import { parseParamJson, parseParamSfo } from '../src/lib/library.ts';
import { emptyTable, parseOwnTable, saveFileText } from '../src/lib/table.ts';
import { openWebSocketStream } from '../src/lib/transport.ts';
import { Ps5Debug } from '../src/lib/ps5debug.ts';
import { ScanSession, scannableRegions, valueKind, compareKind, encodeValue } from '../src/lib/scanner.ts';
import { hexToBytes } from '../src/lib/bytes.ts';
import { createRequire } from 'node:module';
import { createX86, asAsync } from '../src/lib/x86.ts';
import { createGameContext } from '../src/lib/locations.ts';
import { Tracer } from '../src/lib/tracer.ts';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const BIN = path.join(ROOT, 'payload/build/cheatspecter-host');
const PORT = 18744;
const MOCK = 17450;
const EVENTS = 17766;
let skip = false;
try {
if (!fs.existsSync(path.join(ROOT, 'dist/index.html'))) throw new Error('dist missing');
execFileSync(process.execPath, [path.join(ROOT, 'scripts/build-payload.mjs'), 'host'], { stdio: 'pipe' });
} catch {
skip = 'needs a C compiler and a built web app (npm run build)';
}
// A stand-in for the console's file system: two PS5 games, a PS4 game and a system app.
const FAKE_ROOT = fs.mkdtempSync(path.join(os.tmpdir(), 'cs-root-'));
const LAUNCH_LOG = path.join(FAKE_ROOT, 'launched.txt');
const put = (rel, data) => {
const file = path.join(FAKE_ROOT, rel);
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, data);
};
put('system_data/priv/appmeta/PPSA07391/param.json', buildParamJson('PPSA07391', 'Harbor Lights', '01.009.000'));
put('user/appmeta/PPSA07391/icon0.png', Buffer.from([0x89, 0x50, 0x4e, 0x47, 1, 2, 3]));
put('user/app/PPSA07391/app.pkg', Buffer.alloc(5000));
put('user/app/PPSA07391/sce_sys/extra.bin', Buffer.alloc(300));
put('user/patch/PPSA07391/patch.pkg', Buffer.alloc(700));
// The same installed files, also visible at a mount point: not to be counted twice.
put('system_ex/app/PPSA07391/app.pkg', Buffer.alloc(5000));
put('system_data/priv/appmeta/external/PPSA11111/param.json', buildParamJson('PPSA11111', 'On The Drive', '01.000.000'));
put('mnt/ext0/user/app/PPSA11111/app.pkg', Buffer.alloc(1234));
put('system_data/priv/appmeta/CUSA12345/param.sfo', buildSfo({ TITLE: 'Old Favourite', TITLE_ID: 'CUSA12345', APP_VER: '01.07' }));
put('system_data/priv/appmeta/NPXS40000/param.json', buildParamJson('NPXS40000', 'Settings', '01.000.000'));
put('system_data/priv/appmeta/secret.txt', 'not a title');
// A game kept elsewhere and mounted for the console: a small stub under /user/app, the real files under /system_ex/app.
put('user/appmeta/PPSA18605/param.json', buildParamJson('PPSA18605', 'Mounted Game', '01.001.008'));
put('user/app/PPSA18605/stub.bin', Buffer.alloc(40));
put('system_ex/app/PPSA18605/eboot.bin', Buffer.alloc(9000));
put('system_ex/app/PPSA18605/data/a/b/c/d/e/f/g/h/deep.pak', Buffer.alloc(1000));
// Games ShadowMount looks after: one is a disk image that is not mounted at the moment, one a folder that is.
put('user/appmeta/PPSA22222/param.json', buildParamJson('PPSA22222', 'Image Game', '01.000.000'));
put('user/app/PPSA22222/stub.bin', Buffer.alloc(10));
put('mnt/usb0/games/Image Game.ffpkg', Buffer.alloc(7777));
put('user/appmeta/PPSA33333/param.json', buildParamJson('PPSA33333', 'Folder Game', '01.000.000'));
put('data/homebrew/Folder Game/eboot.bin', Buffer.alloc(500));
put('system_ex/app/PPSA33333/eboot.bin', Buffer.alloc(500));
// What ShadowMount answers on its local port, slashes escaped the way its JSON library writes them.
const SHADOWMOUNT = 18745;
const shadowmount = http.createServer((req, res) => {
const games = [
{ path: '/mnt/usb0/games/Image Game.ffpkg', runtime_path: '/system_ex/app/PPSA22222', title_id: 'PPSA22222', title_name: 'Image {Game}', mounted: false },
{ path: '/data/homebrew/Folder Game', runtime_path: '/system_ex/app/PPSA33333', title_id: 'PPSA33333', mounted: true },
// An ordinary installed game, which ShadowMount lists with its install folder.
{ path: '/user/app/PPSA07391', runtime_path: '', title_id: 'PPSA07391', mounted: false },
{ path: '/mnt/usb1/unplugged', runtime_path: '', title_id: 'PPSA11111', mounted: false },
];
res.writeHead(req.method === 'POST' && req.url === '/api/v1/games' ? 200 : 404, { 'content-type': 'application/json' });
res.end(JSON.stringify({ status: 0, count: games.length, games }, null, 1).replace(/\//g, '\\/'));
});
const api = (p, init) => fetch(`http://127.0.0.1:${PORT}${p}`, init);
let mock, proc;
const waitForPort = async (port) => {
for (let i = 0; i < 100; i++) {
const ok = await new Promise((resolve) => {
const s = net.connect(port, '127.0.0.1');
s.once('connect', () => (s.destroy(), resolve(true)));
s.once('error', () => resolve(false));
});
if (ok) return;
await new Promise((r) => setTimeout(r, 30));
}
throw new Error('payload did not start');
};
const connect = async () => new Ps5Debug(await openWebSocketStream(`ws://127.0.0.1:${PORT}/ws`), { timeoutMs: 3000 });
before(async () => {
if (skip) return;
mock = startMock({ tcpPort: MOCK, udpPort: 0, tick: false, eventPort: EVENTS });
await mock.ready;
await new Promise((r) => shadowmount.listen(SHADOWMOUNT, '127.0.0.1', r));
proc = spawn(BIN, [], {
env: {
...process.env,
CS_PORT: String(PORT),
CS_DEBUGGER_PORT: String(MOCK),
CS_EVENT_PORT: String(EVENTS),
CS_ROOT: FAKE_ROOT,
CS_SHADOWMOUNT_PORT: String(SHADOWMOUNT),
CS_LAUNCH_LOG: LAUNCH_LOG,
},
stdio: 'ignore',
});
await waitForPort(PORT);
});
after(async () => {
if (proc) proc.kill();
shadowmount.close();
if (mock) await mock.close();
});
test('payload serves the app and says it is the console', { skip }, async () => {
const info = await (await fetch(`http://127.0.0.1:${PORT}/api/info`)).json();
assert.equal(info.mode, 'console');
assert.match(info.version, /^\d+\.\d+\.\d+$/);
const page = await fetch(`http://127.0.0.1:${PORT}/`);
assert.equal(page.status, 200);
assert.match(page.headers.get('content-type'), /text\/html/);
const html = await page.text(); // fetch undoes the gzip
assert.match(html, /<title>CheatSpecter<\/title>/);
// Every file index.html refers to is served intact.
for (const [, ref] of html.matchAll(/(?:src|href)="\.\/([^"]+)"/g)) {
const res = await fetch(`http://127.0.0.1:${PORT}/${ref}`);
assert.equal(res.status, 200, ref);
const body = Buffer.from(await res.arrayBuffer());
assert.deepEqual(body, fs.readFileSync(path.join(ROOT, 'dist', ref)), ref);
if (ref.startsWith('assets/')) assert.match(res.headers.get('cache-control'), /immutable/);
}
assert.equal((await fetch(`http://127.0.0.1:${PORT}/nope`)).status, 404);
assert.equal((await fetch(`http://127.0.0.1:${PORT}/../package.json`)).status, 404);
assert.equal((await fetch(`http://127.0.0.1:${PORT}/`, { method: 'POST' })).status, 405);
});
test('payload relays the debugger protocol both ways', { skip }, async () => {
const dbg = await connect();
assert.equal(await dbg.version(), '1.3');
assert.equal((await dbg.foregroundApp()).titleId, GAME.titleId);
// Large transfers in both directions cross the 16-bit and chunk boundaries.
const big = await dbg.read(GAME.pid, GAME.heapBase, 0x40000);
assert.deepEqual(Buffer.from(big), mock.game.heap);
const blob = new Uint8Array(0x30000);
for (let i = 0; i < blob.length; i++) blob[i] = (i * 7 + 3) & 0xff;
await dbg.write(GAME.pid, GAME.heapBase + 0x1000n, blob);
assert.deepEqual(mock.game.heap.subarray(0x1000, 0x31000), Buffer.from(blob));
mock.game.heap.fill(0, 0x1000, 0x31000);
mock.game.heap.writeUInt32LE(100, GAME.vars.health);
// Small writes of awkward sizes (frame length encodings 125/126/127 bytes).
for (const n of [1, 125, 126, 127, 65535, 65536]) {
const data = new Uint8Array(n).fill(n & 0xff);
await dbg.write(GAME.pid, GAME.heapBase + 0x2000n, data);
assert.deepEqual(mock.game.heap.subarray(0x2000, 0x2000 + n), Buffer.from(data), `write of ${n}`);
assert.deepEqual(Buffer.from(await dbg.read(GAME.pid, GAME.heapBase + 0x2000n, n)), Buffer.from(data), `read of ${n}`);
}
mock.game.heap.fill(0, 0x2000, 0x2000 + 65536);
mock.game.heap.writeUInt32LE(100, 0x9000);
const kind = valueKind('u32');
const scan = new ScanSession(() => dbg, GAME.pid, kind);
await scan.first(scannableRegions(await dbg.maps(GAME.pid)), compareKind('exact'), encodeValue(kind, '100'), () => {});
assert.ok(scan.matches >= 2);
mock.game.heap.writeUInt32LE(77, GAME.vars.health);
await scan.next(compareKind('exact'), encodeValue(kind, '77'), () => {});
assert.equal(scan.matches, 1);
dbg.close();
});
test('payload handles several connections at once', { skip }, async () => {
const clients = await Promise.all([connect(), connect(), connect(), connect()]);
const results = await Promise.all(clients.map((c) => c.read(GAME.pid, GAME.heapBase, 0x20000)));
for (const r of results) assert.equal(r.length, 0x20000);
clients.forEach((c) => c.close());
});
test('payload reports a missing debugger and survives it', { skip }, async () => {
await mock.close();
const stream = await openWebSocketStream(`ws://127.0.0.1:${PORT}/ws`);
await assert.rejects(new Ps5Debug(stream).version(), /Is the ps5debug payload loaded/);
mock = startMock({ tcpPort: MOCK, udpPort: 0, tick: false, eventPort: EVENTS });
await mock.ready;
const dbg = await connect();
assert.equal(await dbg.version(), '1.3');
dbg.close();
});
test('payload forwards debugger stop reports to /events', { skip }, async () => {
const info = await (await fetch(`http://127.0.0.1:${PORT}/api/info`)).json();
assert.equal(info.events, true);
const x86 = asAsync(createX86(createRequire(import.meta.url)('iced-x86')));
const dbg = await connect();
const ctx = createGameContext({ pid: GAME.pid, dbg: () => dbg, x86 });
const tracer = new Tracer(ctx, { openDebugger: connect, openEvents: () => openWebSocketStream(`ws://127.0.0.1:${PORT}/events`) });
let latest = [];
await tracer.start(GAME.heapBase + BigInt(GAME.vars.ammo), 4, 'write', (hits) => (latest = hits));
for (let i = 0; i < 2; i++) {
const seen = tracer.total;
mock.tick();
for (let n = 0; n < 100 && !(tracer.total === seen + 1 && !mock.debug.stopped); n++) await new Promise((r) => setTimeout(r, 20));
assert.equal(tracer.total, seen + 1);
}
assert.equal(latest[0].insn.text, 'dec dword ptr [rbx+0x28]');
assert.equal(latest[0].count, 2);
await tracer.stop();
assert.equal(mock.debug.owner, null);
mock.game.heap.writeUInt32LE(100, GAME.vars.health);
dbg.close();
});
test('payload refuses WebSockets opened by other sites', { skip }, async () => {
const handshake = (origin) =>
new Promise((resolve, reject) => {
const s = net.connect(PORT, '127.0.0.1');
let data = '';
s.on('connect', () =>
s.write(
`GET /ws HTTP/1.1\r\nHost: 127.0.0.1:${PORT}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
`Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n${origin ? `Origin: ${origin}\r\n` : ''}\r\n`,
),
);
s.on('data', (d) => {
data += d.toString('latin1');
if (data.includes('\r\n\r\n')) {
s.destroy();
resolve(data);
}
});
s.on('error', reject);
});
assert.match(await handshake('http://evil.example'), /^HTTP\/1\.1 403/);
const ok = await handshake(`http://127.0.0.1:${PORT}`);
assert.match(ok, /^HTTP\/1\.1 101/);
// The accept value for this key is the worked example in RFC 6455.
assert.match(ok, /Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK\+xOo=/);
});
test('lists the installed games with their kind, size and where they live', { skip }, async () => {
const res = await api('/api/library');
assert.equal(res.status, 200);
const { titles } = await res.json();
assert.deepEqual(titles, [
{ id: 'CUSA12345', meta: 'sfo', size: 0, partial: false, path: '' },
{ id: 'PPSA07391', meta: 'json', size: 6000, partial: false, path: '/user/app/PPSA07391' },
{ id: 'PPSA11111', meta: 'json', size: 1234, partial: false, path: '/mnt/ext0/user/app/PPSA11111' },
// Counted where the files really are, however deep, and reported at the larger location.
{ id: 'PPSA18605', meta: 'json', size: 10000, partial: false, path: '/system_ex/app/PPSA18605' },
// An image that is not mounted is sized from the image file ShadowMount points to.
{ id: 'PPSA22222', meta: 'json', size: 7787, partial: false, path: '/mnt/usb0/games/Image Game.ffpkg' },
// A mounted folder is counted once, at its source, not again at its mount point.
{ id: 'PPSA33333', meta: 'json', size: 500, partial: false, path: '/data/homebrew/Folder Game' },
]);
});
test('hands over metadata files the web app can read names from', { skip }, async () => {
const json = await api('/api/appmeta/PPSA07391/param.json');
assert.deepEqual(parseParamJson(await json.text()), { name: 'Harbor Lights', version: '01.009.000', platform: 'PS5' });
const external = await api('/api/appmeta/PPSA11111/param.json');
assert.equal(parseParamJson(await external.text()).name, 'On The Drive');
const sfo = await api('/api/appmeta/CUSA12345/param.sfo');
assert.deepEqual(parseParamSfo(new Uint8Array(await sfo.arrayBuffer())), { name: 'Old Favourite', version: '01.07', platform: 'PS4' });
const icon = await api('/api/appmeta/PPSA07391/icon0.png');
assert.equal(icon.headers.get('content-type'), 'image/png');
assert.equal((await icon.arrayBuffer()).byteLength, 7);
});
test('metadata requests cannot wander off into other files', { skip }, async () => {
for (const p of [
'/api/appmeta/PPSA07391/app.pkg',
'/api/appmeta/PPSA07391/../secret.txt',
'/api/appmeta/../secret.txt/param.json',
'/api/appmeta/ppsa07391/param.json',
'/api/appmeta/PPSA0739/param.json',
'/api/appmeta/CUSA12345/param.json',
'/api/appmeta/PPSA99998/icon0.png',
]) {
// Sent raw: fetch would tidy the dots away before the server ever saw them.
const status = await new Promise((resolve, reject) => {
const s = net.connect(PORT, '127.0.0.1', () => s.write(`GET ${p} HTTP/1.1\r\nHost: x\r\n\r\n`));
let data = '';
s.on('data', (d) => (data += d));
s.on('end', () => resolve(Number(data.split(' ')[1])));
s.on('error', reject);
});
assert.equal(status, 404, p);
}
});
test('starts a game that is on the console, and nothing else', { skip }, async () => {
const ok = await api('/api/launch/PPSA07391', { method: 'POST' });
assert.deepEqual(await ok.json(), { ok: true });
assert.equal(fs.readFileSync(LAUNCH_LOG, 'utf8'), 'PPSA07391\n');
assert.equal((await api('/api/launch/PPSA55555', { method: 'POST' })).status, 404); // not installed
assert.equal((await api('/api/launch/NPXS40000', { method: 'POST' })).status, 404); // a system app
assert.equal((await api('/api/launch/PPSA07391')).status, 404); // GET does nothing
const foreign = await api('/api/launch/PPSA07391', { method: 'POST', headers: { origin: 'http://evil.example' } });
assert.equal(foreign.status, 403);
assert.equal(fs.readFileSync(LAUNCH_LOG, 'utf8'), 'PPSA07391\n');
});
test('keeps cheat files on the console, one per game version', { skip }, async () => {
assert.deepEqual(await (await api('/api/tables/PPSA07391')).json(), { folder: '/data/cheatspecter/cheats', versions: [] });
assert.equal((await api('/api/tables/PPSA07391/01.009.000')).status, 404);
const table = emptyTable('PPSA07391', '01.009.000', 'Harbor Lights');
table.entries.push({ id: 'x', name: 'Infinite ammo', type: 'patch', at: { kind: 'module', offset: '0x2040' }, on: '909090', off: 'FF4B28' });
// Bigger than one read, so the body arrives in pieces.
table.entries.push({ id: 'y', name: 'Big script', type: 'script', code: '// pad\n'.repeat(40000) });
const text = saveFileText(table);
const saved = await api('/api/tables/PPSA07391/01.009.000', { method: 'PUT', body: text });
assert.equal(saved.status, 204);
assert.equal(fs.readFileSync(path.join(FAKE_ROOT, 'data/cheatspecter/cheats/PPSA07391-01.009.000.cspecter'), 'utf8'), text);
assert.deepEqual(fs.readdirSync(path.join(FAKE_ROOT, 'data/cheatspecter/cheats')), ['PPSA07391-01.009.000.cspecter']);
await api('/api/tables/PPSA07391/01.010.000', { method: 'PUT', body: saveFileText(emptyTable('PPSA07391', '01.010.000')) });
const listed = await (await api('/api/tables/PPSA07391')).json();
assert.deepEqual(listed.versions.sort(), ['01.009.000', '01.010.000']);
assert.deepEqual((await (await api('/api/tables/PPSA11111')).json()).versions, []);
const back = parseOwnTable(await (await api('/api/tables/PPSA07391/01.009.000')).text(), { own: true });
assert.equal(back.name, 'Harbor Lights');
assert.deepEqual(back.entries.map((e) => e.name), ['Infinite ammo', 'Big script']);
assert.equal(back.entries[1].unreviewed, undefined);
const foreign = await api('/api/tables/PPSA07391/01.009.000', { method: 'PUT', body: '{}', headers: { origin: 'http://evil.example' } });
assert.equal(foreign.status, 403);
for (const bad of ['/api/tables/PPSA07391/..', '/api/tables/PPSA07391/.hidden', '/api/tables/PPSA07391/a%2Fb', '/api/tables/ppsa07391/1']) {
assert.notEqual((await api(bad, { method: 'PUT', body: '{}' })).status, 204, bad);
}
assert.equal(fs.readdirSync(path.join(FAKE_ROOT, 'data/cheatspecter/cheats')).length, 2);
});
+448
View File
@@ -0,0 +1,448 @@
// End-to-end tests: the real client code, through the real bridge, against the
// mock console. Run with `npm test`.
import test, { after, before } from 'node:test';
import assert from 'node:assert/strict';
import { startMock, GAME } from '../mock/mock-ps5.mjs';
import { startBridge, isPrivateAddress } from '../bridge/server.mjs';
import { openWebSocketStream } from '../src/lib/transport.ts';
import { Session } from '../src/lib/session.ts';
import { Ps5Debug, authKeystream, STATUS } from '../src/lib/ps5debug.ts';
import { ScanSession, scannableRegions, valueKind, compareKind, encodeValue, decodeValue } from '../src/lib/scanner.ts';
import { parseCheatTable, findImageBase, readModState, applyMod, sameVersion } from '../src/lib/cheats.ts';
import { parseIndexLine } from '../src/lib/catalog.ts';
import { hexToBytes, bytesToHex } from '../src/lib/bytes.ts';
const TCP = 17440;
const TCP_LEGACY = 17441;
let mock, legacy, bridge, bridgePort;
const connect = async (port = TCP) => {
const stream = await openWebSocketStream(`ws://127.0.0.1:${bridgePort}/ws?host=127.0.0.1&port=${port}`);
return new Ps5Debug(stream, { timeoutMs: 3000 });
};
before(async () => {
mock = startMock({ tcpPort: TCP, udpPort: 0, tick: false });
legacy = startMock({ tcpPort: TCP_LEGACY, udpPort: 0, tick: false, legacy: true });
await Promise.all([mock.ready, legacy.ready]);
// The bridge allows exactly one non-744 target (the demo console), so the
// legacy mock is reached through a second bridge.
bridge = startBridge({ port: 0, host: '127.0.0.1', demo: { host: '127.0.0.1', port: TCP, udpPort: 0, label: 'test' } });
bridgePort = await bridge.ready;
});
after(async () => {
await bridge.close();
await mock.close();
await legacy.close();
});
test('status constants are the bit-swapped wire values', () => {
const swap = (x) => (((x >>> 1) & 0x55555555) | ((x << 1) & 0xaaaaaaaa)) >>> 0;
assert.equal(swap(0x40000000), STATUS.SUCCESS);
assert.equal(swap(0xf0000002), STATUS.ERROR);
assert.equal(swap(0xf0000003), STATUS.DATA_NULL);
assert.equal(swap(0xf0000008), STATUS.ALREADY_DEBUG);
assert.equal(swap(0xf000000a), STATUS.INVALID_INDEX);
});
test('auth keystream is deterministic and non-trivial', () => {
const a = authKeystream();
assert.equal(a.length, 256);
assert.deepEqual(a, authKeystream());
assert.ok(new Set(a).size > 64);
});
test('info commands', async () => {
const dbg = await connect();
assert.equal(await dbg.version(), '1.3');
assert.equal(await dbg.firmware(), 1000);
const b = await dbg.branding();
assert.match(b.brand, /^ps5debug-NG/);
assert.equal(b.capability, '1.1');
assert.equal(await dbg.supports('1.0'), true);
assert.equal(await dbg.supports('2.0'), false);
await dbg.ping();
dbg.close();
});
test('foreground app, process list, info and maps', async () => {
const dbg = await connect();
const app = await dbg.foregroundApp();
assert.deepEqual(app, { pid: GAME.pid, titleId: GAME.titleId, contentId: GAME.contentId, name: 'eboot.bin', version: GAME.version });
const procs = await dbg.processList();
assert.ok(procs.some((p) => p.name === 'eboot.bin' && p.pid === GAME.pid));
const info = await dbg.processInfo(GAME.pid);
assert.equal(info.titleId, GAME.titleId);
const maps = await dbg.maps(GAME.pid);
assert.equal(maps.length, 5);
assert.equal(maps[0].start, GAME.imageBase);
assert.equal(maps[0].end, GAME.imageBase + 0x10000n);
assert.equal(maps[0].prot, 5);
assert.deepEqual(findImageBase(maps, 'eboot.bin'), { address: GAME.imageBase, from: 'executable' });
dbg.close();
});
test('read, write and bulk write', async () => {
const dbg = await connect();
const addr = GAME.heapBase + BigInt(GAME.vars.ammo);
assert.equal(bytesToHex(await dbg.read(GAME.pid, addr, 4)), '1E000000');
await dbg.write(GAME.pid, addr, hexToBytes('E7030000'));
assert.equal(mock.game.heap.readUInt32LE(GAME.vars.ammo), 999);
// A read larger than the server's 64 KiB chunk exercises reassembly.
const big = await dbg.read(GAME.pid, GAME.heapBase, 0x30000);
assert.equal(big.length, 0x30000);
assert.equal(new DataView(big.buffer).getUint32(GAME.vars.ammo, true), 999);
// Writing outside any mapping fails with the second status word.
await assert.rejects(dbg.write(GAME.pid, 0x10n, hexToBytes('00')), /Writing memory failed/);
// ...and the stream is still usable afterwards.
await dbg.ping();
await dbg.writeMulti(GAME.pid, [
{ address: addr, data: hexToBytes('1E000000') },
{ address: GAME.heapBase + BigInt(GAME.vars.score), data: hexToBytes('2A000000') },
]);
assert.equal(mock.game.heap.readUInt32LE(GAME.vars.ammo), 30);
assert.equal(mock.game.heap.readUInt32LE(GAME.vars.score), 42);
// One bad entry fails the call, but the others are still written.
await assert.rejects(
dbg.writeMulti(GAME.pid, [
{ address: addr, data: hexToBytes('05000000') },
{ address: 0x10n, data: hexToBytes('00') },
]),
/Writing memory failed/,
);
assert.equal(mock.game.heap.readUInt32LE(GAME.vars.ammo), 5);
await dbg.ping();
await assert.rejects(dbg.writeMulti(GAME.pid, new Array(0x10000).fill({ address: addr, data: hexToBytes('00') })), /Too many values/);
mock.game.heap.writeUInt32LE(30, GAME.vars.ammo);
dbg.close();
});
test('commands queue instead of interleaving', async () => {
const dbg = await connect();
const results = await Promise.all([dbg.version(), dbg.firmware(), dbg.read(GAME.pid, GAME.heapBase, 8), dbg.ping(), dbg.version()]);
assert.equal(results[0], '1.3');
assert.equal(results[1], 1000);
assert.equal(results[2].length, 8);
assert.equal(results[4], '1.3');
dbg.close();
});
test('notify', async () => {
const dbg = await connect();
await dbg.notify('CheatSpecter connected');
assert.equal(mock.state.notifications.at(-1), 'CheatSpecter connected');
dbg.close();
});
test('scan: exact first pass, then narrow by change', async () => {
const dbg = await connect();
mock.game.heap.writeUInt32LE(100, GAME.vars.health);
const kind = valueKind('u32');
const regions = scannableRegions(await dbg.maps(GAME.pid));
assert.ok(regions.length >= 3);
assert.ok(regions.every((r) => r.start !== GAME.imageBase), 'code is not scanned');
const scan = new ScanSession(() => dbg, GAME.pid, kind);
await scan.first(regions, compareKind('exact'), encodeValue(kind, '100'), () => {});
assert.equal(dbg.authed, true);
assert.equal(scan.matches, 6); // health plus five decoys
const healthAddr = GAME.heapBase + BigInt(GAME.vars.health);
assert.ok((await scan.hits(100)).some((h) => h.address === healthAddr));
mock.game.heap.writeUInt32LE(93, GAME.vars.health);
await scan.next(compareKind('decreased'), new Uint8Array(0), () => {});
assert.equal(scan.matches, 1);
const [hit] = await scan.hits(10);
assert.equal(hit.address, healthAddr);
assert.equal(decodeValue(kind, hit.value), '93');
await scan.next(compareKind('unchanged'), new Uint8Array(0), () => {});
assert.equal(scan.matches, 1);
await scan.next(compareKind('exact'), encodeValue(kind, '93'), () => {});
assert.equal(scan.matches, 1);
await scan.next(compareKind('changed'), new Uint8Array(0), () => {});
assert.equal(scan.matches, 0);
dbg.close();
});
test('scan: float, bigger/smaller/between', async () => {
const dbg = await connect();
mock.game.heap.writeFloatLE(2500, GAME.vars.gold);
const kind = valueKind('float');
const regions = scannableRegions(await dbg.maps(GAME.pid));
const scan = new ScanSession(() => dbg, GAME.pid, kind);
await scan.first(regions, compareKind('exact'), encodeValue(kind, '2500'), () => {});
assert.equal(scan.matches, 1);
const goldHit = (await scan.hits(1))[0];
assert.equal(goldHit.address, GAME.heapBase + BigInt(GAME.vars.gold));
assert.equal(decodeValue(kind, goldHit.value), '2500');
const between = new Uint8Array(8);
between.set(encodeValue(kind, '2000'), 0);
between.set(encodeValue(kind, '3000'), 4);
const scan2 = new ScanSession(() => dbg, GAME.pid, kind);
await scan2.first(regions, compareKind('between'), between, () => {});
assert.ok((await scan2.hits(1000)).some((h) => h.address === GAME.heapBase + BigInt(GAME.vars.gold)));
await scan2.next(compareKind('bigger'), encodeValue(kind, '2499'), () => {});
await scan2.next(compareKind('smaller'), encodeValue(kind, '2501'), () => {});
assert.equal(scan2.matches, 1);
dbg.close();
});
test('value encoding', () => {
assert.equal(bytesToHex(encodeValue(valueKind('u32'), '100')), '64000000');
assert.equal(bytesToHex(encodeValue(valueKind('u32'), '0xFF')), 'FF000000');
assert.equal(bytesToHex(encodeValue(valueKind('i16'), '-2')), 'FEFF');
assert.equal(bytesToHex(encodeValue(valueKind('u64'), '18446744073709551615')), 'FFFFFFFFFFFFFFFF');
assert.equal(bytesToHex(encodeValue(valueKind('float'), '1')), '0000803F');
assert.equal(decodeValue(valueKind('i8'), hexToBytes('FF')), '-1');
assert.equal(decodeValue(valueKind('double'), encodeValue(valueKind('double'), '0.1')), '0.1');
assert.throws(() => encodeValue(valueKind('u8'), '256'), /does not fit/);
assert.throws(() => encodeValue(valueKind('u8'), 'abc'), /not a whole number/);
assert.throws(() => encodeValue(valueKind('u32'), ''), /Enter a value/);
});
test('cheat table: parse, detect state, toggle, refuse mismatch', async () => {
const dbg = await connect();
const table = parseCheatTable(
JSON.stringify({
name: 'Specter Test Game',
id: 'PPSA99999',
version: '01.000.000',
process: 'eboot.bin',
credits: ['tester'],
mods: [
{ name: 'Infinite Health', type: 'checkbox', memory: [{ offset: '1000', on: '909090909090', off: '898190030000' }] },
{ name: 'Wrong build', type: 'checkbox', memory: [{ offset: '5000', on: '9090', off: 'DEAD' }] },
{ name: 'Cave', type: 'checkbox', memory: [{ offset: '10', section: '2', on: '90', off: '00' }] },
{ name: 'Give gold', type: 'button', hint: 'once', memory: [{ offset: '2040', on: 'FF4B28', off: 'FF4B28' }] },
],
}),
);
assert.equal(table.titleId, 'PPSA99999');
assert.equal(table.mods.length, 4);
assert.equal(table.mods[2].unsupported, 'Depends on a master code');
assert.equal(table.mods[3].type, 'button');
assert.equal(table.mods[3].description, 'once');
const base = findImageBase(await dbg.maps(GAME.pid), table.process).address;
const [health, wrong, cave, button] = table.mods;
assert.equal(await readModState(dbg, GAME.pid, base, health), 'off');
await applyMod(dbg, GAME.pid, base, health, true);
assert.equal(bytesToHex(mock.game.image.subarray(0x1000, 0x1006)), '909090909090');
assert.equal(await readModState(dbg, GAME.pid, base, health), 'on');
await applyMod(dbg, GAME.pid, base, health, false);
assert.equal(await readModState(dbg, GAME.pid, base, health), 'off');
assert.equal(await readModState(dbg, GAME.pid, base, wrong), 'mismatch');
assert.equal(await readModState(dbg, GAME.pid, base, cave), 'unknown');
assert.equal(await readModState(dbg, GAME.pid, base, button), 'unknown');
await assert.rejects(applyMod(dbg, GAME.pid, base, cave, true), /master code/);
dbg.close();
});
test('cheat table: rejects junk', () => {
assert.throws(() => parseCheatTable('not json'), /not valid JSON/);
assert.throws(() => parseCheatTable('{"name":"x"}'), /no "mods" list/);
assert.equal(parseCheatTable('{"mods":[]}').mods.length, 0);
});
test('version and index matching', () => {
assert.ok(sameVersion('01.026.000', '1.026.000'));
assert.ok(sameVersion('01.07', '1.7'));
assert.ok(sameVersion('01.00', '01.000.000'));
assert.ok(!sameVersion('01.07', '01.08'));
assert.ok(!sameVersion('', '01.00'));
assert.deepEqual(parseIndexLine('PPSA01628_1.026.000.json=Some Game'), { file: 'PPSA01628_1.026.000.json', titleId: 'PPSA01628', version: '1.026.000', gameName: 'Some Game', format: 'json' });
assert.equal(parseIndexLine('CUSA00018_01.21_default.elf.json=X').version, '01.21');
assert.equal(parseIndexLine('CUSA09193_01.05_2.json=X').version, '01.05');
assert.equal(parseIndexLine('CUSA00002_01.00_c20ae0e8.json=A=B').gameName, 'A=B');
assert.equal(parseIndexLine('README.md'), null);
});
test('bridge refuses targets that are not local consoles', async () => {
assert.ok(isPrivateAddress('192.168.1.20'));
assert.ok(isPrivateAddress('10.0.0.5'));
assert.ok(isPrivateAddress('172.20.1.1'));
assert.ok(!isPrivateAddress('8.8.8.8'));
assert.ok(!isPrivateAddress('172.32.0.1'));
assert.ok(!isPrivateAddress('example.com'));
const stream = await openWebSocketStream(`ws://127.0.0.1:${bridgePort}/ws?host=8.8.8.8&port=744`);
await assert.rejects(new Ps5Debug(stream).version(), /not a console on your local network/);
// A local address on a port that is not the debugger's is refused too.
const stream2 = await openWebSocketStream(`ws://127.0.0.1:${bridgePort}/ws?host=127.0.0.1&port=22`);
await assert.rejects(new Ps5Debug(stream2).version(), /not a console/);
});
test('bridge reports an unreachable console in plain words', async () => {
const b2 = startBridge({ port: 0, host: '127.0.0.1', demo: { host: '127.0.0.1', port: 17499, udpPort: 0, label: 'nothing here' } });
const p2 = await b2.ready;
const stream = await openWebSocketStream(`ws://127.0.0.1:${p2}/ws?host=127.0.0.1&port=17499`);
await assert.rejects(new Ps5Debug(stream).version(), /Is the ps5debug payload loaded/);
await b2.close();
});
test('original ps5debug: no capability level, so extras are not used', async () => {
const b2 = startBridge({ port: 0, host: '127.0.0.1', demo: { host: '127.0.0.1', port: TCP_LEGACY, udpPort: 0, label: 'legacy' } });
const p2 = await b2.ready;
const stream = await openWebSocketStream(`ws://127.0.0.1:${p2}/ws?host=127.0.0.1&port=${TCP_LEGACY}`);
const dbg = new Ps5Debug(stream, { timeoutMs: 400 });
assert.equal((await dbg.branding()).capability, '');
assert.equal(await dbg.supports('1.0'), false);
const procs = await dbg.processList();
assert.ok(procs.some((p) => p.name === 'eboot.bin'));
// Sending an extension anyway gets no answer; the client times out and
// closes the stream rather than hanging forever.
await assert.rejects(dbg.foregroundApp(), /stopped responding/);
assert.equal(dbg.closed, true);
await b2.close();
});
test('scan regions: overlapping map entries are merged, code is skipped', () => {
const m = (start, end, prot, name = '') => ({ name, start, end, offset: 0n, prot });
const regions = scannableRegions([
m(0x5000n, 0x9000n, 3, '(aux)'), // overlaps the next two
m(0x1000n, 0x3000n, 5, 'executable'),
m(0x4000n, 0x6000n, 3),
m(0x6000n, 0x8000n, 3),
m(0xa000n, 0xb000n, 1), // read-only
m(0xc000n, 0xd000n, 7), // writable code
m(0xe000n, 0xf000n, 3),
]);
assert.deepEqual(regions, [
{ start: 0x4000n, length: 0x5000 },
{ start: 0xe000n, length: 0x1000 },
]);
});
test('scan values are size-checked before they reach the console', async () => {
const dbg = await connect();
await dbg.auth();
const base = { pid: GAME.pid, address: GAME.heapBase, length: 0x1000, valueType: 4 };
await assert.rejects(dbg.scanStart({ ...base, compareType: 4, value: new Uint8Array(4) }, () => {}), /wrong size/);
await assert.rejects(dbg.scanStart({ ...base, compareType: 0, value: new Uint8Array(0) }, () => {}), /needs a value/);
await dbg.ping(); // nothing was sent, so the stream is intact
dbg.close();
});
test('session: a console-side error drops the connection and the session reopens it', async () => {
const url = `ws://127.0.0.1:${bridgePort}/ws?host=127.0.0.1&port=${TCP}`;
const session = await Session.connect({ host: '127.0.0.1', port: TCP }, url);
let lost = null;
session.onLost = (r) => (lost = r);
assert.equal(session.extended, true);
assert.equal(session.firmware, 1000);
assert.equal((await session.currentGame()).titleId, GAME.titleId);
const before = session.main;
await assert.rejects(session.main.maps(4242), /Reading the memory map failed/);
// Give the reopen a moment, then the same session works again on a new connection.
for (let i = 0; i < 50 && session.main === before; i++) await new Promise((r) => setTimeout(r, 20));
assert.notEqual(session.main, before);
assert.equal((await session.main.maps(GAME.pid)).length, 5);
assert.equal(lost, null);
// A scan session keeps working across the swap because it asks for the connection each pass.
const kind = valueKind('u32');
mock.game.heap.writeUInt32LE(100, GAME.vars.health);
const scan = new ScanSession(() => session.scan, GAME.pid, kind);
await scan.first(scannableRegions(await session.scan.maps(GAME.pid)), compareKind('exact'), encodeValue(kind, '100'), () => {});
const oldScan = session.scan;
await assert.rejects(session.scan.maps(4242));
for (let i = 0; i < 50 && session.scan === oldScan; i++) await new Promise((r) => setTimeout(r, 20));
await scan.next(compareKind('unchanged'), new Uint8Array(0), () => {});
assert.equal(scan.matches, 6);
session.close();
assert.equal(lost, null);
});
test('session: gives up when the console keeps dropping the connection', async () => {
const url = `ws://127.0.0.1:${bridgePort}/ws?host=127.0.0.1&port=${TCP}`;
const session = await Session.connect({ host: '127.0.0.1', port: TCP }, url);
let lost = null;
session.onLost = (r) => (lost = r);
for (let i = 0; i < 8 && lost === null; i++) {
const cur = session.main;
await cur.maps(4242).catch(() => {});
for (let j = 0; j < 50 && session.main === cur && lost === null; j++) await new Promise((r) => setTimeout(r, 20));
}
assert.notEqual(lost, null);
});
test('session: payload that never answers BRANDING still connects, without extras', async () => {
const old = startMock({ tcpPort: 17442, udpPort: 0, tick: false, legacy: true, noBranding: true });
await old.ready;
const b2 = startBridge({ port: 0, host: '127.0.0.1', demo: { host: '127.0.0.1', port: 17442, udpPort: 0, label: 'old' } });
const p2 = await b2.ready;
const session = await Session.connect({ host: '127.0.0.1', port: 17442 }, `ws://127.0.0.1:${p2}/ws?host=127.0.0.1&port=17442`);
assert.equal(session.extended, false);
assert.equal(session.firmware, 0);
const game = await session.currentGame();
assert.equal(game.titleId, GAME.titleId);
assert.equal(game.version, '');
session.close();
await b2.close();
await old.close();
});
test('bridge serves info and the local cheats index', async () => {
const info = await (await fetch(`http://127.0.0.1:${bridgePort}/api/info`)).json();
assert.equal(info.mode, 'bridge');
assert.equal(info.demo.port, TCP);
const index = await (await fetch(`http://127.0.0.1:${bridgePort}/api/local-cheats`)).text();
assert.match(index, /PPSA99999_01\.000\.000\.json=Specter Test Game/);
const res = await fetch(`http://127.0.0.1:${bridgePort}/local-cheats/..%2Fpackage.json`);
assert.equal(res.status, 404);
});
test('Auto search finds a value whatever type it is stored as', async () => {
const { AutoScan } = await import('../src/lib/scanner.ts');
const dbg = await connect();
try {
const regions = scannableRegions(await dbg.maps(GAME.pid));
// The mock's gold is a float and its ammo a 4-byte integer; set both to the same number.
const gold = GAME.heapBase + BigInt(GAME.vars.gold);
const ammo = GAME.heapBase + BigInt(GAME.vars.ammo);
const f = new Uint8Array(4); new DataView(f.buffer).setFloat32(0, 7777, true);
const i = new Uint8Array(4); new DataView(i.buffer).setUint32(0, 7777, true);
await dbg.write(GAME.pid, gold, f);
await dbg.write(GAME.pid, ammo, i);
const scan = new AutoScan(() => dbg, GAME.pid);
scan.input('7777');
const seen = [];
await scan.first(regions, compareKind('exact'), new Uint8Array(0), (p) => seen.push(p.detail));
assert.ok(seen.includes('as float') && seen.includes('as 4 bytes'));
let hits = await scan.hits(50);
const at = (addr) => hits.find((h) => h.address === addr)?.kind.id;
assert.equal(at(gold), 'float');
assert.equal(at(ammo), 'u32');
// The integer changes, the float does not: narrowing keeps each type's own candidates.
new DataView(i.buffer).setUint32(0, 7770, true);
await dbg.write(GAME.pid, ammo, i);
scan.input('7770');
await scan.next(compareKind('exact'), new Uint8Array(0), () => {});
hits = await scan.hits(50);
assert.deepEqual(hits.map((h) => [h.address, h.kind.id]), [[ammo, 'u32']]);
// A value with a fraction cannot be a whole-number type; those are simply not searched.
const frac = new AutoScan(() => dbg, GAME.pid);
frac.input('99.5');
await frac.first(regions, compareKind('exact'), new Uint8Array(0), () => {});
assert.deepEqual(frac.kinds.map((k) => k.id).sort(), ['double', 'float']);
const none = new AutoScan(() => dbg, GAME.pid);
none.input('abc');
await assert.rejects(none.first(regions, compareKind('exact'), new Uint8Array(0), () => {}), /not a number/);
} finally {
dbg.close();
}
});
+513
View File
@@ -0,0 +1,513 @@
// The workbench: locations, own tables, code injection, tracing, pointer
// paths, unknown-value scans and the script API, against the mock console.
import test, { after, before } from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { startMock, GAME } from '../mock/mock-ps5.mjs';
import { startBridge } from '../bridge/server.mjs';
import { openWebSocketStream } from '../src/lib/transport.ts';
import { Ps5Debug } from '../src/lib/ps5debug.ts';
import { createX86, asAsync, instructionEndingAt, parsePattern, signatureFromCode } from '../src/lib/x86.ts';
import { createGameContext, describeLocation, findPattern, imageRange, parseAddress, resolveLocation } from '../src/lib/locations.ts';
import { MismatchError, TableRunner, describeEntry, exportCommunityTable, exportOwnTable, parseOwnTable, emptyTable } from '../src/lib/table.ts';
import { Tracer } from '../src/lib/tracer.ts';
import { findPointerPaths } from '../src/lib/pointerscan.ts';
import { SnapshotScan, scannableRegions, valueKind, compareKind, encodeValue, decodeValue } from '../src/lib/scanner.ts';
import { handleScriptCall } from '../src/lib/script.ts';
import { bytesToHex, hexToBytes } from '../src/lib/bytes.ts';
const require = createRequire(import.meta.url);
const sync = createX86(require('iced-x86'));
const x86 = asAsync(sync);
const TCP = 17460;
const TCP_FAR = 17461;
const EVENTS = 17765;
let mock, mockFar, bridge, bridgeFar, port, portFar;
const HEALTH = GAME.heapBase + BigInt(GAME.vars.health);
const SITE = GAME.imageBase + BigInt(GAME.code.healthDrain.offset);
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
const until = async (cond, what) => {
for (let i = 0; i < 100; i++) {
if (cond()) return;
await wait(20);
}
throw new Error(`timed out waiting for ${what}`);
};
const url = (p, tcp, path = 'ws') => `ws://127.0.0.1:${p}/${path}?host=127.0.0.1&port=${tcp}`;
const connect = async (p = port, tcp = TCP) => new Ps5Debug(await openWebSocketStream(url(p, tcp)), { timeoutMs: 4000 });
const context = async (p = port, tcp = TCP) => {
const dbg = await connect(p, tcp);
// As in the app: assembling gets a connection of its own, because the console drops it on a syntax error.
const assemble = async (base, text) => {
const tmp = await connect(p, tcp);
try {
return await tmp.assemble(base, text);
} finally {
if (!tmp.closed) tmp.close();
}
};
return { dbg, ctx: createGameContext({ pid: GAME.pid, dbg: () => dbg, x86, assemble }) };
};
before(async () => {
mock = startMock({ tcpPort: TCP, udpPort: 0, tick: false, eventPort: EVENTS });
mockFar = startMock({ tcpPort: TCP_FAR, udpPort: 0, tick: false, noNearAlloc: true });
await Promise.all([mock.ready, mockFar.ready]);
bridge = startBridge({ port: 0, host: '127.0.0.1', eventPort: EVENTS, demo: { host: '127.0.0.1', port: TCP, udpPort: 0, label: 't' } });
bridgeFar = startBridge({ port: 0, host: '127.0.0.1', eventPort: null, demo: { host: '127.0.0.1', port: TCP_FAR, udpPort: 0, label: 't' } });
port = await bridge.ready;
portFar = await bridgeFar.ready;
});
after(async () => {
await bridge.close();
await bridgeFar.close();
await mock.close();
await mockFar.close();
});
test('x86: decode, relocate, find the previous instruction, build a signature', () => {
const code = hexToBytes('898190030000 FF4B28 8B0512340000 E800100000 C3');
const insns = sync.disassemble(code, 0x1000n);
assert.deepEqual(insns.map((i) => i.text), ['mov [rcx+0x390], eax', 'dec dword ptr [rbx+0x28]', 'mov eax, [0x4421]', 'call 0x2014', 'ret']);
assert.equal(insns[0].writesMemory, true);
assert.equal(insns[2].ripTarget, 0x4421n);
assert.equal(insns[3].flow, 'call');
assert.equal(insns[3].target, 0x2014n);
assert.deepEqual(insns[2].variable, [{ offset: 2, size: 4 }]);
// Moving RIP-relative code keeps it pointing at the same data.
const moved = sync.relocate(hexToBytes('8B0512340000'), 0x1000n, 0x900000n);
assert.equal(sync.disassemble(moved, 0x900000n)[0].ripTarget, 0x1000n + 6n + 0x3412n);
assert.equal(instructionEndingAt(sync, code.subarray(0, 9), 0x1009n).text, 'dec dword ptr [rbx+0x28]');
assert.equal(instructionEndingAt(sync, code.subarray(0, 6), 0x1006n).text, 'mov [rcx+0x390], eax');
// The displacement and the call target are wildcarded; the rest is literal.
assert.equal(signatureFromCode(insns.slice(2), 10).text, '8B 05 ?? ?? ?? ?? E8');
assert.equal(signatureFromCode(insns, 8).text, '89 81 90 03 00 00 FF 4B 28');
assert.deepEqual([...parsePattern('89 81 ?? 03').mask], [1, 1, 0, 1]);
assert.throws(() => parsePattern('89 8'), /not a byte/);
assert.throws(() => parsePattern('?? ??'), /at least one fixed byte/);
});
test('locations: module, signature, pointer path, typed addresses', async () => {
const { dbg, ctx } = await context();
assert.equal(await resolveLocation(ctx, { kind: 'module', offset: '1000' }), SITE);
assert.equal(await parseAddress(ctx, 'game+1000'), SITE);
assert.equal(await parseAddress(ctx, '0x880012340'), HEALTH);
await assert.rejects(parseAddress(ctx, 'hello'), /not a hex number/);
assert.deepEqual(await imageRange(ctx), { start: GAME.imageBase, end: GAME.dataBase + 0x4000n });
assert.deepEqual(await findPattern(ctx, '89 81 90 03 00 00'), { address: SITE, unique: true });
assert.equal((await findPattern(ctx, 'CC CC CC CC')).unique, false);
assert.equal(await findPattern(ctx, 'DE AD BE EF 01 02'), null);
await assert.rejects(findPattern(ctx, '00 00 ?? 00'), /only of 00 bytes/);
assert.equal(await resolveLocation(ctx, { kind: 'signature', pattern: '89 81 ?? ?? 00 00 C3', offset: 0 }), SITE);
assert.equal(await resolveLocation(ctx, { kind: 'signature', pattern: 'FF 4B 28', offset: 3 }), GAME.imageBase + 0x2043n);
await assert.rejects(resolveLocation(ctx, { kind: 'signature', pattern: 'CC CC CC CC', offset: 0 }), /more than one place/);
await assert.rejects(resolveLocation(ctx, { kind: 'signature', pattern: 'DE AD BE EF 01', offset: 0 }), /not found/);
const p1 = { kind: 'pointer', base: '10100', offsets: ['0x340'] };
const p2 = { kind: 'pointer', base: '10200', offsets: ['0x8', '0x340'] };
assert.equal(await resolveLocation(ctx, p1), HEALTH);
assert.equal(await resolveLocation(ctx, p2), HEALTH);
assert.equal(describeLocation(p2), '[[game+0x10200]+0x8]+0x340');
await assert.rejects(resolveLocation(ctx, { kind: 'pointer', base: '10300', offsets: ['0x10'] }), /leads nowhere/);
dbg.close();
});
test('runner: patch by signature, mismatch refusal, undo', async () => {
const { dbg, ctx } = await context();
const runner = new TableRunner(ctx);
const patch = { id: 'a', type: 'patch', name: 'Infinite health', at: { kind: 'signature', pattern: '89 81 90 03 00 00', offset: 0 }, on: '909090909090', off: '898190030000' };
await runner.enable(patch);
assert.equal(runner.isOn('a'), true);
assert.equal(bytesToHex(mock.game.image.subarray(0x1000, 0x1006)), '909090909090');
await runner.disable(patch);
assert.equal(bytesToHex(mock.game.image.subarray(0x1000, 0x1006)), '898190030000');
const wrong = { id: 'b', type: 'patch', name: 'Wrong', at: { kind: 'module', offset: '2040' }, on: '909090', off: 'AABBCC' };
await assert.rejects(runner.enable(wrong), MismatchError);
assert.equal(bytesToHex(mock.game.image.subarray(0x2040, 0x2043)), 'FF4B28');
// Forced, it applies, and undo puts back what was really there rather than the table's guess.
await runner.enable(wrong, { force: true });
assert.equal(bytesToHex(mock.game.image.subarray(0x2040, 0x2043)), '909090');
await runner.disable(wrong);
assert.equal(bytesToHex(mock.game.image.subarray(0x2040, 0x2043)), 'FF4B28');
// No "off" bytes recorded: the original is captured when it is switched on.
const bare = { id: 'c', type: 'patch', name: 'Bare', at: { kind: 'module', offset: '30A0' }, on: '90909090' };
await runner.enable(bare);
await runner.disable(bare);
assert.equal(bytesToHex(mock.game.image.subarray(0x30a0, 0x30a4)), 'F30F5CC1');
runner.dispose();
dbg.close();
});
test('runner: set and hold a value through a pointer path, call a function', async () => {
const { dbg, ctx } = await context();
const runner = new TableRunner(ctx);
const hold = { id: 'v', type: 'value', name: 'Health', at: { kind: 'pointer', base: '10100', offsets: ['0x340'] }, valueType: 'u32', value: '999', freeze: true };
await runner.enable(hold);
assert.equal(mock.game.heap.readUInt32LE(GAME.vars.health), 999);
mock.game.heap.writeUInt32LE(5, GAME.vars.health);
await until(() => mock.game.heap.readUInt32LE(GAME.vars.health) === 999, 'the freeze to rewrite the value');
assert.equal(await runner.readValue(hold), '999');
await runner.disable(hold);
mock.game.heap.writeUInt32LE(100, GAME.vars.health);
await wait(350);
assert.equal(mock.game.heap.readUInt32LE(GAME.vars.health), 100);
const add = { id: 'f', type: 'call', name: 'add', fn: { kind: 'module', offset: '4000' }, args: ['40', '0x2'] };
await runner.enable(add);
assert.match(runner.result('f'), /Returned 0x2A \(42\)/);
await runner.enable({ id: 'g', type: 'call', name: 'gold', fn: { kind: 'module', offset: '4100' }, args: ['777'] });
assert.equal(mock.game.heap.readFloatLE(GAME.vars.gold), 777);
mock.game.heap.writeFloatLE(2500, GAME.vars.gold);
await assert.rejects(runner.enable({ id: 'h', type: 'call', name: 'bad', fn: { kind: 'module', offset: '5000' }, args: [] }), /Calling the function failed/);
await assert.rejects(runner.enable({ ...add, id: 'i', args: ['x'] }), /not a number/);
runner.dispose();
dbg.close();
});
for (const far of [false, true]) {
test(`runner: inject code through a ${far ? 'far (14-byte)' : 'near (5-byte)'} hook`, async () => {
const m = far ? mockFar : mock;
const { dbg, ctx } = await context(far ? portFar : port, far ? TCP_FAR : TCP);
const runner = new TableRunner(ctx);
const before = Buffer.from(m.game.image.subarray(0x1000, 0x1020));
for (const placement of ['before', 'after', 'replace']) {
const entry = { id: 'inj-' + placement, type: 'inject', name: placement, at: { kind: 'module', offset: '1000' }, code: 'nop\nnop\ndb 0x90', placement };
await runner.enable(entry);
const site = m.game.image.subarray(0x1000, 0x1020);
const hook = sync.disassemble(site.subarray(0, 16), SITE, 1)[0];
assert.equal(hook.flow, 'jump');
// Far hooks are "jmp [rip+0]" (6 bytes) followed by the 8-byte destination.
assert.equal(hook.length, far ? 6 : 5);
const cave = far ? site.readBigUInt64LE(6) : hook.target;
assert.equal(cave - SITE < 0x7fffffffn && cave > SITE, !far);
// What the hook overwrote: whole instructions, at least as long as the jump.
const covered = far ? 14 : 6;
if (!far) assert.equal(site[5], 0x90, 'leftover byte is padded with a nop');
const body = sync.disassemble(Buffer.from(m.game.read(cave, 64)), cave, 16).map((i) => i.text);
const orig = far
? ['mov [rcx+0x390], eax', 'ret', 'int3', 'int3', 'int3', 'int3', 'int3', 'int3', 'int3']
: ['mov [rcx+0x390], eax'];
const user = ['nop', 'nop', 'nop'];
const expected = placement === 'before' ? [...user, ...orig] : placement === 'after' ? [...orig, ...user] : user;
assert.deepEqual(body.slice(0, expected.length), expected, placement);
// ...followed by the jump back to just past the overwritten instructions.
const tail = sync.disassemble(Buffer.from(m.game.read(cave, 64)), cave, expected.length + 1)[expected.length];
assert.equal(tail.flow, 'jump', placement);
const backTo = tail.target ?? Buffer.from(m.game.read(tail.address + 6n, 8)).readBigUInt64LE(0);
assert.equal(backTo, SITE + BigInt(covered), placement);
// Hooking the same spot twice is refused rather than stacking jumps.
await assert.rejects(runner.enable({ ...entry, id: 'again' }), /already a jump/);
await runner.disable(entry);
assert.deepEqual(Buffer.from(m.game.image.subarray(0x1000, 0x1020)), before, 'original code restored');
}
// A syntax error surfaces with the assembler's message and leaves the game untouched.
await assert.rejects(
runner.enable({ id: 'bad', type: 'inject', name: 'bad', at: { kind: 'module', offset: '1000' }, code: 'frobnicate rax', placement: 'before' }),
/Assembler: invalid mnemonic/,
);
assert.deepEqual(Buffer.from(m.game.image.subarray(0x1000, 0x1020)), before);
await dbg.ping(); // the typo did not cost us the main connection
// Sent on a shared connection instead, the same error ends that connection.
const shared = await connect(far ? portFar : port, far ? TCP_FAR : TCP);
await assert.rejects(shared.assemble(0x1000n, 'frobnicate'), /Assembler/);
await until(() => shared.closed, 'the console to drop the connection');
runner.dispose();
dbg.close();
});
}
test('tracer: finds the instruction that writes a value, then lets go of the game', async () => {
const { dbg, ctx } = await context();
const tracer = new Tracer(ctx, {
openDebugger: () => connect(),
openEvents: () => openWebSocketStream(`ws://127.0.0.1:${port}/events?host=127.0.0.1`),
});
let latest = [];
await tracer.start(HEALTH, 4, 'write', (hits) => {
latest = hits;
});
assert.equal(mock.debug.owner !== null, true);
for (let i = 0; i < 3; i++) {
const seen = tracer.total;
mock.tick(); // the game writes health and stops
await until(() => tracer.total === seen + 1 && !mock.debug.stopped, 'the hit to be handled and the game resumed');
}
assert.equal(latest.length, 1);
assert.equal(latest[0].count, 3);
assert.equal(latest[0].insn.text, 'mov [rcx+0x390], eax');
assert.equal(latest[0].insn.address, SITE);
assert.equal(latest[0].regs.rcx, HEALTH - 0x390n);
// A second debugger is refused while this one is attached.
const other = await connect();
await assert.rejects(other.debugAttach(GAME.pid), /already attached/);
await tracer.stop();
assert.equal(tracer.running, false);
assert.equal(mock.debug.owner, null);
assert.equal(mock.state.detachedWithWatchArmed, false, 'the watchpoint is disarmed before letting go');
const h = mock.game.heap.readUInt32LE(GAME.vars.health);
mock.tick();
assert.equal(mock.game.heap.readUInt32LE(GAME.vars.health), h - 1, 'the game runs freely again');
assert.equal(mock.debug.stopped, false);
mock.game.heap.writeUInt32LE(100, GAME.vars.health);
dbg.close();
});
test('tracer: stops by itself after the hit limit and still detaches', async () => {
const { dbg, ctx } = await context();
const tracer = new Tracer(ctx, {
openDebugger: () => connect(),
openEvents: () => openWebSocketStream(`ws://127.0.0.1:${port}/events?host=127.0.0.1`),
});
tracer.maxHits = 2;
let reason;
await tracer.start(GAME.heapBase + BigInt(GAME.vars.score), 4, 'write', (_hits, ended) => {
if (ended) reason = ended;
});
mock.tick();
await until(() => tracer.total === 1 && !mock.debug.stopped, 'first hit');
mock.tick();
await until(() => !tracer.running, 'the tracer to stop');
assert.match(reason, /Stopped after 2 hits/);
assert.equal(tracer.list()[0].insn.text, 'add dword ptr [rdi+0x38880], 0xA');
assert.equal(mock.debug.owner, null);
mock.game.heap.writeUInt32LE(100, GAME.vars.health);
mock.game.heap.writeUInt32LE(30, GAME.vars.ammo);
mock.game.heap.writeFloatLE(2500, GAME.vars.gold);
dbg.close();
});
test('tracer: steps aside when the game gets a signal of its own, or the session ends under it', async () => {
const { dbg, ctx } = await context();
const deps = { openDebugger: () => connect(), openEvents: () => openWebSocketStream(`ws://127.0.0.1:${port}/events?host=127.0.0.1`) };
let reason;
const tracer = new Tracer(ctx, deps);
await tracer.start(HEALTH, 4, 'write', (_h, ended) => ended && (reason = ended));
mock.raise(11);
await until(() => !tracer.running, 'the tracer to end');
assert.match(reason, /received signal 11/);
assert.equal(tracer.total, 0, 'not counted as a hit');
assert.equal(mock.debug.owner, null);
// An unaligned address is watched as the aligned block that contains it.
reason = undefined;
const t2 = new Tracer(ctx, deps);
await t2.start(HEALTH + 1n, 4, 'write', (_h, ended) => ended && (reason = ended));
assert.equal(mock.debug.watch[0].address, HEALTH);
// The console ends the session by itself (as when the game quits).
mock.debug.events.destroy();
await until(() => !t2.running, 'the second tracer to notice');
assert.match(reason, /ended the debugging session/);
mock.debug.owner?.destroy();
await until(() => mock.debug.owner === null, 'teardown');
dbg.close();
});
test('tracer: a bridge without the event port explains itself', async () => {
await assert.rejects(
(async () => {
const s = await openWebSocketStream(`ws://127.0.0.1:${portFar}/events?host=127.0.0.1`);
await s.read(1);
})(),
/turned off/,
);
});
test('pointer scan: finds static paths to a heap value', async () => {
const { dbg, ctx } = await context();
const paths = await findPointerPaths(ctx, HEALTH, { maxDepth: 2 }, () => {});
const texts = paths.map((p) => describeLocation(p.location));
assert.ok(texts.includes('[game+0x10100]+0x340'), texts.join(' | '));
assert.ok(texts.includes('[[game+0x10200]+0x8]+0x340'), texts.join(' | '));
assert.equal(paths[0].depth, 1, 'shortest first');
for (const p of paths) assert.equal(await resolveLocation(ctx, p.location), HEALTH);
dbg.close();
});
test('unknown-value scan: snapshot on the console, narrow by change', async () => {
const dbg = await connect();
const kind = valueKind('u32');
mock.game.heap.writeUInt32LE(100, GAME.vars.health);
const regions = scannableRegions(await dbg.maps(GAME.pid));
assert.ok(((await dbg.turboCaps()) & 0x18) === 0x18);
const scan = new SnapshotScan(() => dbg, GAME.pid, kind);
await scan.first(regions, compareKind('unknown'), new Uint8Array(0), () => {});
const start = scan.matches;
assert.ok(start > 8, 'every non-zero value is a candidate');
mock.game.heap.writeUInt32LE(90, GAME.vars.health);
await scan.next(compareKind('decreased'), new Uint8Array(0), () => {});
assert.equal(scan.matches, 1);
const [hit] = await scan.hits(10);
assert.equal(hit.address, HEALTH);
assert.equal(decodeValue(kind, hit.value), '90');
await scan.next(compareKind('unchanged'), new Uint8Array(0), () => {});
assert.equal(scan.matches, 1);
await scan.next(compareKind('exact'), encodeValue(kind, '90'), () => {});
assert.equal(scan.matches, 1);
mock.game.heap.writeUInt32LE(95, GAME.vars.health);
await scan.next(compareKind('decreased'), new Uint8Array(0), () => {});
assert.equal(scan.matches, 0);
assert.deepEqual(await scan.hits(10), []);
await scan.end();
// A value that is zero when the snapshot is taken can still be found.
mock.game.heap.writeUInt32LE(0, GAME.vars.score);
const zero = new SnapshotScan(() => dbg, GAME.pid, kind);
await zero.first(regions, compareKind('unknown'), new Uint8Array(0), () => {});
mock.game.heap.writeUInt32LE(50, GAME.vars.score);
await zero.next(compareKind('increased'), new Uint8Array(0), () => {});
assert.equal(zero.matches, 1);
assert.equal((await zero.hits(1))[0].address, GAME.heapBase + BigInt(GAME.vars.score));
await zero.end();
mock.game.heap.writeUInt32LE(0, GAME.vars.score);
// The snapshot lives on one connection; a different one is told plainly.
const scan2 = new SnapshotScan(() => dbg, GAME.pid, kind);
await scan2.first(regions, compareKind('unknown'), new Uint8Array(0), () => {});
const dbg2 = await connect();
const moved = new SnapshotScan(() => dbg2, GAME.pid, kind);
await assert.rejects(moved.next(compareKind('changed'), new Uint8Array(0), () => {}), /Start a new search/);
mock.game.heap.writeUInt32LE(100, GAME.vars.health);
dbg.close();
dbg2.close();
});
test('script API: read, write, addresses, patterns, pointers, calls, other entries', async () => {
const { dbg, ctx } = await context();
const toggled = [];
const api = { setEntry: async (name, on) => void toggled.push([name, on]) };
const call = (method, ...args) => handleScriptCall(ctx, api, method, args);
const health = await call('pointer', 'game+10100', [0x340]);
assert.equal(health, HEALTH);
assert.equal(await call('read', health, 'u32'), 100);
await call('write', health, 'u32', 250);
assert.equal(mock.game.heap.readUInt32LE(GAME.vars.health), 250);
await call('write', health, 'u32', 100);
assert.equal(await call('read', GAME.heapBase + BigInt(GAME.vars.gold), 'float'), 2500);
assert.equal(typeof (await call('read', GAME.dataBase + 0x100n, 'u64')), 'bigint');
assert.equal(await call('address', 'game+1000'), SITE);
assert.equal(await call('address', { kind: 'module', offset: '1000' }), SITE);
assert.equal(await call('find', '89 81 90 03 00 00'), SITE);
assert.equal(await call('find', 'DE AD BE EF 00 11'), null);
assert.equal(await call('readBytes', SITE, 6), '89 81 90 03 00 00');
await call('writeBytes', SITE, '90 90 90 90 90 90');
assert.equal(bytesToHex(mock.game.image.subarray(0x1000, 0x1006)), '909090909090');
await call('writeBytes', SITE, '898190030000');
assert.equal(await call('call', 'game+4000', [40, 2n]), 42n);
await call('enable', 'Infinite health');
await call('disable', 'Infinite health');
assert.deepEqual(toggled, [['Infinite health', true], ['Infinite health', false]]);
await call('notify', 'hello from a script');
assert.equal(mock.state.notifications.at(-1), 'hello from a script');
await assert.rejects(call('readBytes', SITE, 0), /between 1 and/);
await assert.rejects(call('launchMissiles'), /Unknown script function/);
dbg.close();
});
test('own tables: export, import, and what gets flagged or left out', () => {
const table = emptyTable('PPSA99999', '01.000.000', 'Demo');
table.entries.push(
{ id: '1', type: 'patch', name: 'P', at: { kind: 'module', offset: '1000' }, on: '9090', off: '8981' },
{ id: '2', type: 'patch', name: 'Sig', at: { kind: 'signature', pattern: '89 81', offset: 0 }, on: '9090' },
{ id: '3', type: 'value', name: 'Temp', at: { kind: 'address', address: '880012340' }, valueType: 'u32', value: '1', freeze: false },
{ id: '4', type: 'script', name: 'S', code: 'cs.log(1)' },
{ id: '5', type: 'inject', name: 'I', at: { kind: 'module', offset: '1000' }, code: 'nop', placement: 'before' },
);
const text = exportOwnTable(table);
assert.ok(!text.includes('"id"'));
const back = parseOwnTable(text);
assert.deepEqual(back.entries.map((e) => e.name), ['P', 'Sig', 'S', 'I'], 'raw-address entries are not exported');
assert.deepEqual(back.entries.map((e) => !!e.unreviewed), [false, false, true, true], 'anything that runs code needs a look first');
assert.ok(back.entries.every((e) => e.id && e.id.length >= 6));
const community = exportCommunityTable(table);
assert.equal(community.included, 1);
assert.equal(community.skipped, 4);
assert.deepEqual(JSON.parse(community.text).mods[0].memory[0], { offset: '1000', on: '9090', off: '8981' });
assert.throws(() => parseOwnTable('{"mods":[]}'), /not a CheatSpecter table/);
assert.throws(() => parseOwnTable('nope'), /not valid JSON/);
});
test('a patch already in the game is shown as on and can be switched off', async () => {
const { dbg, ctx } = await context();
const entry = { id: 'adopt1', name: 'Ammo', type: 'patch', at: { kind: 'module', offset: '0x2040' }, on: '909090', off: 'FF4B28' };
await dbg.write(GAME.pid, GAME.imageBase + 0x2040n, hexToBytes('909090'));
const runner = new TableRunner(ctx);
assert.equal(runner.isOn('adopt1'), false);
assert.equal(await runner.adopt([entry]), true);
assert.equal(runner.isOn('adopt1'), true);
assert.equal(await runner.adopt([entry]), false, 'nothing new the second time');
await runner.disable(entry);
assert.equal(bytesToHex(mock.game.image.subarray(0x2040, 0x2043)), 'FF4B28');
assert.equal(await new TableRunner(ctx).adopt([entry]), false, 'off stays off');
});
test('one switch can change several places, all or nothing', async () => {
const { ctx } = await context();
const runner = new TableRunner(ctx);
const multi = {
id: 'multi1', name: 'Two places', type: 'patch',
at: { kind: 'module', offset: '0x1000' }, on: '909090909090', off: '898190030000',
more: [{ at: { kind: 'signature', pattern: 'FF 4B 28', offset: 0 }, on: '909090', off: 'FF4B28' }],
};
assert.match(describeEntry(multi), /and 1 more place$/);
await runner.enable(multi);
assert.equal(bytesToHex(mock.game.image.subarray(0x1000, 0x1006)), '909090909090');
assert.equal(bytesToHex(mock.game.image.subarray(0x2040, 0x2043)), '909090');
await runner.disable(multi);
assert.equal(bytesToHex(mock.game.image.subarray(0x1000, 0x1006)), '898190030000');
assert.equal(bytesToHex(mock.game.image.subarray(0x2040, 0x2043)), 'FF4B28');
// The second place does not fit: nothing is written, not even the first.
const bad = { ...multi, id: 'multi2', more: [{ at: { kind: 'module', offset: '0x2040' }, on: '909090', off: 'AABBCC' }] };
await assert.rejects(runner.enable(bad), MismatchError);
assert.equal(bytesToHex(mock.game.image.subarray(0x1000, 0x1006)), '898190030000');
// Shown as on only when every place is already applied.
const both = { ...multi, id: 'multi3', more: [{ at: { kind: 'module', offset: '0x2040' }, on: '909090', off: 'FF4B28' }] };
mock.game.image.set(hexToBytes('909090909090'), 0x1000);
assert.equal(await new TableRunner(ctx).adopt([both]), false);
mock.game.image.set(hexToBytes('909090'), 0x2040);
const fresh = new TableRunner(ctx);
assert.equal(await fresh.adopt([both]), true);
await fresh.disable(both);
assert.equal(bytesToHex(mock.game.image.subarray(0x1000, 0x1006)), '898190030000');
assert.equal(bytesToHex(mock.game.image.subarray(0x2040, 0x2043)), 'FF4B28');
// The GoldHEN export carries every place.
const out = JSON.parse(exportCommunityTable({ ...emptyTable('PPSA99999', '01.000.000'), entries: [both] }).text);
assert.equal(out.mods[0].memory.length, 2);
// And the file format keeps them.
const back = parseOwnTable(exportOwnTable({ ...emptyTable('PPSA99999', '01.000.000'), entries: [multi] }));
assert.equal(back.entries[0].more.length, 1);
});
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"strict": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"skipLibCheck": true,
"jsx": "react-jsx",
"types": ["vite/client"],
"baseUrl": ".",
"paths": { "@/*": ["./src/*"] }
},
"include": ["src"]
}
+26
View File
@@ -0,0 +1,26 @@
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';
// `npm run dev` runs the bridge on 8744 and Vite on 5173; these proxies make
// the dev server look like the bridge to the app.
const bridge = 'http://127.0.0.1:8744';
export default defineConfig({
// Relative asset paths, so the built app works from any folder, including
// whatever path the on-console payload ends up serving it from.
base: './',
plugins: [react(), tailwindcss()],
resolve: { alias: { '@': path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'src') } },
build: { target: 'es2022', sourcemap: false, chunkSizeWarningLimit: 700 },
server: {
host: true,
proxy: {
'/api': bridge,
'/local-cheats': bridge,
'/ws': { target: bridge, ws: true },
},
},
});