Initial commit xmarticaims
This commit is contained in:
@@ -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>.
|
||||
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"name" : "wp-media/mcp-oauth",
|
||||
"description" : "MCP OAuth layer for the WordPress MCP Adapter",
|
||||
"type" : "library",
|
||||
"keywords" : ["wordpress", "wp", "plugin"],
|
||||
"homepage" : "https://github.com/wp-media/mcp-oauth",
|
||||
"license" : "GPL-2.0+",
|
||||
"authors" : [
|
||||
{
|
||||
"name": "WP Media",
|
||||
"email": "contact@wp-media.me"
|
||||
}
|
||||
],
|
||||
"config": {
|
||||
"sort-packages": true,
|
||||
"allow-plugins": {
|
||||
"dealerdirect/phpcodesniffer-composer-installer": true,
|
||||
"phpstan/extension-installer": true
|
||||
}
|
||||
},
|
||||
"require": {
|
||||
"php" : ">=7.4",
|
||||
"wp-media/apply-filters-typed": "^1.0",
|
||||
"wordpress/mcp-adapter": "^0.5"
|
||||
},
|
||||
"require-dev": {
|
||||
"php": ">=7.4",
|
||||
"dealerdirect/phpcodesniffer-composer-installer": "^1",
|
||||
"phpcompatibility/phpcompatibility-wp": "^2.0",
|
||||
"php-stubs/wordpress-tests-stubs": "^6.8",
|
||||
"phpstan/extension-installer": "^1.4",
|
||||
"phpstan/phpstan-mockery": "^2.0",
|
||||
"phpstan/phpstan-phpunit": "^2.0",
|
||||
"szepeviktor/phpstan-wordpress": "^2.0",
|
||||
"roave/security-advisories": "dev-master",
|
||||
"wp-coding-standards/wpcs": "^3",
|
||||
"wp-media/phpunit": "^3"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"WPMedia\\MCP\\OAuth\\": "inc/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"WPMedia\\MCP\\OAuth\\Tests\\": "Tests/"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"phpcs": "vendor/bin/phpcs",
|
||||
"phpcs:fix": "vendor/bin/phpcbf",
|
||||
"phpstan": "vendor/bin/phpstan analyze --memory-limit=2G",
|
||||
"test-unit": "vendor/bin/phpunit --testsuite unit --colors=always --configuration \"Tests/Unit/phpunit.xml.dist\"",
|
||||
"test-integration": "vendor/bin/phpunit --testsuite integration --colors=always --configuration \"Tests/Integration/phpunit.xml.dist\"",
|
||||
"run-tests": [
|
||||
"@test-unit",
|
||||
"@test-integration"
|
||||
]
|
||||
}
|
||||
}
|
||||
Vendored
+164
@@ -0,0 +1,164 @@
|
||||
<?php
|
||||
/**
|
||||
* Post-login Authorization Callback — Consent Screen.
|
||||
*
|
||||
* Handles GET /oauth/authorize-callback — called by WordPress after the user
|
||||
* authenticates. Looks up the state transient (which already carries the
|
||||
* validated client display data captured at authorize time), refreshes the
|
||||
* transient TTL to give the user time to read the screen, then renders a
|
||||
* standalone HTML consent page.
|
||||
*
|
||||
* The user's Allow/Deny choice is handled by ConsentEndpoint (POST /oauth/consent).
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
use WPMedia\MCP\OAuth\Logging\McpLogger;
|
||||
use WPMedia\MCP\OAuth\Views\Render;
|
||||
|
||||
/**
|
||||
* Authorize Callback — renders the consent screen.
|
||||
*/
|
||||
class AuthorizeCallback {
|
||||
/**
|
||||
* How long (seconds) the state transient lives once the consent screen is shown.
|
||||
* Replaces the original 60 s authorize-window TTL so the user has time to decide.
|
||||
*/
|
||||
const CONSENT_TTL = 300;
|
||||
|
||||
/**
|
||||
* View renderer.
|
||||
*
|
||||
* @var Render
|
||||
*/
|
||||
private Render $render;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param Render $render View renderer.
|
||||
*/
|
||||
public function __construct( Render $render ) {
|
||||
$this->render = $render;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the post-login callback — show the consent screen.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle_request(): void {
|
||||
$state = sanitize_text_field( wp_unslash( $_GET['state'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- OAuth state token echoed back by the login redirect, not a WP nonce-protected form.
|
||||
|
||||
McpLogger::log(
|
||||
'CALLBACK',
|
||||
'authorize-callback received',
|
||||
[
|
||||
'is_logged_in' => is_user_logged_in() ? 'yes' : 'no',
|
||||
'user_id' => is_user_logged_in() ? get_current_user_id() : 0,
|
||||
'has_state' => '' !== $state ? 'yes' : 'no',
|
||||
'remote_addr' => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
|
||||
]
|
||||
);
|
||||
|
||||
if ( ! is_user_logged_in() ) {
|
||||
McpLogger::log( 'CALLBACK', 'rejected: user not logged in' );
|
||||
wp_die( esc_html__( 'You must be logged in to authorise an MCP session.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 401 ] );
|
||||
}
|
||||
|
||||
if ( '' === $state ) {
|
||||
McpLogger::log( 'CALLBACK', 'rejected: missing state' );
|
||||
wp_die( esc_html__( 'Missing state parameter.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
$state_key = 'mcp_oauth_state_' . $state;
|
||||
$state_data = get_transient( $state_key );
|
||||
|
||||
if ( false === $state_data || ! is_array( $state_data ) ) {
|
||||
McpLogger::log( 'CALLBACK', 'rejected: state transient not found or expired', [ 'state' => $state ] );
|
||||
wp_die( esc_html__( 'Invalid or expired state. Please restart the authorization flow.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
// Client display data was captured and validated by AuthorizeEndpoint and
|
||||
// stored in the state transient. Reusing it avoids a second CIMD lookup —
|
||||
// no network round-trip, and no spurious failure if the publisher is
|
||||
// briefly unreachable between login and consent.
|
||||
$client_id = (string) ( $state_data['client_id'] ?? '' );
|
||||
$client = [
|
||||
'client_id' => $client_id,
|
||||
'client_name' => (string) ( $state_data['client_name'] ?? '' ),
|
||||
'client_uri' => (string) ( $state_data['client_uri'] ?? '' ),
|
||||
'verified' => ! empty( $state_data['verified'] ),
|
||||
'publisher' => (string) ( $state_data['publisher'] ?? '' ),
|
||||
];
|
||||
|
||||
// Refresh state TTL — the user now has CONSENT_TTL seconds to decide.
|
||||
set_transient( $state_key, $state_data, self::CONSENT_TTL );
|
||||
|
||||
McpLogger::log(
|
||||
'CALLBACK',
|
||||
'showing consent screen',
|
||||
[
|
||||
'user_id' => get_current_user_id(),
|
||||
'client_id' => $client_id,
|
||||
'client_name' => $client['client_name'],
|
||||
'verified' => $client['verified'] ? 'yes' : 'no',
|
||||
]
|
||||
);
|
||||
|
||||
$this->render_consent_screen( $state, $client );
|
||||
}
|
||||
|
||||
/**
|
||||
* Assemble the consent-screen view model and render it.
|
||||
*
|
||||
* @param string $state OAuth state token.
|
||||
* @param array<string, mixed> $client Resolved CIMD client record.
|
||||
* @return void
|
||||
*/
|
||||
private function output_consent_screen( string $state, array $client ): void {
|
||||
nocache_headers();
|
||||
|
||||
// Escaped at each output site inside the template. URLs are esc_url'd
|
||||
// here since they're only ever emitted into href/action attributes.
|
||||
$client_name = (string) ( $client['client_name'] ?? '' );
|
||||
$client_id = esc_url( (string) ( $client['client_id'] ?? '' ) );
|
||||
$client_uri = esc_url( (string) ( $client['client_uri'] ?? '' ) );
|
||||
$verified = ! empty( $client['verified'] );
|
||||
$publisher = (string) ( $client['publisher'] ?? '' );
|
||||
$site_name = (string) get_bloginfo( 'name' );
|
||||
$consent_url = esc_url( home_url( '/oauth/consent' ) ); // Rewrite endpoint: home_url(), not get_site_url().
|
||||
|
||||
// The display name links to client_uri if available, otherwise client_id.
|
||||
$display_href = '' !== $client_uri ? $client_uri : $client_id;
|
||||
|
||||
$this->render->view(
|
||||
'consent-screen',
|
||||
[
|
||||
'state' => $state,
|
||||
'client_name' => $client_name,
|
||||
'client_id' => $client_id,
|
||||
'client_uri' => $client_uri,
|
||||
'verified' => $verified,
|
||||
'publisher' => $publisher,
|
||||
'site_name' => $site_name,
|
||||
'consent_url' => $consent_url,
|
||||
'display_href' => $display_href,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the consent screen, then terminate the request.
|
||||
*
|
||||
* @param string $state OAuth state token.
|
||||
* @param array<string, mixed> $client Resolved CIMD client record.
|
||||
* @return void
|
||||
*/
|
||||
private function render_consent_screen( string $state, array $client ): void {
|
||||
$this->output_consent_screen( $state, $client );
|
||||
exit;
|
||||
}
|
||||
}
|
||||
Vendored
+275
@@ -0,0 +1,275 @@
|
||||
<?php
|
||||
/**
|
||||
* Authorization Endpoint.
|
||||
*
|
||||
* Handles GET /oauth/authorize — validates the PKCE parameters, stores the
|
||||
* challenge in a 60-second transient, then routes the browser onward: a
|
||||
* user with an existing WordPress session is redirected straight to
|
||||
* /oauth/authorize-callback; otherwise the browser goes to the WordPress
|
||||
* login form first, and WordPress delivers the user back to
|
||||
* /oauth/authorize-callback after a successful login, where the auth code
|
||||
* is issued.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
use WPMedia\MCP\OAuth\Logging\McpLogger;
|
||||
|
||||
/**
|
||||
* Authorize Endpoint.
|
||||
*/
|
||||
class AuthorizeEndpoint {
|
||||
/**
|
||||
* Transient TTL for the state parameter (seconds).
|
||||
*/
|
||||
const STATE_TTL = 60;
|
||||
|
||||
/**
|
||||
* CIMD resolver used to dereference and validate the client_id URL.
|
||||
*
|
||||
* @var CimdResolver
|
||||
*/
|
||||
private CimdResolver $resolver;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param CimdResolver $resolver CIMD resolver.
|
||||
*/
|
||||
public function __construct( CimdResolver $resolver ) {
|
||||
$this->resolver = $resolver;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an authorization request.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle_request(): void {
|
||||
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- OAuth 2.1 authorization request from an external client; CSRF protection is provided by the state parameter and PKCE, not a WP nonce.
|
||||
$client_id = esc_url_raw( wp_unslash( $_GET['client_id'] ?? '' ) );
|
||||
$redirect_uri = esc_url_raw( wp_unslash( $_GET['redirect_uri'] ?? '' ) );
|
||||
$response_type = sanitize_text_field( wp_unslash( $_GET['response_type'] ?? '' ) );
|
||||
$code_challenge = sanitize_text_field( wp_unslash( $_GET['code_challenge'] ?? '' ) );
|
||||
$code_challenge_method = sanitize_text_field( wp_unslash( $_GET['code_challenge_method'] ?? '' ) );
|
||||
$state = sanitize_text_field( wp_unslash( $_GET['state'] ?? '' ) );
|
||||
// phpcs:enable WordPress.Security.NonceVerification.Recommended
|
||||
|
||||
McpLogger::log(
|
||||
'AUTHORIZE',
|
||||
'authorization request received',
|
||||
[
|
||||
'response_type' => $response_type,
|
||||
'client_id' => $client_id,
|
||||
'redirect_uri' => $redirect_uri,
|
||||
'code_challenge_method' => $code_challenge_method,
|
||||
'has_code_challenge' => '' !== $code_challenge ? 'yes' : 'no',
|
||||
'has_state' => '' !== $state ? 'yes' : 'no',
|
||||
'remote_addr' => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
|
||||
]
|
||||
);
|
||||
|
||||
// Validate the client and redirect_uri BEFORE using redirect_uri in any redirect.
|
||||
// Per OAuth 2.1 §7.5.2 and RFC 6749 §10.15, the AS MUST NOT redirect to a URI
|
||||
// that has not been positively validated against a registered client.
|
||||
|
||||
if ( '' === $client_id ) {
|
||||
McpLogger::log( 'AUTHORIZE', 'rejected: missing client_id' );
|
||||
wp_die( esc_html__( 'client_id is required.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
$client = $this->resolver->resolve( $client_id );
|
||||
if ( null === $client ) {
|
||||
McpLogger::log( 'AUTHORIZE', 'rejected: client_id could not be resolved via CIMD', [ 'client_id' => $client_id ] );
|
||||
wp_die( esc_html__( 'Unknown OAuth client.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
if ( empty( $client['verified'] ) ) {
|
||||
McpLogger::log( 'AUTHORIZE', 'rejected: client not a verified publisher', [ 'client_id' => $client_id ] );
|
||||
wp_die( esc_html__( 'This OAuth client is not a verified publisher.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
if ( '' === $redirect_uri ) {
|
||||
McpLogger::log( 'AUTHORIZE', 'rejected: missing redirect_uri' );
|
||||
wp_die( esc_html__( 'redirect_uri is required.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
if ( ! $this->redirect_uri_matches( $redirect_uri, $client['redirect_uris'] ) ) {
|
||||
McpLogger::log(
|
||||
'AUTHORIZE',
|
||||
'rejected: redirect_uri mismatch',
|
||||
[
|
||||
'provided' => $redirect_uri,
|
||||
'registered' => $client['redirect_uris'],
|
||||
]
|
||||
);
|
||||
wp_die( esc_html__( 'redirect_uri does not match registered value.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
// redirect_uri is now validated — remaining errors may safely redirect to it.
|
||||
|
||||
if ( 'code' !== $response_type ) {
|
||||
McpLogger::log( 'AUTHORIZE', 'rejected: unsupported response_type', [ 'response_type' => $response_type ] );
|
||||
$this->send_error( $redirect_uri, 'unsupported_response_type', $state );
|
||||
return;
|
||||
}
|
||||
|
||||
if ( '' === $code_challenge || 'S256' !== $code_challenge_method ) {
|
||||
McpLogger::log(
|
||||
'AUTHORIZE',
|
||||
'rejected: missing or invalid PKCE params',
|
||||
[
|
||||
'has_code_challenge' => '' !== $code_challenge ? 'yes' : 'no',
|
||||
'code_challenge_method' => $code_challenge_method,
|
||||
]
|
||||
);
|
||||
$this->send_error( $redirect_uri, 'invalid_request', $state );
|
||||
return;
|
||||
}
|
||||
|
||||
// OAuth 2.1 §4.1.1 requires state; reject rather than generate silently.
|
||||
// A server-generated state never reaches the client before the redirect,
|
||||
// so the client cannot validate it on return — providing no CSRF protection.
|
||||
if ( '' === $state ) {
|
||||
McpLogger::log( 'AUTHORIZE', 'rejected: state parameter is required' );
|
||||
$this->send_error( $redirect_uri, 'invalid_request', '' );
|
||||
return;
|
||||
}
|
||||
|
||||
// Persist the validated client display data alongside the PKCE state so the
|
||||
// consent screen can be rendered after login without a second CIMD fetch.
|
||||
set_transient(
|
||||
'mcp_oauth_state_' . $state,
|
||||
[
|
||||
'client_id' => $client_id,
|
||||
'client_name' => (string) ( $client['client_name'] ?? '' ),
|
||||
'client_uri' => (string) ( $client['client_uri'] ?? '' ),
|
||||
// Already guaranteed truthy - the 'client not a verified publisher' guard above exits otherwise.
|
||||
'verified' => true,
|
||||
'publisher' => (string) ( $client['publisher'] ?? '' ),
|
||||
'redirect_uri' => $redirect_uri,
|
||||
'code_challenge' => $code_challenge,
|
||||
'code_challenge_method' => $code_challenge_method,
|
||||
'state' => $state,
|
||||
],
|
||||
self::STATE_TTL
|
||||
);
|
||||
|
||||
// home_url(): the callback is a rewrite endpoint served from the Site Address,
|
||||
// so it must match home_url() and not get_site_url() on split-directory installs.
|
||||
$callback_url = add_query_arg( 'state', rawurlencode( $state ), home_url( '/oauth/authorize-callback' ) );
|
||||
|
||||
if ( is_user_logged_in() ) {
|
||||
McpLogger::log(
|
||||
'AUTHORIZE',
|
||||
'existing session, skipping login',
|
||||
[
|
||||
'state' => $state,
|
||||
'callback_url' => $callback_url,
|
||||
]
|
||||
);
|
||||
wp_redirect( $callback_url ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- server-constructed home_url() target.
|
||||
exit;
|
||||
}
|
||||
|
||||
$login_url = wp_login_url( $callback_url );
|
||||
|
||||
McpLogger::log(
|
||||
'AUTHORIZE',
|
||||
'redirecting to login',
|
||||
[
|
||||
'state' => $state,
|
||||
'callback_url' => $callback_url,
|
||||
]
|
||||
);
|
||||
|
||||
wp_redirect( $login_url ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether a provided redirect_uri matches a registered one.
|
||||
*
|
||||
* Non-loopback clients require an exact match. Loopback clients (native
|
||||
* apps per RFC 8252) are matched port-agnostically: the ephemeral port
|
||||
* varies per session, so scheme, host, and path must match but the port is
|
||||
* ignored. The exemption is constrained to the literal loopback hosts over
|
||||
* http so it cannot widen open-redirect exposure for normal clients.
|
||||
*
|
||||
* @param string $provided The redirect_uri supplied in the request.
|
||||
* @param string[] $registered The redirect URIs from the client metadata.
|
||||
* @return bool
|
||||
*/
|
||||
private function redirect_uri_matches( string $provided, array $registered ): bool {
|
||||
if ( in_array( $provided, $registered, true ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$provided_parts = wp_parse_url( $provided );
|
||||
if ( ! is_array( $provided_parts ) || ! $this->is_loopback( $provided_parts ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ( $registered as $candidate ) {
|
||||
$candidate_parts = wp_parse_url( (string) $candidate );
|
||||
if ( ! is_array( $candidate_parts ) || ! $this->is_loopback( $candidate_parts ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
( $provided_parts['scheme'] ?? '' ) === ( $candidate_parts['scheme'] ?? '' )
|
||||
&& ( $provided_parts['host'] ?? '' ) === ( $candidate_parts['host'] ?? '' )
|
||||
&& ( $provided_parts['path'] ?? '' ) === ( $candidate_parts['path'] ?? '' )
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a parsed URL points at a loopback address over http.
|
||||
*
|
||||
* Covers IPv4 (127.0.0.1), hostname (localhost), and IPv6 (::1) loopback
|
||||
* addresses per RFC 8252 §8.3. Only plain HTTP is permitted — HTTPS
|
||||
* loopback is not exempted to avoid widening open-redirect exposure for
|
||||
* normal (non-native-app) clients. wp_parse_url() strips the brackets
|
||||
* from IPv6 literals, so the host value is '::1', not '[::1]'.
|
||||
*
|
||||
* @param array<string, mixed> $parts Parsed URL components from wp_parse_url().
|
||||
* @return bool
|
||||
*/
|
||||
private function is_loopback( array $parts ): bool {
|
||||
$scheme = (string) ( $parts['scheme'] ?? '' );
|
||||
$host = (string) ( $parts['host'] ?? '' );
|
||||
|
||||
return 'http' === $scheme && in_array( $host, [ '127.0.0.1', 'localhost', '::1' ], true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirect the client to redirect_uri with an error parameter.
|
||||
*
|
||||
* @param string $redirect_uri Destination URI (may be empty on early failure).
|
||||
* @param string $error OAuth error code.
|
||||
* @param string $state State token echoed back to the client.
|
||||
* @return void
|
||||
*/
|
||||
private function send_error( string $redirect_uri, string $error, string $state ): void {
|
||||
if ( '' !== $redirect_uri ) {
|
||||
$params = [
|
||||
'error' => $error,
|
||||
'iss' => home_url(),
|
||||
];
|
||||
if ( '' !== $state ) {
|
||||
$params['state'] = $state;
|
||||
}
|
||||
wp_redirect( add_query_arg( $params, $redirect_uri ) ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- redirecting to the client's own registered redirect_uri, already validated against the CIMD allowlist; not a same-site redirect.
|
||||
exit;
|
||||
}
|
||||
|
||||
wp_die( esc_html( $error ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
}
|
||||
+363
@@ -0,0 +1,363 @@
|
||||
<?php
|
||||
/**
|
||||
* Client ID Metadata Document (CIMD) resolver.
|
||||
*
|
||||
* Replaces Dynamic Client Registration (RFC 7591). Instead of pre-registering
|
||||
* a client and minting a client_id/secret, the client presents an HTTPS URL as
|
||||
* its client_id; this resolver dereferences that URL, validates the returned
|
||||
* metadata document, and produces a normalised client record compatible with
|
||||
* the one AuthorizeEndpoint previously read from ClientRegistration::get_client().
|
||||
*
|
||||
* CIMD is the default client-registration model in the 2025-11-25 MCP
|
||||
* specification (IETF OAuth WG, adopted October 2025).
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
use WPMedia\MCP\OAuth\Logging\McpLogger;
|
||||
|
||||
class CimdResolver {
|
||||
/**
|
||||
* Maximum size (bytes) of a metadata document we will read.
|
||||
*/
|
||||
const MAX_DOCUMENT_BYTES = 5120;
|
||||
|
||||
/**
|
||||
* HTTP request timeout (seconds) for fetching a document.
|
||||
*/
|
||||
const FETCH_TIMEOUT = 5;
|
||||
|
||||
/**
|
||||
* Transient key prefix for cached, validated documents.
|
||||
*/
|
||||
const CACHE_PREFIX = 'mcp_cimd_';
|
||||
|
||||
/**
|
||||
* Grant types this server supports.
|
||||
*/
|
||||
const SUPPORTED_GRANT_TYPES = [ 'authorization_code', 'refresh_token' ];
|
||||
|
||||
/**
|
||||
* Trusted-publisher verifier.
|
||||
*
|
||||
* @var ClaudeClientVerifier
|
||||
*/
|
||||
private ClaudeClientVerifier $verifier;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param ClaudeClientVerifier $verifier Trusted-publisher verifier.
|
||||
*/
|
||||
public function __construct( ClaudeClientVerifier $verifier ) {
|
||||
$this->verifier = $verifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a client_id URL into a normalised client record.
|
||||
*
|
||||
* @param string $client_id The client_id URL presented by the client.
|
||||
* @return array<string, mixed>|null Normalised client record, or null on any failure.
|
||||
*/
|
||||
public function resolve( string $client_id ): ?array {
|
||||
if ( ! $this->is_valid_client_id_url( $client_id ) ) {
|
||||
McpLogger::log( 'CIMD', 'rejected: invalid client_id url', [ 'client_id' => $client_id ] );
|
||||
return null;
|
||||
}
|
||||
|
||||
// Gate the network fetch on the trusted-publisher host allowlist. The
|
||||
// authorize endpoint is unauthenticated, so dereferencing an arbitrary
|
||||
// client_id URL would let any caller use this server as an outbound
|
||||
// fetch proxy and pollute the transient cache. Only allowlisted hosts
|
||||
// are ever fetched; exact client_id verification still happens later.
|
||||
if ( ! $this->verifier->is_trusted_host( $client_id ) ) {
|
||||
McpLogger::log( 'CIMD', 'rejected: client_id host not in trusted-publisher allowlist', [ 'client_id' => $client_id ] );
|
||||
return null;
|
||||
}
|
||||
|
||||
$cached = $this->cache_get( $client_id );
|
||||
if ( null !== $cached ) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
$fetched = $this->fetch_document( $client_id );
|
||||
if ( null === $fetched ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$record = $this->validate_document( $fetched['doc'], $client_id );
|
||||
if ( null === $record ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$verification = $this->verifier->verify( $client_id, $fetched['doc'] );
|
||||
$record['verified'] = (bool) $verification['verified'];
|
||||
$record['publisher'] = (string) $verification['publisher'];
|
||||
|
||||
$this->cache_set( $client_id, $record, $fetched['ttl'] );
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the shape of a client_id URL per the CIMD spec.
|
||||
*
|
||||
* Requires an HTTPS URL with a path and no fragment or userinfo.
|
||||
*
|
||||
* @param string $client_id The client_id URL.
|
||||
* @return bool
|
||||
*/
|
||||
private function is_valid_client_id_url( string $client_id ): bool {
|
||||
if ( '' === $client_id ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$parts = wp_parse_url( $client_id );
|
||||
|
||||
if ( ! is_array( $parts ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( 'https' !== ( $parts['scheme'] ?? '' ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( empty( $parts['host'] ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$path = (string) ( $parts['path'] ?? '' );
|
||||
if ( '' === $path || '/' === $path ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( isset( $parts['fragment'] ) || isset( $parts['user'] ) || isset( $parts['pass'] ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a metadata document with SSRF guards and a size cap.
|
||||
*
|
||||
* @param string $url The client_id URL.
|
||||
* @return array{doc: array<string, mixed>, ttl: int}|null Decoded document and cache TTL, or null on failure.
|
||||
*/
|
||||
private function fetch_document( string $url ) {
|
||||
$response = wp_safe_remote_get(
|
||||
$url,
|
||||
[
|
||||
'timeout' => self::FETCH_TIMEOUT,
|
||||
'redirection' => 0,
|
||||
'limit_response_size' => self::MAX_DOCUMENT_BYTES,
|
||||
'headers' => [ 'Accept' => 'application/json' ],
|
||||
]
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
McpLogger::log(
|
||||
'CIMD',
|
||||
'rejected: fetch failed',
|
||||
[
|
||||
'client_id' => $url,
|
||||
'error' => $response->get_error_message(),
|
||||
]
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
$status = (int) wp_remote_retrieve_response_code( $response );
|
||||
if ( 200 !== $status ) {
|
||||
McpLogger::log(
|
||||
'CIMD',
|
||||
'rejected: non-200 status',
|
||||
[
|
||||
'client_id' => $url,
|
||||
'status' => $status,
|
||||
]
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
$body = (string) wp_remote_retrieve_body( $response );
|
||||
if ( strlen( $body ) > self::MAX_DOCUMENT_BYTES ) {
|
||||
McpLogger::log(
|
||||
'CIMD',
|
||||
'rejected: document too large',
|
||||
[
|
||||
'client_id' => $url,
|
||||
'bytes' => strlen( $body ),
|
||||
]
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
$content_type = (string) wp_remote_retrieve_header( $response, 'content-type' );
|
||||
if ( '' !== $content_type && false === strpos( $content_type, 'application/json' ) ) {
|
||||
McpLogger::log(
|
||||
'CIMD',
|
||||
'warning: unexpected content-type',
|
||||
[
|
||||
'client_id' => $url,
|
||||
'content_type' => $content_type,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
$doc = json_decode( $body, true );
|
||||
if ( ! is_array( $doc ) || empty( $doc ) ) {
|
||||
McpLogger::log( 'CIMD', 'rejected: body is not a JSON object', [ 'client_id' => $url ] );
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'doc' => $doc,
|
||||
'ttl' => $this->parse_ttl( (string) wp_remote_retrieve_header( $response, 'cache-control' ) ),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a metadata document and build a normalized client record.
|
||||
*
|
||||
* @param array<string, mixed> $doc The decoded metadata document.
|
||||
* @param string $url The client_id URL it was fetched from.
|
||||
* @return array<string, mixed>|null Normalized record, or null on validation failure.
|
||||
*/
|
||||
private function validate_document( array $doc, string $url ): ?array {
|
||||
// The document's client_id MUST exactly equal the document URL.
|
||||
$doc_client_id = isset( $doc['client_id'] ) && is_string( $doc['client_id'] ) ? $doc['client_id'] : '';
|
||||
if ( '' === $doc_client_id || $url !== $doc_client_id ) {
|
||||
McpLogger::log(
|
||||
'CIMD',
|
||||
'rejected: client_id mismatch',
|
||||
[
|
||||
'client_id' => $url,
|
||||
'document_client_id' => $doc_client_id,
|
||||
]
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Only public clients are supported (no shared secret to authenticate).
|
||||
$auth_method = isset( $doc['token_endpoint_auth_method'] ) ? (string) $doc['token_endpoint_auth_method'] : 'none';
|
||||
if ( 'none' !== $auth_method ) {
|
||||
McpLogger::log(
|
||||
'CIMD',
|
||||
'rejected: unsupported token_endpoint_auth_method',
|
||||
[
|
||||
'client_id' => $url,
|
||||
'method' => $auth_method,
|
||||
]
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
// redirect_uris is required.
|
||||
$redirect_uris = $doc['redirect_uris'] ?? [];
|
||||
if ( ! is_array( $redirect_uris ) || empty( $redirect_uris ) ) {
|
||||
McpLogger::log( 'CIMD', 'rejected: missing redirect_uris', [ 'client_id' => $url ] );
|
||||
return null;
|
||||
}
|
||||
|
||||
$redirect_uris = array_values(
|
||||
array_filter(
|
||||
array_map( 'esc_url_raw', array_map( 'strval', $redirect_uris ) )
|
||||
)
|
||||
);
|
||||
|
||||
if ( empty( $redirect_uris ) ) {
|
||||
McpLogger::log( 'CIMD', 'rejected: no valid redirect_uris after sanitisation', [ 'client_id' => $url ] );
|
||||
return null;
|
||||
}
|
||||
|
||||
// grant_types: intersect with what we support; must include authorization_code.
|
||||
$requested_grants = isset( $doc['grant_types'] ) && is_array( $doc['grant_types'] )
|
||||
? array_map( 'strval', $doc['grant_types'] )
|
||||
: self::SUPPORTED_GRANT_TYPES;
|
||||
|
||||
$grant_types = array_values( array_intersect( self::SUPPORTED_GRANT_TYPES, $requested_grants ) );
|
||||
if ( ! in_array( 'authorization_code', $grant_types, true ) ) {
|
||||
McpLogger::log(
|
||||
'CIMD',
|
||||
'rejected: authorization_code grant not offered',
|
||||
[
|
||||
'client_id' => $url,
|
||||
'grant_types' => $requested_grants,
|
||||
]
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
$client_name = isset( $doc['client_name'] ) ? sanitize_text_field( (string) $doc['client_name'] ) : '';
|
||||
if ( '' === $client_name ) {
|
||||
$client_name = (string) wp_parse_url( $url, PHP_URL_HOST );
|
||||
}
|
||||
|
||||
$client_uri = isset( $doc['client_uri'] ) && is_string( $doc['client_uri'] ) ? esc_url_raw( $doc['client_uri'] ) : '';
|
||||
|
||||
return [
|
||||
'client_id' => $url,
|
||||
'client_name' => $client_name,
|
||||
'client_uri' => $client_uri,
|
||||
'redirect_uris' => $redirect_uris,
|
||||
'grant_types' => $grant_types,
|
||||
'token_endpoint_auth_method' => 'none',
|
||||
'source' => 'cimd',
|
||||
'verified' => false,
|
||||
'publisher' => '',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a max-age TTL from a Cache-Control header, clamped to a sane range.
|
||||
*
|
||||
* @param string $cache_control The Cache-Control header value.
|
||||
* @return int TTL in seconds.
|
||||
*/
|
||||
private function parse_ttl( string $cache_control ): int {
|
||||
$default = HOUR_IN_SECONDS;
|
||||
|
||||
if ( '' !== $cache_control && preg_match( '/max-age\s*=\s*(\d+)/i', $cache_control, $matches ) ) {
|
||||
$default = (int) $matches[1];
|
||||
}
|
||||
|
||||
return (int) max( 300, min( $default, DAY_IN_SECONDS ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the transient cache key for a client_id URL.
|
||||
*
|
||||
* @param string $url The client_id URL.
|
||||
* @return string
|
||||
*/
|
||||
private function cache_key( string $url ): string {
|
||||
return self::CACHE_PREFIX . md5( $url );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a cached, validated client record.
|
||||
*
|
||||
* @param string $url The client_id URL.
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
private function cache_get( string $url ): ?array {
|
||||
$cached = get_transient( $this->cache_key( $url ) );
|
||||
|
||||
return is_array( $cached ) ? $cached : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cache a validated client record. Only successful documents are ever cached.
|
||||
*
|
||||
* @param string $url The client_id URL.
|
||||
* @param array<string, mixed> $record The normalised record.
|
||||
* @param int $ttl Cache TTL in seconds.
|
||||
* @return void
|
||||
*/
|
||||
private function cache_set( string $url, array $record, int $ttl ): void {
|
||||
set_transient( $this->cache_key( $url ), $record, $ttl );
|
||||
}
|
||||
}
|
||||
Vendored
+147
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
/**
|
||||
* Built-in verification for trusted CIMD publishers.
|
||||
*
|
||||
* Client ID Metadata Documents (CIMD) let any client identify itself with an
|
||||
* HTTPS URL, but this proof of concept only authorizes clients whose metadata
|
||||
* matches a known, trusted publisher. Claude is the bundled publisher: its
|
||||
* official client_id URL, host, and loopback redirect shape are pinned here so
|
||||
* that a fetched document can be cryptographically bound to Claude rather than
|
||||
* trusted on its own say-so.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
use WPMedia\MCP\OAuth\Logging\McpLogger;
|
||||
|
||||
class ClaudeClientVerifier {
|
||||
/**
|
||||
* Verify a fetched CIMD document against the trusted-publisher allowlist.
|
||||
*
|
||||
* @param string $client_id The client_id URL the document was fetched from.
|
||||
* @param array<string, mixed> $doc The decoded, already URL-validated metadata document.
|
||||
* @return array{verified: bool, publisher: string} Verification result.
|
||||
*/
|
||||
public function verify( string $client_id, array $doc ): array {
|
||||
$unverified = [
|
||||
'verified' => false,
|
||||
'publisher' => '',
|
||||
];
|
||||
|
||||
foreach ( $this->get_trusted_publishers() as $publisher => $config ) {
|
||||
if ( $this->matches_publisher( $client_id, $doc, (array) $config ) ) {
|
||||
McpLogger::log(
|
||||
'CIMD',
|
||||
'client verified against trusted publisher',
|
||||
[
|
||||
'client_id' => $client_id,
|
||||
'publisher' => $publisher,
|
||||
]
|
||||
);
|
||||
|
||||
return [
|
||||
'verified' => true,
|
||||
'publisher' => (string) $publisher,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $unverified;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a client_id URL's host belongs to a trusted publisher.
|
||||
*
|
||||
* Used to gate the (unauthenticated) CIMD network fetch: only client_ids
|
||||
* whose host is allowlisted are ever dereferenced, so an arbitrary URL
|
||||
* cannot turn the public authorize endpoint into an outbound-request proxy
|
||||
* or fill the transient cache with junk records.
|
||||
*
|
||||
* @param string $client_id The client_id URL.
|
||||
* @return bool
|
||||
*/
|
||||
public function is_trusted_host( string $client_id ): bool {
|
||||
$host = (string) wp_parse_url( $client_id, PHP_URL_HOST );
|
||||
if ( '' === $host ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ( $this->get_trusted_publishers() as $config ) {
|
||||
if ( (string) ( ( (array) $config )['host'] ?? '' ) === $host ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the trusted-publisher allowlist.
|
||||
*
|
||||
* @return array<string, array<string, mixed>>
|
||||
*/
|
||||
private function get_trusted_publishers(): array {
|
||||
$publishers = [
|
||||
'claude' => [
|
||||
'client_ids' => [
|
||||
'https://claude.ai/oauth/claude-code-client-metadata',
|
||||
'https://claude.ai/oauth/mcp-oauth-client-metadata',
|
||||
],
|
||||
'host' => 'claude.ai',
|
||||
],
|
||||
];
|
||||
|
||||
$publishers = apply_filters_deprecated( 'rocket_mcp_trusted_publishers', [ $publishers ], '1.0.1', 'wpmedia_mcp_oauth_trusted_publishers' );
|
||||
|
||||
/**
|
||||
* Filters the trusted-publisher allowlist for MCP OAuth client verification.
|
||||
*
|
||||
* Each entry is keyed by an arbitrary publisher slug and must provide:
|
||||
* - client_ids (string[]): exact client_id URLs that are trusted for this publisher.
|
||||
* - host (string): the hostname client_id URLs must resolve to (defense in depth,
|
||||
* also used as the SSRF allowlist gate before any network fetch is made).
|
||||
*
|
||||
* This filter only ever runs server-side, with no request-derived input passed into it
|
||||
* or influencing its evaluation — it does not accept or process untrusted input. It can
|
||||
* only ADD trusted publishers; it does not bypass the exact client_id match in
|
||||
* matches_publisher() or the "verified" hard-reject in AuthorizeEndpoint::handle_request().
|
||||
*
|
||||
* @param array<string, array{client_ids: string[], host: string}> $publishers Trusted-publisher allowlist.
|
||||
* @return array<string, array{client_ids: string[], host: string}>
|
||||
*/
|
||||
return wpm_apply_filters_typed( 'array', 'wpmedia_mcp_oauth_trusted_publishers', $publishers );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a document matches a single trusted publisher.
|
||||
*
|
||||
* @param string $client_id The client_id URL.
|
||||
* @param array<string, mixed> $doc The metadata document.
|
||||
* @param array<string, mixed> $config The publisher configuration.
|
||||
* @return bool
|
||||
*/
|
||||
private function matches_publisher( string $client_id, array $doc, array $config ): bool {
|
||||
$client_ids = (array) ( $config['client_ids'] ?? [] );
|
||||
|
||||
// 1. Exact, known-good client_id URL (primary trust anchor).
|
||||
if ( ! in_array( $client_id, $client_ids, true ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 2. URL host must match the publisher host (defense in depth).
|
||||
$host = (string) wp_parse_url( $client_id, PHP_URL_HOST );
|
||||
if ( '' === $host || (string) ( $config['host'] ?? '' ) !== $host ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 3. Public-client flow only.
|
||||
// Redirect URI validation at authorize time is AuthorizeEndpoint::redirect_uri_matches()'s
|
||||
// responsibility. Checking the redirect_uri shape here would break verification when
|
||||
// the publisher's CIMD document includes additional redirect URIs for other products.
|
||||
$auth_method = (string) ( $doc['token_endpoint_auth_method'] ?? 'none' );
|
||||
|
||||
return 'none' === $auth_method;
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
/**
|
||||
* Consent Endpoint.
|
||||
*
|
||||
* Handles POST /oauth/consent — the form submission from the consent screen
|
||||
* rendered by AuthorizeCallback. Verifies the WordPress nonce, looks up and
|
||||
* consumes the state transient, then either issues an auth code (Allow) or
|
||||
* redirects back to the client with error=access_denied (Deny).
|
||||
*
|
||||
* redirect_uri is always read from the server-side state transient, never from
|
||||
* $_POST, so it cannot be manipulated by the user or a third party.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
use WPMedia\MCP\OAuth\Logging\McpLogger;
|
||||
|
||||
class ConsentEndpoint {
|
||||
/**
|
||||
* Auth-code transient TTL (seconds). Codes are single-use; the transient
|
||||
* is deleted immediately on redemption at the token endpoint.
|
||||
*/
|
||||
const CODE_TTL = 60;
|
||||
|
||||
/**
|
||||
* Handle the consent form POST.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle_request(): void {
|
||||
$request_method = isset( $_SERVER['REQUEST_METHOD'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : '';
|
||||
|
||||
if ( 'POST' !== $request_method ) {
|
||||
McpLogger::log( 'CONSENT', 'rejected: wrong method', [ 'method' => $request_method ] );
|
||||
wp_die( esc_html__( 'Method not allowed.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 405 ] );
|
||||
}
|
||||
|
||||
if ( ! is_user_logged_in() ) {
|
||||
McpLogger::log( 'CONSENT', 'rejected: user not logged in' );
|
||||
wp_die( esc_html__( 'You must be logged in to authorise an MCP session.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 401 ] );
|
||||
}
|
||||
|
||||
$state = sanitize_text_field( wp_unslash( $_POST['state'] ?? '' ) );
|
||||
$action = sanitize_text_field( wp_unslash( $_POST['mcp_action'] ?? '' ) );
|
||||
|
||||
if ( '' === $state ) {
|
||||
McpLogger::log( 'CONSENT', 'rejected: missing state' );
|
||||
wp_die( esc_html__( 'Missing state parameter.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
// Nonce verification (CSRF protection) — must happen before consuming the transient.
|
||||
check_admin_referer( 'mcp_consent_' . $state, 'mcp_consent_nonce' );
|
||||
|
||||
$state_key = 'mcp_oauth_state_' . $state;
|
||||
$state_data = get_transient( $state_key );
|
||||
|
||||
if ( false === $state_data || ! is_array( $state_data ) ) {
|
||||
McpLogger::log( 'CONSENT', 'rejected: state transient not found or expired', [ 'state' => $state ] );
|
||||
wp_die( esc_html__( 'Your session has expired. Please restart the authorization flow.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
// Atomically consume the state — one-time use only. delete_transient()
|
||||
// returns true for a single caller when requests race, so a double
|
||||
// submission cannot mint two auth codes from one consent.
|
||||
if ( ! delete_transient( $state_key ) ) {
|
||||
McpLogger::log( 'CONSENT', 'rejected: state already consumed (concurrent submission)', [ 'state' => $state ] );
|
||||
wp_die( esc_html__( 'Your session has expired. Please restart the authorization flow.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
$redirect_uri = (string) ( $state_data['redirect_uri'] ?? '' );
|
||||
$user_id = get_current_user_id();
|
||||
|
||||
if ( 'allow' !== $action ) {
|
||||
McpLogger::log(
|
||||
'CONSENT',
|
||||
'user denied access',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'client_id' => $state_data['client_id'] ?? '',
|
||||
'mcp_action' => $action,
|
||||
'redirect_uri' => $redirect_uri,
|
||||
]
|
||||
);
|
||||
|
||||
wp_redirect( // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- redirecting to the client's registered redirect_uri sourced from the server-side state transient, not user input.
|
||||
add_query_arg(
|
||||
[
|
||||
'error' => 'access_denied',
|
||||
'state' => $state,
|
||||
'iss' => home_url(),
|
||||
],
|
||||
$redirect_uri
|
||||
)
|
||||
);
|
||||
exit;
|
||||
}
|
||||
|
||||
// User allowed — issue a single-use auth code.
|
||||
$auth_code = bin2hex( random_bytes( 32 ) );
|
||||
|
||||
set_transient(
|
||||
'mcp_oauth_code_' . $auth_code,
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'client_id' => $state_data['client_id'] ?? '',
|
||||
'client_name' => $state_data['client_name'] ?? '',
|
||||
'code_challenge' => $state_data['code_challenge'] ?? '',
|
||||
'redirect_uri' => $redirect_uri,
|
||||
],
|
||||
self::CODE_TTL
|
||||
);
|
||||
|
||||
McpLogger::log(
|
||||
'CONSENT',
|
||||
'user granted access, auth code issued',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'client_id' => $state_data['client_id'] ?? '',
|
||||
'redirect_uri' => $redirect_uri,
|
||||
'code_ttl_s' => self::CODE_TTL,
|
||||
]
|
||||
);
|
||||
|
||||
wp_redirect( // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- redirecting to the client's registered redirect_uri sourced from the server-side state transient, not user input.
|
||||
add_query_arg(
|
||||
[
|
||||
'code' => $auth_code,
|
||||
'state' => $state,
|
||||
'iss' => home_url(),
|
||||
],
|
||||
$redirect_uri
|
||||
)
|
||||
);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
Vendored
+144
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
/**
|
||||
* OAuth 2.0 Discovery Endpoints.
|
||||
*
|
||||
* Registers the two RFC-mandated well-known documents so MCP clients can
|
||||
* auto-discover the authorization server metadata without hard-coding URLs.
|
||||
*
|
||||
* Paths served:
|
||||
* GET /.well-known/oauth-protected-resource (RFC 9728)
|
||||
* GET /.well-known/oauth-authorization-server (RFC 8414)
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth\Discovery;
|
||||
|
||||
use WPMedia\MCP\OAuth\Auth\Http404Trait;
|
||||
use WPMedia\MCP\OAuth\Context;
|
||||
use WPMedia\MCP\OAuth\Logging\McpLogger;
|
||||
|
||||
class Endpoints {
|
||||
|
||||
use Http404Trait;
|
||||
|
||||
/**
|
||||
* Query var name used to route discovery requests.
|
||||
*/
|
||||
const QUERY_VAR = 'mcp_oauth_discovery';
|
||||
|
||||
/**
|
||||
* OAuth server context.
|
||||
*
|
||||
* @var Context
|
||||
*/
|
||||
private Context $context;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param Context $context OAuth server context.
|
||||
*/
|
||||
public function __construct( Context $context ) {
|
||||
$this->context = $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register rewrite rules for the .well-known paths.
|
||||
*
|
||||
* Called on the 'init' action.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function add_rewrite_rules(): void {
|
||||
if ( ! $this->context->is_enabled() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
add_rewrite_rule(
|
||||
'^\\.well-known/oauth-protected-resource$',
|
||||
'index.php?' . self::QUERY_VAR . '=protected-resource',
|
||||
'top'
|
||||
);
|
||||
add_rewrite_rule(
|
||||
'^\\.well-known/oauth-authorization-server$',
|
||||
'index.php?' . self::QUERY_VAR . '=authorization-server',
|
||||
'top'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the OAuth query var to WordPress's list of recognised vars.
|
||||
*
|
||||
* @param string[] $vars Existing query vars.
|
||||
* @return string[] Modified list.
|
||||
*/
|
||||
public function add_query_vars( array $vars ): array {
|
||||
$vars[] = self::QUERY_VAR;
|
||||
|
||||
return $vars;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serve the discovery document if the request matches.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle_request(): void {
|
||||
$discovery = (string) get_query_var( self::QUERY_VAR, '' );
|
||||
|
||||
if ( '' === $discovery ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! $this->context->is_enabled() ) {
|
||||
$this->force_404();
|
||||
return;
|
||||
}
|
||||
|
||||
// Every OAuth endpoint and both .well-known documents are served through
|
||||
// rewrite rules, which resolve against home_url() (the Site Address) — the
|
||||
// same base get_rest_url() uses for the resource/audience below. Advertising
|
||||
// them under get_site_url() (the WordPress Address) would point clients at
|
||||
// the wrong location on installs where WordPress lives in its own directory
|
||||
// (siteurl !== home).
|
||||
$base_url = home_url();
|
||||
|
||||
McpLogger::log(
|
||||
'DISCOVERY',
|
||||
'request received',
|
||||
[
|
||||
'document' => $discovery,
|
||||
'remote_addr' => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
|
||||
'user_agent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '',
|
||||
]
|
||||
);
|
||||
|
||||
if ( 'protected-resource' === $discovery ) {
|
||||
$body = [
|
||||
'resource' => get_rest_url( null, 'mcp/mcp-oauth-server' ),
|
||||
'authorization_servers' => [ $base_url ],
|
||||
'bearer_methods_supported' => [ 'header' ],
|
||||
'scopes_supported' => [ 'mcp' ],
|
||||
];
|
||||
McpLogger::log( 'DISCOVERY', 'serving protected-resource document', $body );
|
||||
wp_send_json( $body );
|
||||
} elseif ( 'authorization-server' === $discovery ) {
|
||||
$body = [
|
||||
'issuer' => $base_url,
|
||||
'authorization_endpoint' => $base_url . '/oauth/authorize',
|
||||
'token_endpoint' => $base_url . '/oauth/token',
|
||||
'revocation_endpoint' => $base_url . '/oauth/revoke',
|
||||
'response_types_supported' => [ 'code' ],
|
||||
'grant_types_supported' => [ 'authorization_code', 'refresh_token' ],
|
||||
'code_challenge_methods_supported' => [ 'S256' ],
|
||||
'scopes_supported' => [ 'mcp' ],
|
||||
'token_endpoint_auth_methods_supported' => [ 'none' ],
|
||||
'client_id_metadata_document_supported' => true,
|
||||
'authorization_response_iss_parameter_supported' => true,
|
||||
];
|
||||
McpLogger::log( 'DISCOVERY', 'serving authorization-server document', $body );
|
||||
wp_send_json( $body );
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+272
@@ -0,0 +1,272 @@
|
||||
<?php
|
||||
/**
|
||||
* Site Health self-check for the .well-known OAuth discovery documents.
|
||||
*
|
||||
* On hosts that provision a physical `.well-known/acme-challenge/` directory
|
||||
* for Let's Encrypt auto-SSL (OVH, cPanel/AutoSSL, Plesk, and most managed-WP
|
||||
* hosts), the web server can 404 sibling `.well-known/oauth-*` paths before
|
||||
* WordPress ever runs — see the README "Hosting: .well-known conflicts"
|
||||
* section. No WordPress-level code change can influence that; this class is
|
||||
* a passive diagnostic only, registered as a single `direct` WordPress Site
|
||||
* Health test (the `site_status_tests` filter) that issues a loopback request
|
||||
* to both RFC discovery documents (`Endpoints`) and reports one combined
|
||||
* status.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth\Discovery;
|
||||
|
||||
use WP_Error;
|
||||
use WPMedia\MCP\OAuth\Context;
|
||||
|
||||
class HealthCheck {
|
||||
|
||||
/**
|
||||
* Site Health test key registered under the `direct` bucket.
|
||||
*/
|
||||
const TEST_KEY = 'wpmedia_mcp_oauth_wellknown_discovery';
|
||||
|
||||
/**
|
||||
* Transient key caching the combined self-check result.
|
||||
*/
|
||||
const TRANSIENT_KEY = 'wpmedia_mcp_oauth_wellknown_health_check';
|
||||
|
||||
/**
|
||||
* Cache TTL, in seconds, for the combined self-check result.
|
||||
*/
|
||||
const TRANSIENT_TTL = 5 * MINUTE_IN_SECONDS;
|
||||
|
||||
/**
|
||||
* Per-request timeout, in seconds, for each loopback discovery request.
|
||||
*/
|
||||
const FETCH_TIMEOUT = 5;
|
||||
|
||||
/**
|
||||
* Relative discovery document paths, keyed by a short display name.
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
private const DOCUMENTS = [
|
||||
'oauth-protected-resource' => '/.well-known/oauth-protected-resource',
|
||||
'oauth-authorization-server' => '/.well-known/oauth-authorization-server',
|
||||
];
|
||||
|
||||
/**
|
||||
* Status severity used to pick the combined result.
|
||||
*
|
||||
* @var array<string, int>
|
||||
*/
|
||||
private const STATUS_RANK = [
|
||||
'good' => 0,
|
||||
'recommended' => 1,
|
||||
'critical' => 2,
|
||||
];
|
||||
|
||||
/**
|
||||
* OAuth server context.
|
||||
*
|
||||
* @var Context
|
||||
*/
|
||||
private Context $context;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param Context $context OAuth server context.
|
||||
*/
|
||||
public function __construct( Context $context ) {
|
||||
$this->context = $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the combined discovery-document self-check as a `direct` Site Health test.
|
||||
*
|
||||
* @param array<string, array<string, array<string, mixed>>> $tests Existing Site Health tests, keyed by bucket ('direct'|'async').
|
||||
* @return array<string, array<string, array<string, mixed>>> Modified tests.
|
||||
*/
|
||||
public function add_test( array $tests ): array {
|
||||
$tests['direct'][ self::TEST_KEY ] = [
|
||||
'label' => __( 'MCP OAuth discovery documents', 'mcp-oauth' ),
|
||||
'test' => [ $this, 'run_self_check' ],
|
||||
];
|
||||
|
||||
return $tests;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the combined discovery-document self-check.
|
||||
*
|
||||
* @return array<string, mixed> Site Health test result (label, status, badge, description, actions, test).
|
||||
*/
|
||||
public function run_self_check(): array {
|
||||
if ( ! $this->context->is_enabled() ) {
|
||||
return $this->build_result(
|
||||
'good',
|
||||
[],
|
||||
__( 'The MCP OAuth server is intentionally disabled (the <code>wpmedia_mcp_oauth_server_enabled</code> filter returns false), so the .well-known discovery documents are not expected to be reachable.', 'mcp-oauth' )
|
||||
);
|
||||
}
|
||||
|
||||
if ( '' === (string) get_option( 'permalink_structure' ) ) {
|
||||
return $this->build_result(
|
||||
'recommended',
|
||||
[],
|
||||
__( 'The .well-known OAuth discovery documents are served through a rewrite rule, which requires a pretty permalink structure. Enable one under Settings → Permalinks, then re-check this test.', 'mcp-oauth' )
|
||||
);
|
||||
}
|
||||
|
||||
$cached = get_transient( self::TRANSIENT_KEY );
|
||||
if ( is_array( $cached ) ) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
$worst_status = 'good';
|
||||
$failing = [];
|
||||
|
||||
foreach ( self::DOCUMENTS as $name => $path ) {
|
||||
$response = wp_safe_remote_get(
|
||||
home_url( $path ),
|
||||
[
|
||||
'timeout' => self::FETCH_TIMEOUT,
|
||||
]
|
||||
);
|
||||
|
||||
$status = $this->classify( $response );
|
||||
|
||||
if ( self::STATUS_RANK[ $status ] > self::STATUS_RANK[ $worst_status ] ) {
|
||||
$worst_status = $status;
|
||||
}
|
||||
|
||||
if ( 'good' !== $status ) {
|
||||
$failing[] = $name;
|
||||
}
|
||||
}
|
||||
|
||||
$result = $this->build_result( $worst_status, $failing );
|
||||
|
||||
set_transient( self::TRANSIENT_KEY, $result, self::TRANSIENT_TTL );
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify a single document's fetch result into a Site Health status.
|
||||
*
|
||||
* @param array<string, mixed>|WP_Error $response The wp_remote_get() response array, or a WP_Error.
|
||||
* @return string One of 'good', 'recommended', 'critical'.
|
||||
*/
|
||||
private function classify( $response ): string {
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return 'recommended';
|
||||
}
|
||||
|
||||
$status_code = (int) wp_remote_retrieve_response_code( $response );
|
||||
|
||||
if ( in_array( $status_code, [ 401, 403, 407 ], true ) ) {
|
||||
return 'recommended';
|
||||
}
|
||||
|
||||
if ( 404 === $status_code ) {
|
||||
$powered_by = (string) wp_remote_retrieve_header( $response, 'x-powered-by' );
|
||||
$redirect_by = (string) wp_remote_retrieve_header( $response, 'x-redirect-by' );
|
||||
|
||||
if ( '' === $powered_by && false === stripos( $redirect_by, 'WordPress' ) ) {
|
||||
return 'critical';
|
||||
}
|
||||
|
||||
return 'recommended';
|
||||
}
|
||||
|
||||
if ( 200 === $status_code ) {
|
||||
$body = (string) wp_remote_retrieve_body( $response );
|
||||
$decoded = json_decode( $body, true );
|
||||
|
||||
if ( is_array( $decoded ) ) {
|
||||
return 'good';
|
||||
}
|
||||
}
|
||||
|
||||
return 'recommended';
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the Site Health result array for a given combined status.
|
||||
*
|
||||
* @param string $status One of 'good', 'recommended', 'critical'.
|
||||
* @param string[] $failing Display names of the documents that did not report 'good'.
|
||||
* @param string $summary Optional override for the description's leading sentence
|
||||
* (used by the disabled/plain-permalinks short-circuits).
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function build_result( string $status, array $failing, string $summary = '' ): array {
|
||||
$loopback_caveat = __( 'This check runs from the server to itself. A "Good" result here does not guarantee external clients can reach these documents: a CDN, WAF, or reverse proxy in front of the site can still 404 these paths for external traffic while the server\'s own loopback request bypasses it. Verify with an external <code>curl</code> request after applying any server-config change.', 'mcp-oauth' );
|
||||
|
||||
/*
|
||||
* The acme-challenge fingerprint is classified 'critical' internally so
|
||||
* the detailed guidance below is selected, but it is reported to Site
|
||||
* Health as 'recommended': the .well-known discovery documents are an
|
||||
* optional MCP feature, and a "critical" badge generates support tickets
|
||||
* for what is a non-blocking misconfiguration.
|
||||
*/
|
||||
$reported_status = 'critical' === $status ? 'recommended' : $status;
|
||||
|
||||
if ( '' !== $summary ) {
|
||||
$description = sprintf( '<p>%s</p>', $summary );
|
||||
$actions = sprintf( '<p>%s</p>', $loopback_caveat );
|
||||
} elseif ( 'good' === $status ) {
|
||||
$description = sprintf(
|
||||
'<p>%s</p>',
|
||||
__( 'Both .well-known OAuth discovery documents (oauth-protected-resource and oauth-authorization-server) responded with HTTP 200 and valid JSON.', 'mcp-oauth' )
|
||||
);
|
||||
$actions = sprintf( '<p>%s</p>', $loopback_caveat );
|
||||
} else {
|
||||
$document_list = implode( ', ', $failing );
|
||||
|
||||
if ( 'critical' === $status ) {
|
||||
$description = sprintf(
|
||||
'<p>%s</p>',
|
||||
sprintf(
|
||||
/* translators: %s: comma-separated list of failing discovery document names. */
|
||||
__( 'The following .well-known discovery document(s) returned a bare 404 with no WordPress-originated response header: %s. This matches the fingerprint of a physical .well-known/acme-challenge/ directory (provisioned by the host for Let\'s Encrypt auto-SSL) intercepting the request before WordPress runs — likely the cause here, though this should be confirmed against the actual .well-known/acme-challenge/ directory on the server before concluding root cause.', 'mcp-oauth' ),
|
||||
esc_html( $document_list )
|
||||
)
|
||||
);
|
||||
|
||||
$actions = sprintf(
|
||||
'<p>%s</p><p>%s</p><p>%s</p>',
|
||||
__( 'Apply the Apache or Nginx snippet from this library\'s README ("Hosting: .well-known conflicts") to re-enable routing for these two paths without touching acme-challenge/.', 'mcp-oauth' ),
|
||||
__( 'If a CDN or page cache is in front of the site, purge it after applying the fix — a stale cached 404 for these paths can otherwise persist even once the server config is corrected.', 'mcp-oauth' ),
|
||||
$loopback_caveat
|
||||
);
|
||||
} else {
|
||||
$description = sprintf(
|
||||
'<p>%s</p>',
|
||||
sprintf(
|
||||
/* translators: %s: comma-separated list of failing discovery document names. */
|
||||
__( 'The following .well-known discovery document(s) did not respond as expected: %s. This does not match the confirmed .well-known/acme-challenge/ interception fingerprint, so the cause is inconclusive from this check alone (it may be a timeout, an access wall such as HTTP Basic Auth or a WAF, or a WordPress-served error).', 'mcp-oauth' ),
|
||||
esc_html( $document_list )
|
||||
)
|
||||
);
|
||||
|
||||
$actions = sprintf(
|
||||
'<p>%s</p><p>%s</p>',
|
||||
__( 'Check your error/access logs for the requests to these paths, and rule out an authentication wall (staging HTTP Basic Auth, a WAF, or bot mitigation) before assuming a routing problem.', 'mcp-oauth' ),
|
||||
$loopback_caveat
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'label' => __( 'MCP OAuth discovery documents', 'mcp-oauth' ),
|
||||
'status' => $reported_status,
|
||||
'badge' => [
|
||||
'label' => __( 'Configuration', 'mcp-oauth' ),
|
||||
'color' => 'blue',
|
||||
],
|
||||
'description' => $description,
|
||||
'actions' => $actions,
|
||||
'test' => self::TEST_KEY,
|
||||
];
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
/**
|
||||
* Shared 404 helper for OAuth request handlers.
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
/**
|
||||
* Provides a clean 404 response for stale OAuth/discovery rewrite rules.
|
||||
*/
|
||||
trait Http404Trait {
|
||||
|
||||
/**
|
||||
* Force a clean 404 response.
|
||||
*
|
||||
* Used when a stale rewrite rule still routes a request to an OAuth or
|
||||
* discovery endpoint after the OAuth server has been disabled, before
|
||||
* rewrite rules have been flushed. Without this, WordPress's main query
|
||||
* would fall through to the homepage instead of returning a 404.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function force_404(): void {
|
||||
global $wp_query;
|
||||
$wp_query->set_404();
|
||||
status_header( 404 );
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
/**
|
||||
* JWT Helper — pure HS256 implementation with no external dependencies.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
/**
|
||||
* JWT encoder / decoder.
|
||||
*
|
||||
* Implements HS256 (HMAC-SHA256) signing. All methods are static so callers
|
||||
* never need to instantiate the class.
|
||||
*/
|
||||
class JWT {
|
||||
|
||||
/**
|
||||
* Encode a payload as a signed JWT.
|
||||
*
|
||||
* @param array<string, mixed> $payload Claims to include in the token.
|
||||
* @param string $secret HMAC signing secret.
|
||||
* @return string Signed JWT string.
|
||||
*/
|
||||
public static function encode( array $payload, string $secret ): string {
|
||||
$header = self::base64url_encode(
|
||||
(string) wp_json_encode(
|
||||
[
|
||||
'typ' => 'JWT',
|
||||
'alg' => 'HS256',
|
||||
]
|
||||
)
|
||||
);
|
||||
$body = self::base64url_encode( (string) wp_json_encode( $payload ) );
|
||||
$sig = self::base64url_encode( hash_hmac( 'sha256', $header . '.' . $body, $secret, true ) );
|
||||
|
||||
return $header . '.' . $body . '.' . $sig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode and verify a JWT.
|
||||
*
|
||||
* Returns null if the signature is invalid or (when $verify_expiry is true)
|
||||
* the token has expired. Pass false for $verify_expiry when the caller
|
||||
* needs to act on an expired token — e.g. the revocation endpoint, which
|
||||
* must accept expired tokens per RFC 7009.
|
||||
*
|
||||
* @param string $token JWT string.
|
||||
* @param string $secret HMAC signing secret.
|
||||
* @param bool $verify_expiry Whether to reject tokens whose exp has passed.
|
||||
* @return array<string, mixed>|null Decoded payload, or null on failure.
|
||||
*/
|
||||
public static function decode( string $token, string $secret, bool $verify_expiry = true ): ?array {
|
||||
$parts = explode( '.', $token );
|
||||
if ( 3 !== count( $parts ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
list( $header, $body, $signature ) = $parts;
|
||||
|
||||
// Pin the algorithm. We only ever issue and verify HS256; rejecting any
|
||||
// other alg (notably 'none') defends against algorithm-substitution
|
||||
// attacks explicitly rather than relying on the HMAC comparison alone.
|
||||
$header_data = json_decode( self::base64url_decode( $header ), true );
|
||||
if ( ! is_array( $header_data ) || 'HS256' !== ( $header_data['alg'] ?? '' ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$expected_sig = self::base64url_encode( hash_hmac( 'sha256', $header . '.' . $body, $secret, true ) );
|
||||
if ( ! hash_equals( $expected_sig, $signature ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$payload = json_decode( self::base64url_decode( $body ), true );
|
||||
if ( ! is_array( $payload ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ( $verify_expiry && isset( $payload['exp'] ) && (int) $payload['exp'] < time() ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64URL-encode a binary string.
|
||||
*
|
||||
* @param string $data Raw bytes to encode.
|
||||
* @return string URL-safe base64 without padding.
|
||||
*/
|
||||
public static function base64url_encode( string $data ): string {
|
||||
return rtrim( strtr( base64_encode( $data ), '+/', '-_' ), '=' ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64URL-decode a string.
|
||||
*
|
||||
* @param string $data URL-safe base64 string.
|
||||
* @return string Decoded binary string.
|
||||
*/
|
||||
private static function base64url_decode( string $data ): string {
|
||||
return (string) base64_decode( strtr( $data, '-_', '+/' ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
/**
|
||||
* OAuth Request Body Parser.
|
||||
*
|
||||
* Shared logic for parsing application/json or application/x-www-form-urlencoded
|
||||
* request bodies in OAuth endpoints (TokenEndpoint, RevokeEndpoint).
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
/**
|
||||
* Provides parse_body() to OAuth endpoint classes.
|
||||
*/
|
||||
trait ParseBodyTrait {
|
||||
|
||||
/**
|
||||
* Parse the request body from either JSON or form-encoded content.
|
||||
*
|
||||
* JSON bodies are capped at 32 KB to prevent memory exhaustion from
|
||||
* oversized payloads; form-encoded bodies are read from $_POST which
|
||||
* PHP already limits via the post_max_size ini setting.
|
||||
*
|
||||
* @return array<string, mixed> Associative array of body parameters.
|
||||
*/
|
||||
private function parse_body(): array {
|
||||
$content_type = isset( $_SERVER['CONTENT_TYPE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['CONTENT_TYPE'] ) ) : '';
|
||||
|
||||
if ( false !== strpos( $content_type, 'application/json' ) ) {
|
||||
$raw = substr( (string) file_get_contents( 'php://input' ), 0, 32768 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
|
||||
$body = json_decode( '' !== $raw ? $raw : '{}', true );
|
||||
return is_array( $body ) ? $body : [];
|
||||
}
|
||||
|
||||
// Form-encoded (application/x-www-form-urlencoded).
|
||||
// phpcs:ignore WordPress.Security.NonceVerification.Missing
|
||||
return array_map( 'sanitize_text_field', wp_unslash( $_POST ) );
|
||||
}
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
/**
|
||||
* Token Revocation Endpoint (RFC 7009).
|
||||
*
|
||||
* Handles POST /oauth/revoke. Accepts an access or refresh JWT, verifies its
|
||||
* signature (ignoring expiry per spec), then deletes the WordPress Application
|
||||
* Password that anchors the session. Because OAuthHttpTransport checks the
|
||||
* Application Password on every request, deletion immediately invalidates all
|
||||
* outstanding tokens for that session — no token store is needed.
|
||||
*
|
||||
* RFC 7009 §2.2 requires HTTP 200 even for unrecognisable or already-revoked
|
||||
* tokens; the response body is an empty JSON object `{}`.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
use WPMedia\MCP\OAuth\Logging\McpLogger;
|
||||
|
||||
/**
|
||||
* Revoke Endpoint.
|
||||
*/
|
||||
class RevokeEndpoint {
|
||||
use ParseBodyTrait;
|
||||
|
||||
/**
|
||||
* Handle the revocation request.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle_request(): void {
|
||||
$request_method = isset( $_SERVER['REQUEST_METHOD'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : '';
|
||||
|
||||
McpLogger::log(
|
||||
'REVOKE',
|
||||
'revocation request received',
|
||||
[
|
||||
'method' => $request_method,
|
||||
'remote_addr' => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
|
||||
'user_agent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '',
|
||||
]
|
||||
);
|
||||
|
||||
if ( 'POST' !== $request_method ) {
|
||||
McpLogger::log( 'REVOKE', 'rejected: wrong method', [ 'method' => $request_method ] );
|
||||
$this->send_error( 405, 'invalid_request', 'Method not allowed.' );
|
||||
return;
|
||||
}
|
||||
|
||||
$body = $this->parse_body();
|
||||
$token = sanitize_text_field( $body['token'] ?? '' );
|
||||
$client_id_param = esc_url_raw( $body['client_id'] ?? '' );
|
||||
|
||||
if ( '' === $token ) {
|
||||
McpLogger::log( 'REVOKE', 'rejected: missing token parameter' );
|
||||
$this->send_error( 400, 'invalid_request', 'token is required.' );
|
||||
return;
|
||||
}
|
||||
|
||||
$secret = SecretManager::get_secret();
|
||||
|
||||
// Decode without expiry check — RFC 7009 requires revoking even expired tokens.
|
||||
$claims = JWT::decode( $token, $secret, false );
|
||||
|
||||
if ( null === $claims ) {
|
||||
// Invalid signature or malformed token — return success per RFC 7009 §2.2.
|
||||
McpLogger::log( 'REVOKE', 'no-op: token not recognised (invalid signature or format)' );
|
||||
$this->send_success();
|
||||
return;
|
||||
}
|
||||
|
||||
$user_id = (int) ( $claims['sub'] ?? 0 );
|
||||
$app_pass_uuid = (string) ( $claims['app_pass_id'] ?? '' );
|
||||
|
||||
if ( 0 === $user_id || '' === $app_pass_uuid ) {
|
||||
McpLogger::log( 'REVOKE', 'no-op: token missing sub or app_pass_id claims' );
|
||||
$this->send_success();
|
||||
return;
|
||||
}
|
||||
|
||||
// Client binding check (RFC 7009 §2.1): if the caller supplied a client_id and
|
||||
// the token carries one, they must match. A mismatch silently succeeds — no
|
||||
// Application Password is deleted and no information about token ownership is
|
||||
// leaked to the caller.
|
||||
$token_client_id = (string) ( $claims['client_id'] ?? '' );
|
||||
if ( '' !== $client_id_param && '' !== $token_client_id && $client_id_param !== $token_client_id ) {
|
||||
McpLogger::log(
|
||||
'REVOKE',
|
||||
'no-op: client_id mismatch',
|
||||
[
|
||||
'param_client_id' => $client_id_param,
|
||||
'token_client_id' => $token_client_id,
|
||||
'user_id' => $user_id,
|
||||
]
|
||||
);
|
||||
$this->send_success();
|
||||
return;
|
||||
}
|
||||
|
||||
\WP_Application_Passwords::delete_application_password( $user_id, $app_pass_uuid );
|
||||
|
||||
McpLogger::log(
|
||||
'REVOKE',
|
||||
'session revoked',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'app_pass_uuid' => $app_pass_uuid,
|
||||
'client_id' => $token_client_id,
|
||||
'token_type' => isset( $claims['type'] ) && 'refresh' === $claims['type'] ? 'refresh' : 'access',
|
||||
]
|
||||
);
|
||||
|
||||
$this->send_success();
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a successful revocation response (HTTP 200, empty JSON object).
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function send_success(): void {
|
||||
nocache_headers();
|
||||
wp_send_json( new \stdClass() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a JSON error response and exit.
|
||||
*
|
||||
* @param int $status HTTP status code.
|
||||
* @param string $error OAuth error code.
|
||||
* @param string $description Optional human-readable description.
|
||||
* @return void
|
||||
*/
|
||||
private function send_error( int $status, string $error, string $description = '' ): void {
|
||||
status_header( $status );
|
||||
nocache_headers();
|
||||
$body = [ 'error' => $error ];
|
||||
if ( '' !== $description ) {
|
||||
$body['error_description'] = $description;
|
||||
}
|
||||
wp_send_json( $body );
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
/**
|
||||
* OAuth 2.1 Rewrite Rules.
|
||||
*
|
||||
* Registers the WordPress rewrite rules and query var used to route the
|
||||
* five OAuth endpoints (authorize, authorize-callback, token, consent,
|
||||
* revoke).
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
/**
|
||||
* Registers OAuth endpoint rewrite rules and the query var used to route them.
|
||||
*/
|
||||
class Rewrite {
|
||||
|
||||
/**
|
||||
* WordPress query var used to route OAuth endpoint requests.
|
||||
*/
|
||||
const OAUTH_QUERY_VAR = 'mcp_oauth_endpoint';
|
||||
|
||||
/**
|
||||
* Canary rule key used to detect whether the OAuth rules are persisted.
|
||||
*/
|
||||
const AUTHORIZE_RULE = '^oauth/authorize$';
|
||||
|
||||
/**
|
||||
* Register WordPress rewrite rules for all five OAuth endpoints.
|
||||
*
|
||||
* Called on the 'init' action (normal page load).
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_oauth_rewrite_rules(): void {
|
||||
add_rewrite_rule( self::AUTHORIZE_RULE, 'index.php?' . self::OAUTH_QUERY_VAR . '=authorize', 'top' );
|
||||
add_rewrite_rule( '^oauth/authorize-callback$', 'index.php?' . self::OAUTH_QUERY_VAR . '=authorize-callback', 'top' );
|
||||
add_rewrite_rule( '^oauth/token$', 'index.php?' . self::OAUTH_QUERY_VAR . '=token', 'top' );
|
||||
add_rewrite_rule( '^oauth/consent$', 'index.php?' . self::OAUTH_QUERY_VAR . '=consent', 'top' );
|
||||
add_rewrite_rule( '^oauth/revoke$', 'index.php?' . self::OAUTH_QUERY_VAR . '=revoke', 'top' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the OAuth query var to WordPress's list of recognised vars.
|
||||
*
|
||||
* @param string[] $vars Existing query vars.
|
||||
* @return string[] Modified list.
|
||||
*/
|
||||
public function add_oauth_query_vars( array $vars ): array {
|
||||
$vars[] = self::OAUTH_QUERY_VAR;
|
||||
|
||||
return $vars;
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
<?php
|
||||
/**
|
||||
* MCP Auth Router.
|
||||
*
|
||||
* Wires the OAuth 2.1 endpoint routing. Registered directly by Bootstrap via
|
||||
* add_action()/add_filter() calls. Plugin lifecycle (activation) is handled
|
||||
* separately by Rewrite and SecretManager.
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
use WPMedia\MCP\OAuth\Context;
|
||||
|
||||
/**
|
||||
* Registers OAuth endpoint routing callbacks.
|
||||
*/
|
||||
class Router {
|
||||
|
||||
use Http404Trait;
|
||||
|
||||
/**
|
||||
* OAuth rewrite rules and query var registration.
|
||||
*
|
||||
* @var Rewrite
|
||||
*/
|
||||
private Rewrite $rewrite;
|
||||
|
||||
/**
|
||||
* Authorize endpoint handler.
|
||||
*
|
||||
* @var AuthorizeEndpoint
|
||||
*/
|
||||
private AuthorizeEndpoint $authorize_endpoint;
|
||||
|
||||
/**
|
||||
* Authorize callback handler.
|
||||
*
|
||||
* @var AuthorizeCallback
|
||||
*/
|
||||
private AuthorizeCallback $authorize_callback;
|
||||
|
||||
/**
|
||||
* Token endpoint handler.
|
||||
*
|
||||
* @var TokenEndpoint
|
||||
*/
|
||||
private TokenEndpoint $token_endpoint;
|
||||
|
||||
/**
|
||||
* Consent endpoint handler.
|
||||
*
|
||||
* @var ConsentEndpoint
|
||||
*/
|
||||
private ConsentEndpoint $consent_endpoint;
|
||||
|
||||
/**
|
||||
* Revoke endpoint handler.
|
||||
*
|
||||
* @var RevokeEndpoint
|
||||
*/
|
||||
private RevokeEndpoint $revoke_endpoint;
|
||||
|
||||
/**
|
||||
* OAuth server context.
|
||||
*
|
||||
* @var Context
|
||||
*/
|
||||
private Context $context;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param Rewrite $rewrite OAuth rewrite rules and query var registration.
|
||||
* @param AuthorizeEndpoint $authorize_endpoint Authorization endpoint.
|
||||
* @param AuthorizeCallback $authorize_callback Authorization callback.
|
||||
* @param TokenEndpoint $token_endpoint Token endpoint.
|
||||
* @param ConsentEndpoint $consent_endpoint Consent endpoint.
|
||||
* @param RevokeEndpoint $revoke_endpoint Revocation endpoint.
|
||||
* @param Context $context OAuth server context.
|
||||
*/
|
||||
public function __construct(
|
||||
Rewrite $rewrite,
|
||||
AuthorizeEndpoint $authorize_endpoint,
|
||||
AuthorizeCallback $authorize_callback,
|
||||
TokenEndpoint $token_endpoint,
|
||||
ConsentEndpoint $consent_endpoint,
|
||||
RevokeEndpoint $revoke_endpoint,
|
||||
Context $context
|
||||
) {
|
||||
$this->rewrite = $rewrite;
|
||||
$this->authorize_endpoint = $authorize_endpoint;
|
||||
$this->authorize_callback = $authorize_callback;
|
||||
$this->token_endpoint = $token_endpoint;
|
||||
$this->consent_endpoint = $consent_endpoint;
|
||||
$this->revoke_endpoint = $revoke_endpoint;
|
||||
$this->context = $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register WordPress rewrite rules for all five OAuth endpoints.
|
||||
*
|
||||
* Called on the 'init' action (normal page load).
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_rewrite_rules(): void {
|
||||
if ( ! $this->context->is_enabled() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->rewrite->register_oauth_rewrite_rules();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the OAuth query var to WordPress's list of recognised vars.
|
||||
*
|
||||
* @param string[] $vars Existing query vars.
|
||||
* @return string[] Modified list.
|
||||
*/
|
||||
public function add_query_vars( array $vars ): array {
|
||||
return $this->rewrite->add_oauth_query_vars( $vars );
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch an incoming OAuth endpoint request to the appropriate handler.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle_request(): void {
|
||||
$endpoint = (string) get_query_var( Rewrite::OAUTH_QUERY_VAR, '' );
|
||||
|
||||
if ( '' === $endpoint ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! $this->context->is_enabled() ) {
|
||||
$this->force_404();
|
||||
return;
|
||||
}
|
||||
|
||||
switch ( $endpoint ) {
|
||||
case 'authorize':
|
||||
$this->authorize_endpoint->handle_request();
|
||||
break;
|
||||
case 'authorize-callback':
|
||||
$this->authorize_callback->handle_request();
|
||||
break;
|
||||
case 'consent':
|
||||
$this->consent_endpoint->handle_request();
|
||||
break;
|
||||
case 'revoke':
|
||||
$this->revoke_endpoint->handle_request();
|
||||
break;
|
||||
case 'token':
|
||||
$this->token_endpoint->handle_request();
|
||||
break;
|
||||
default:
|
||||
status_header( 404 );
|
||||
wp_die( esc_html__( 'Unknown OAuth endpoint.', 'mcp-oauth' ), '', [ 'response' => 404 ] );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the refresh-token rotation marker when a session's Application
|
||||
* Password is deleted.
|
||||
*
|
||||
* @param int $user_id WordPress user ID.
|
||||
* @param array<string, mixed> $item The Application Password record being deleted.
|
||||
* @return void
|
||||
*/
|
||||
public function purge_refresh_jti_meta( $user_id, $item ): void {
|
||||
$this->token_endpoint->purge_refresh_jti_meta( (int) $user_id, (array) $item );
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
/**
|
||||
* Site Secret Manager.
|
||||
*
|
||||
* Generates, stores, and rotates the 256-bit HMAC secret used to sign all
|
||||
* MCP JWTs. Regenerating the secret immediately invalidates every outstanding
|
||||
* access and refresh token site-wide.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
/**
|
||||
* Secret Manager.
|
||||
*/
|
||||
class SecretManager {
|
||||
|
||||
/**
|
||||
* WordPress option key where the JWT signing secret is stored.
|
||||
*/
|
||||
const OPTION_KEY = 'mcp_jwt_secret';
|
||||
|
||||
/**
|
||||
* Return the current site JWT signing secret, generating one if absent.
|
||||
*
|
||||
* Uses add_option() for the initial write so that two concurrent requests
|
||||
* racing on first activation cannot both store different secrets — only one
|
||||
* caller's add_option() succeeds; the other reads back the winner's value.
|
||||
*
|
||||
* @return string Hex-encoded 256-bit secret.
|
||||
*/
|
||||
public static function get_secret(): string {
|
||||
$secret = (string) get_option( self::OPTION_KEY, '' );
|
||||
if ( '' !== $secret ) {
|
||||
return $secret;
|
||||
}
|
||||
|
||||
$candidate = self::generate();
|
||||
if ( ! add_option( self::OPTION_KEY, $candidate, '', false ) ) {
|
||||
// Another request won the race; read back whatever was stored.
|
||||
$candidate = (string) get_option( self::OPTION_KEY );
|
||||
}
|
||||
|
||||
return $candidate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure a secret exists; create one on first activation.
|
||||
*
|
||||
* Idempotent — safe to call on every activation.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function ensure_secret(): void {
|
||||
self::get_secret();
|
||||
}
|
||||
|
||||
/**
|
||||
* Regenerate the site secret, invalidating all current MCP sessions.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function regenerate(): void {
|
||||
update_option( self::OPTION_KEY, self::generate(), false );
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a fresh 256-bit random secret as a hex string.
|
||||
*
|
||||
* @return string 64-character hex string.
|
||||
*/
|
||||
private static function generate(): string {
|
||||
return bin2hex( random_bytes( 32 ) );
|
||||
}
|
||||
}
|
||||
+517
@@ -0,0 +1,517 @@
|
||||
<?php
|
||||
/**
|
||||
* Token Endpoint.
|
||||
*
|
||||
* Handles POST /oauth/token for two grant types:
|
||||
* - authorization_code: PKCE verification → create Application Password → issue JWT pair.
|
||||
* - refresh_token: verify refresh JWT → revocation check → issue new access JWT.
|
||||
*
|
||||
* Raw Application Passwords are never stored and are discarded immediately
|
||||
* after creation. Only the UUID is retained inside the JWT claims for
|
||||
* revocation checking.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
use WPMedia\MCP\OAuth\Logging\McpLogger;
|
||||
|
||||
class TokenEndpoint {
|
||||
use ParseBodyTrait;
|
||||
|
||||
/**
|
||||
* User-meta key prefix storing the currently valid refresh-token id (jti)
|
||||
* for a session. The session is identified by its Application Password UUID,
|
||||
* so the full key is REFRESH_JTI_META_PREFIX . $app_pass_uuid.
|
||||
*/
|
||||
const REFRESH_JTI_META_PREFIX = 'mcp_refresh_jti_';
|
||||
|
||||
/**
|
||||
* Maximum number of concurrent MCP sessions (Application Passwords) retained
|
||||
* per user per client. Every successful code exchange mints a new Application
|
||||
* Password, so a client that re-runs the authorize→token flow repeatedly would
|
||||
* otherwise accumulate unbounded rows — bloating the user's Application
|
||||
* Passwords screen and slowing the per-request revocation lookup in
|
||||
* OAuthHttpTransport, which scans all of the user's Application Passwords. When
|
||||
* a new session would exceed this cap, the oldest sessions for that client are
|
||||
* evicted first.
|
||||
*/
|
||||
const MAX_SESSIONS_PER_CLIENT = 5;
|
||||
|
||||
/**
|
||||
* Handle the token request.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle_request(): void {
|
||||
$request_method = isset( $_SERVER['REQUEST_METHOD'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : '';
|
||||
$content_type = isset( $_SERVER['CONTENT_TYPE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['CONTENT_TYPE'] ) ) : '';
|
||||
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'token request received',
|
||||
[
|
||||
'method' => $request_method,
|
||||
'content_type' => $content_type,
|
||||
'remote_addr' => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
|
||||
'user_agent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '',
|
||||
'headers' => McpLogger::safe_request_headers(),
|
||||
'body' => McpLogger::safe_request_body(),
|
||||
]
|
||||
);
|
||||
|
||||
if ( 'POST' !== $request_method ) {
|
||||
McpLogger::log( 'TOKEN', 'rejected: wrong method', [ 'method' => $request_method ] );
|
||||
$this->send_error( 405, 'invalid_request', 'Method not allowed.' );
|
||||
return;
|
||||
}
|
||||
|
||||
$body = $this->parse_body();
|
||||
|
||||
$grant_type = sanitize_text_field( $body['grant_type'] ?? '' );
|
||||
|
||||
McpLogger::log( 'TOKEN', 'grant_type received', [ 'grant_type' => $grant_type ] );
|
||||
|
||||
if ( 'authorization_code' === $grant_type ) {
|
||||
$this->handle_authorization_code( $body );
|
||||
} elseif ( 'refresh_token' === $grant_type ) {
|
||||
$this->handle_refresh_token( $body );
|
||||
} else {
|
||||
McpLogger::log( 'TOKEN', 'rejected: unsupported grant_type', [ 'grant_type' => $grant_type ] );
|
||||
$this->send_error( 400, 'unsupported_grant_type' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exchange an auth code for a JWT pair.
|
||||
*
|
||||
* @param array<string, mixed> $body Parsed request body.
|
||||
* @return void
|
||||
*/
|
||||
private function handle_authorization_code( array $body ): void {
|
||||
$code = sanitize_text_field( $body['code'] ?? '' );
|
||||
$code_verifier = sanitize_text_field( $body['code_verifier'] ?? '' );
|
||||
$redirect_uri = esc_url_raw( $body['redirect_uri'] ?? '' );
|
||||
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'authorization_code exchange: params',
|
||||
[
|
||||
'has_code' => '' !== $code ? 'yes' : 'no',
|
||||
'has_code_verifier' => '' !== $code_verifier ? 'yes' : 'no',
|
||||
'redirect_uri' => $redirect_uri,
|
||||
]
|
||||
);
|
||||
|
||||
if ( '' === $code || '' === $code_verifier ) {
|
||||
McpLogger::log( 'TOKEN', 'rejected: missing code or code_verifier' );
|
||||
$this->send_error( 400, 'invalid_request', 'code and code_verifier are required.' );
|
||||
return;
|
||||
}
|
||||
|
||||
// Look up the single-use code, then atomically consume it. delete_transient()
|
||||
// returns true for only one caller when two requests race for the same code
|
||||
// (delete_option / wp_cache_delete report the row/key they actually removed),
|
||||
// so a double-submitted or replayed code is rejected here rather than minting
|
||||
// a second session.
|
||||
$code_key = 'mcp_oauth_code_' . $code;
|
||||
$code_data = get_transient( $code_key );
|
||||
|
||||
if ( false === $code_data || ! is_array( $code_data ) ) {
|
||||
McpLogger::log( 'TOKEN', 'rejected: auth code transient missing or expired (60 s window)' );
|
||||
$this->send_error( 400, 'invalid_grant', 'Code is invalid or has expired.' );
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! delete_transient( $code_key ) ) {
|
||||
McpLogger::log( 'TOKEN', 'rejected: auth code already consumed (concurrent redemption)' );
|
||||
$this->send_error( 400, 'invalid_grant', 'Code is invalid or has expired.' );
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify PKCE S256: BASE64URL(SHA256(verifier)) must equal stored challenge.
|
||||
$expected = JWT::base64url_encode( hash( 'sha256', $code_verifier, true ) );
|
||||
|
||||
if ( ! hash_equals( (string) $code_data['code_challenge'], $expected ) ) {
|
||||
McpLogger::log( 'TOKEN', 'rejected: PKCE code_verifier does not match challenge' );
|
||||
$this->send_error( 400, 'invalid_grant', 'PKCE code_verifier does not match challenge.' );
|
||||
return;
|
||||
}
|
||||
|
||||
// redirect_uri is required whenever it was included in the authorization request
|
||||
// (OAuth 2.1 §4.1.3). AuthorizeEndpoint always requires it, so code_data always
|
||||
// contains a non-empty value. Exact match is enforced; the client must send the
|
||||
// same runtime URI (including ephemeral port for loopback) it used at authorize time.
|
||||
if ( $redirect_uri !== (string) $code_data['redirect_uri'] ) {
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'rejected: redirect_uri missing or does not match authorization request',
|
||||
[
|
||||
'provided' => $redirect_uri,
|
||||
'stored' => $code_data['redirect_uri'],
|
||||
]
|
||||
);
|
||||
$this->send_error( 400, 'invalid_grant', 'redirect_uri is required and must match the authorization request.' );
|
||||
return;
|
||||
}
|
||||
|
||||
$user_id = (int) $code_data['user_id'];
|
||||
$client_id = (string) ( $code_data['client_id'] ?? '' );
|
||||
|
||||
// The Application Password name is required by WordPress core and must be
|
||||
// non-empty. Fall back to the client host when the CIMD document omitted a
|
||||
// client_name so a sparse-but-valid client cannot break the token exchange.
|
||||
$client_name = (string) ( $code_data['client_name'] ?? '' );
|
||||
if ( '' === $client_name ) {
|
||||
$client_name = (string) wp_parse_url( $client_id, PHP_URL_HOST );
|
||||
}
|
||||
if ( '' === $client_name ) {
|
||||
$client_name = 'MCP Client';
|
||||
}
|
||||
|
||||
McpLogger::log( 'TOKEN', 'PKCE verified — creating Application Password', [ 'user_id' => $user_id ] );
|
||||
|
||||
// Bound the number of sessions this client can stockpile before adding one more.
|
||||
$this->prune_sessions( $user_id, $client_id );
|
||||
|
||||
// Create a WordPress Application Password (raw password is discarded).
|
||||
$result = \WP_Application_Passwords::create_new_application_password(
|
||||
$user_id,
|
||||
[
|
||||
'name' => $client_name,
|
||||
'app_id' => $client_id,
|
||||
],
|
||||
);
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'server_error: Application Password creation failed',
|
||||
[
|
||||
'wp_error_code' => $result->get_error_code(),
|
||||
'wp_error_message' => $result->get_error_message(),
|
||||
'user_id' => $user_id,
|
||||
]
|
||||
);
|
||||
$this->send_error( 500, 'server_error', 'Could not create MCP session.' );
|
||||
return;
|
||||
}
|
||||
|
||||
// create_new_application_password() returns [raw_password, metadata]. Raw password is discarded.
|
||||
$app_pass_uuid = (string) $result[1]['uuid'];
|
||||
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'Application Password created — issuing token pair',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'app_pass_uuid' => $app_pass_uuid,
|
||||
]
|
||||
);
|
||||
|
||||
$this->issue_token_pair( $user_id, $app_pass_uuid, $client_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh an access token using a valid refresh JWT.
|
||||
*
|
||||
* @param array<string, mixed> $body Parsed request body.
|
||||
* @return void
|
||||
*/
|
||||
private function handle_refresh_token( array $body ): void {
|
||||
$refresh_token = sanitize_text_field( $body['refresh_token'] ?? '' );
|
||||
|
||||
McpLogger::log( 'TOKEN', 'refresh_token grant: validating', [ 'has_refresh_token' => '' !== $refresh_token ? 'yes' : 'no' ] );
|
||||
|
||||
if ( '' === $refresh_token ) {
|
||||
McpLogger::log( 'TOKEN', 'rejected: refresh_token missing' );
|
||||
$this->send_error( 400, 'invalid_request', 'refresh_token is required.' );
|
||||
return;
|
||||
}
|
||||
|
||||
$secret = SecretManager::get_secret();
|
||||
$claims = JWT::decode( $refresh_token, $secret );
|
||||
|
||||
if ( null === $claims || 'refresh' !== ( $claims['type'] ?? '' ) ) {
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'rejected: refresh token decode failed or wrong type',
|
||||
[
|
||||
'claims_null' => null === $claims ? 'yes' : 'no',
|
||||
'type' => null !== $claims ? ( $claims['type'] ?? '(missing)' ) : 'n/a',
|
||||
]
|
||||
);
|
||||
$this->send_error( 401, 'invalid_token', 'Refresh token is invalid or expired.' );
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify the token was issued by this site. A staging clone sharing the same
|
||||
// JWT secret would otherwise allow cross-site token replay.
|
||||
$token_iss = (string) ( $claims['iss'] ?? '' );
|
||||
if ( home_url() !== $token_iss ) {
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'rejected: refresh token issuer mismatch',
|
||||
[
|
||||
'token_iss' => $token_iss,
|
||||
'expected_iss' => home_url(),
|
||||
]
|
||||
);
|
||||
$this->send_error( 401, 'invalid_token', 'Refresh token was not issued by this server.' );
|
||||
return;
|
||||
}
|
||||
|
||||
$user_id = (int) $claims['sub'];
|
||||
$app_pass_uuid = (string) ( $claims['app_pass_id'] ?? '' );
|
||||
$client_id = (string) ( $claims['client_id'] ?? '' );
|
||||
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'refresh token decoded — checking revocation',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'app_pass_uuid' => $app_pass_uuid,
|
||||
]
|
||||
);
|
||||
|
||||
// Revocation check: if the Application Password was deleted the session is gone.
|
||||
$app_pass = \WP_Application_Passwords::get_user_application_password( $user_id, $app_pass_uuid );
|
||||
|
||||
if ( ! is_array( $app_pass ) ) {
|
||||
// Session is gone; drop the now-orphaned rotation marker too.
|
||||
delete_user_meta( $user_id, self::REFRESH_JTI_META_PREFIX . $app_pass_uuid );
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'rejected: Application Password revoked or not found',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'app_pass_uuid' => $app_pass_uuid,
|
||||
]
|
||||
);
|
||||
$this->send_error( 401, 'invalid_token', 'MCP session has been revoked.' );
|
||||
return;
|
||||
}
|
||||
|
||||
// Refresh-token rotation / reuse detection (OAuth 2.1 §4.3.1, RFC 6819 §5.2.2.3).
|
||||
// Each issued refresh token carries a unique jti; only the most recently
|
||||
// issued jti for this session is accepted. Presenting any other (i.e. an
|
||||
// already-rotated, previously-consumed) refresh token means the token has
|
||||
// leaked and is being replayed — revoke the whole session so the attacker
|
||||
// and the legitimate client are both forced to re-authenticate.
|
||||
$presented_jti = (string) ( $claims['jti'] ?? '' );
|
||||
$current_jti = (string) get_user_meta( $user_id, self::REFRESH_JTI_META_PREFIX . $app_pass_uuid, true );
|
||||
|
||||
if ( '' === $presented_jti || '' === $current_jti || ! hash_equals( $current_jti, $presented_jti ) ) {
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'SECURITY: refresh token reuse detected — revoking session',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'app_pass_uuid' => $app_pass_uuid,
|
||||
'has_presented' => '' !== $presented_jti ? 'yes' : 'no',
|
||||
'has_current' => '' !== $current_jti ? 'yes' : 'no',
|
||||
]
|
||||
);
|
||||
// Deleting the Application Password fires wp_delete_application_password,
|
||||
// which purges the rotation marker via purge_refresh_jti_meta().
|
||||
\WP_Application_Passwords::delete_application_password( $user_id, $app_pass_uuid );
|
||||
$this->send_error( 401, 'invalid_grant', 'Refresh token has been revoked.' );
|
||||
return;
|
||||
}
|
||||
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'refresh token valid — issuing new token pair',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'app_pass_uuid' => $app_pass_uuid,
|
||||
]
|
||||
);
|
||||
|
||||
// Issue a new access token and rotate the refresh token: issue_token_pair()
|
||||
// mints a fresh jti and overwrites the stored marker, invalidating the
|
||||
// refresh token just presented.
|
||||
$this->issue_token_pair( $user_id, $app_pass_uuid, $client_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* Build and return an access + refresh JWT pair.
|
||||
*
|
||||
* @param int $user_id WordPress user ID.
|
||||
* @param string $app_pass_uuid UUID of the Application Password.
|
||||
* @param string $client_id Client ID URL from the CIMD record.
|
||||
* @return void
|
||||
*/
|
||||
private function issue_token_pair( int $user_id, string $app_pass_uuid, string $client_id = '' ): void {
|
||||
$secret = SecretManager::get_secret();
|
||||
// iss is home_url() (the Site Address), matching the base get_rest_url()
|
||||
// uses for aud and where the OAuth/.well-known routes are actually served.
|
||||
$issuer = home_url();
|
||||
$now = time();
|
||||
$aud = get_rest_url( null, 'mcp/mcp-oauth-server' );
|
||||
|
||||
// Mint a fresh refresh-token id and persist it as the only one accepted
|
||||
// for this session. This overwrites any prior marker, so the previously
|
||||
// issued refresh token (if any) is invalidated the instant this returns.
|
||||
$refresh_jti = bin2hex( random_bytes( 16 ) );
|
||||
update_user_meta( $user_id, self::REFRESH_JTI_META_PREFIX . $app_pass_uuid, $refresh_jti );
|
||||
|
||||
$access_payload = [
|
||||
'iss' => $issuer,
|
||||
'aud' => $aud,
|
||||
'sub' => (string) $user_id,
|
||||
'app_pass_id' => $app_pass_uuid,
|
||||
'client_id' => $client_id,
|
||||
'scope' => 'mcp',
|
||||
'iat' => $now,
|
||||
'exp' => $now + HOUR_IN_SECONDS,
|
||||
];
|
||||
|
||||
$refresh_payload = [
|
||||
'iss' => $issuer,
|
||||
'sub' => (string) $user_id,
|
||||
'app_pass_id' => $app_pass_uuid,
|
||||
'client_id' => $client_id,
|
||||
'type' => 'refresh',
|
||||
'jti' => $refresh_jti,
|
||||
'iat' => $now,
|
||||
'exp' => $now + ( 30 * DAY_IN_SECONDS ),
|
||||
];
|
||||
|
||||
$access_token = JWT::encode( $access_payload, $secret );
|
||||
$refresh_token = JWT::encode( $refresh_payload, $secret );
|
||||
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'token pair issued',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'app_pass_uuid' => $app_pass_uuid,
|
||||
'access_exp' => $access_payload['exp'],
|
||||
'refresh_exp' => $refresh_payload['exp'],
|
||||
'access_token_len' => strlen( $access_token ),
|
||||
]
|
||||
);
|
||||
|
||||
nocache_headers();
|
||||
wp_send_json(
|
||||
[
|
||||
'access_token' => $access_token,
|
||||
'token_type' => 'Bearer',
|
||||
'expires_in' => HOUR_IN_SECONDS,
|
||||
'refresh_token' => $refresh_token,
|
||||
'scope' => 'mcp',
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Evict the oldest MCP sessions for a user+client so that creating one more
|
||||
* stays within MAX_SESSIONS_PER_CLIENT.
|
||||
*
|
||||
* Only Application Passwords this feature created are considered — they are
|
||||
* matched by the `app_id` we set to the client_id at creation time, so
|
||||
* Application Passwords the user created for other integrations are never
|
||||
* touched. Deleting one fires `wp_delete_application_password`, which removes
|
||||
* its `mcp_refresh_jti_*` meta via purge_refresh_jti_meta(), so no orphaned
|
||||
* rows are left behind.
|
||||
*
|
||||
* @param int $user_id WordPress user ID.
|
||||
* @param string $client_id Client ID URL the sessions belong to.
|
||||
* @return void
|
||||
*/
|
||||
private function prune_sessions( int $user_id, string $client_id ): void {
|
||||
if ( '' === $client_id ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$passwords = \WP_Application_Passwords::get_user_application_passwords( $user_id );
|
||||
|
||||
// Keep only this feature's Application Passwords for this client.
|
||||
$ours = array_values(
|
||||
array_filter(
|
||||
$passwords,
|
||||
static function ( $item ) use ( $client_id ) {
|
||||
return $item['app_id'] === $client_id;
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
// Below the cap: the new session about to be created still fits.
|
||||
if ( count( $ours ) < self::MAX_SESSIONS_PER_CLIENT ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Oldest first.
|
||||
usort(
|
||||
$ours,
|
||||
static function ( $a, $b ) {
|
||||
return $a['created'] <=> $b['created'];
|
||||
}
|
||||
);
|
||||
|
||||
// Evict enough of the oldest so that, after the new one is created, the
|
||||
// total sits at exactly MAX_SESSIONS_PER_CLIENT.
|
||||
$evict_count = ( count( $ours ) - self::MAX_SESSIONS_PER_CLIENT ) + 1;
|
||||
|
||||
for ( $i = 0; $i < $evict_count; $i++ ) {
|
||||
$uuid = (string) ( $ours[ $i ]['uuid'] ?? '' );
|
||||
if ( '' === $uuid ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
\WP_Application_Passwords::delete_application_password( $user_id, $uuid );
|
||||
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'evicted oldest MCP session to enforce per-client cap',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'client_id' => $client_id,
|
||||
'app_pass_uuid' => $uuid,
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge the stored refresh-token rotation marker for a deleted session.
|
||||
*
|
||||
* Hooked on WordPress's `wp_delete_application_password` action so the
|
||||
* per-session user meta is removed wherever the Application Password that
|
||||
* anchors the session is deleted — the revoke endpoint, the admin page, or
|
||||
* WordPress core — leaving no orphaned rows behind.
|
||||
*
|
||||
* @param int $user_id WordPress user ID.
|
||||
* @param array<string, mixed> $item The Application Password record being deleted.
|
||||
* @return void
|
||||
*/
|
||||
public function purge_refresh_jti_meta( int $user_id, array $item ): void {
|
||||
$uuid = (string) ( $item['uuid'] ?? '' );
|
||||
|
||||
if ( '' === $uuid ) {
|
||||
return;
|
||||
}
|
||||
|
||||
delete_user_meta( $user_id, self::REFRESH_JTI_META_PREFIX . $uuid );
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a JSON error response and exit.
|
||||
*
|
||||
* @param int $status HTTP status code.
|
||||
* @param string $error OAuth error code.
|
||||
* @param string $description Optional human-readable description.
|
||||
* @return void
|
||||
*/
|
||||
private function send_error( int $status, string $error, string $description = '' ): void {
|
||||
status_header( $status );
|
||||
nocache_headers();
|
||||
$body = [ 'error' => $error ];
|
||||
if ( '' !== $description ) {
|
||||
$body['error_description'] = $description;
|
||||
}
|
||||
wp_send_json( $body );
|
||||
}
|
||||
}
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
<?php
|
||||
/**
|
||||
* MCP OAuth Bootstrap.
|
||||
*
|
||||
* Single centralized entry point for the library. Consuming plugins call
|
||||
* Bootstrap::instance() (recommended on the 'plugins_loaded' action); the
|
||||
* first call wires the entire library to WordPress, every subsequent call
|
||||
* (from the same or another consuming plugin) returns the same instance and
|
||||
* binds nothing further.
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WPMedia\MCP\OAuth;
|
||||
|
||||
use WP\MCP\Core\McpAdapter;
|
||||
use WPMedia\MCP\OAuth\Auth\AuthorizeCallback;
|
||||
use WPMedia\MCP\OAuth\Auth\AuthorizeEndpoint;
|
||||
use WPMedia\MCP\OAuth\Auth\CimdResolver;
|
||||
use WPMedia\MCP\OAuth\Auth\ClaudeClientVerifier;
|
||||
use WPMedia\MCP\OAuth\Auth\ConsentEndpoint;
|
||||
use WPMedia\MCP\OAuth\Auth\Discovery\Endpoints as DiscoveryEndpoints;
|
||||
use WPMedia\MCP\OAuth\Auth\Discovery\HealthCheck as DiscoveryHealthCheck;
|
||||
use WPMedia\MCP\OAuth\Auth\RevokeEndpoint;
|
||||
use WPMedia\MCP\OAuth\Auth\Rewrite;
|
||||
use WPMedia\MCP\OAuth\Auth\Router;
|
||||
use WPMedia\MCP\OAuth\Auth\SecretManager;
|
||||
use WPMedia\MCP\OAuth\Auth\TokenEndpoint;
|
||||
use WPMedia\MCP\OAuth\Transport\Server;
|
||||
use WPMedia\MCP\OAuth\Transport\ServerRegistrar;
|
||||
use WPMedia\MCP\OAuth\Views\Render;
|
||||
|
||||
/**
|
||||
* Centralized single-instance bootstrap for the MCP OAuth library.
|
||||
*/
|
||||
final class Bootstrap {
|
||||
|
||||
/**
|
||||
* Bumped whenever any endpoint's or discovery document's rewrite regex changes.
|
||||
*/
|
||||
private const REWRITE_VERSION = '1';
|
||||
|
||||
/**
|
||||
* Option storing the rewrite-rules version last flushed for.
|
||||
*/
|
||||
private const REWRITE_OPTION = 'wpmedia_mcp_oauth_rewrite_version';
|
||||
|
||||
/**
|
||||
* The single instance.
|
||||
*
|
||||
* @var self
|
||||
*/
|
||||
private static self $instance;
|
||||
|
||||
/**
|
||||
* Whether register() has already run.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private static bool $initialized = false;
|
||||
|
||||
/**
|
||||
* OAuth server context, shared across all wired collaborators.
|
||||
*
|
||||
* @var Context
|
||||
*/
|
||||
private Context $context;
|
||||
|
||||
/**
|
||||
* Return the single Bootstrap instance, wiring the library on first call.
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
public static function instance(): self {
|
||||
if ( ! isset( self::$instance ) ) {
|
||||
self::$instance = new self();
|
||||
self::$instance->register();
|
||||
}
|
||||
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Private constructor — use instance().
|
||||
*/
|
||||
private function __construct() {}
|
||||
|
||||
/**
|
||||
* Singletons cannot be cloned.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __clone() {
|
||||
_doing_it_wrong( __METHOD__, 'Bootstrap is a singleton and cannot be cloned.', '1.0.0' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Singletons cannot be unserialized.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __wakeup() {
|
||||
_doing_it_wrong( __METHOD__, 'Bootstrap is a singleton and cannot be unserialized.', '1.0.0' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire the object graph and bind every WordPress hook.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function register(): void {
|
||||
if ( self::$initialized ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->context = new Context();
|
||||
|
||||
$this->register_auth_router();
|
||||
$this->register_discovery( $this->context );
|
||||
$this->register_discovery_health_check( $this->context );
|
||||
$this->register_transport( $this->context );
|
||||
|
||||
add_action( 'init', [ SecretManager::class, 'ensure_secret' ], 5 );
|
||||
add_action( 'init', [ $this, 'maybe_flush_rewrite_rules' ], 20 );
|
||||
|
||||
// Ensure the adapter is booted so it fires mcp_adapter_init on rest_api_init@15.
|
||||
if ( class_exists( McpAdapter::class ) ) {
|
||||
McpAdapter::instance();
|
||||
}
|
||||
|
||||
self::$initialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire OAuth endpoint routing.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function register_auth_router(): void {
|
||||
$authorize = new AuthorizeEndpoint( new CimdResolver( new ClaudeClientVerifier() ) );
|
||||
|
||||
$router = new Router(
|
||||
new Rewrite(),
|
||||
$authorize,
|
||||
new AuthorizeCallback( new Render() ),
|
||||
new TokenEndpoint(),
|
||||
new ConsentEndpoint(),
|
||||
new RevokeEndpoint(),
|
||||
$this->context
|
||||
);
|
||||
|
||||
add_action( 'init', [ $router, 'register_rewrite_rules' ] );
|
||||
add_filter( 'query_vars', [ $router, 'add_query_vars' ] );
|
||||
add_action( 'template_redirect', [ $router, 'handle_request' ] );
|
||||
add_action( 'wp_delete_application_password', [ $router, 'purge_refresh_jti_meta' ], 10, 2 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire the .well-known discovery documents.
|
||||
*
|
||||
* @param Context $context OAuth server context.
|
||||
* @return void
|
||||
*/
|
||||
private function register_discovery( Context $context ): void {
|
||||
$discovery = new DiscoveryEndpoints( $context );
|
||||
|
||||
add_action( 'init', [ $discovery, 'add_rewrite_rules' ] );
|
||||
add_filter( 'query_vars', [ $discovery, 'add_query_vars' ] );
|
||||
add_action( 'template_redirect', [ $discovery, 'handle_request' ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire the Site Health self-check for the .well-known discovery documents.
|
||||
*
|
||||
* @param Context $context OAuth server context.
|
||||
* @return void
|
||||
*/
|
||||
private function register_discovery_health_check( Context $context ): void {
|
||||
$health_check = new DiscoveryHealthCheck( $context );
|
||||
|
||||
add_filter( 'site_status_tests', [ $health_check, 'add_test' ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire MCP server + abilities registration.
|
||||
*
|
||||
* @param Context $context OAuth server context.
|
||||
* @return void
|
||||
*/
|
||||
private function register_transport( Context $context ): void {
|
||||
$registrar = new ServerRegistrar( new Server( $context ), $context );
|
||||
|
||||
add_action( 'wp_abilities_api_categories_init', [ $registrar, 'ensure_default_category' ] );
|
||||
add_action( 'wp_abilities_api_init', [ $registrar, 'ensure_shared_abilities_registered' ] );
|
||||
add_action( 'mcp_adapter_init', [ $registrar, 'register_server' ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazily flush rewrite rules once per REWRITE_VERSION bump.
|
||||
*
|
||||
* Runs after rewrite rules are (re-)registered on the same 'init' action
|
||||
* (priority 10), so the rules exist before being persisted.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function maybe_flush_rewrite_rules(): void {
|
||||
if ( ! $this->context->is_enabled() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! $this->needs_rewrite_flush() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
flush_rewrite_rules( false );
|
||||
update_option( self::REWRITE_OPTION, self::REWRITE_VERSION, false );
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the OAuth rewrite rules need to be (re-)persisted.
|
||||
*
|
||||
* Self-heals cases the version flag alone cannot detect: a fresh site, a
|
||||
* filter/snippet that enables the server only after init@20 on the previous
|
||||
* load, or our rules dropped from the persisted set. When pretty permalinks
|
||||
* are off, the rules can never be persisted, so a flag match alone is used
|
||||
* to avoid flushing on every request.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function needs_rewrite_flush(): bool {
|
||||
if ( get_option( self::REWRITE_OPTION ) !== self::REWRITE_VERSION ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Plain permalinks: no pretty rules to check; a flag match is enough.
|
||||
if ( '' === (string) get_option( 'permalink_structure' ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$rules = get_option( 'rewrite_rules' );
|
||||
|
||||
return ! is_array( $rules ) || ! array_key_exists( Rewrite::AUTHORIZE_RULE, $rules );
|
||||
}
|
||||
|
||||
/**
|
||||
* Force the next 'init' to re-flush rewrite rules.
|
||||
*
|
||||
* Call this whenever whatever flips the `wpmedia_mcp_oauth_server_enabled`
|
||||
* filter changes state — a version-flag match alone cannot detect that.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function schedule_rewrite_flush(): void {
|
||||
delete_option( self::REWRITE_OPTION );
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth;
|
||||
|
||||
use WP\MCP\Infrastructure\Observability\Contracts\McpObservabilityHandlerInterface;
|
||||
use WP\MCP\Infrastructure\Observability\NullMcpObservabilityHandler;
|
||||
|
||||
class Context {
|
||||
/**
|
||||
* Determines whether the MCP OAuth server is enabled.
|
||||
*
|
||||
* @return bool True when the OAuth server (rewrite rules, endpoints,
|
||||
* discovery documents, transport) should be registered; false otherwise.
|
||||
*/
|
||||
public function is_enabled(): bool {
|
||||
$enabled = apply_filters_deprecated( 'rocket_mcp_oauth_server_enabled', [ true ], '1.0.1', 'wpmedia_mcp_oauth_server_enabled' );
|
||||
|
||||
/**
|
||||
* Filters whether the MCP OAuth server is enabled.
|
||||
*
|
||||
* When `false`, the host plugin does not register the OAuth rewrite rules
|
||||
* or respond to any /oauth/* endpoint or /.well-known discovery request,
|
||||
* and does not register the MCP OAuth transport server.
|
||||
*
|
||||
* @param bool $enabled Whether the MCP OAuth server is enabled. Default true.
|
||||
*/
|
||||
return wpm_apply_filters_typed( 'boolean', 'wpmedia_mcp_oauth_server_enabled', $enabled );
|
||||
}
|
||||
|
||||
/**
|
||||
* Observability handler class used by the MCP server.
|
||||
*
|
||||
* Defaults to the mcp-adapter's null handler, so no observability event is
|
||||
* written unless a site opts in. The verbose handler
|
||||
* (`WPMedia\MCP\OAuth\Transport\McpObservabilityHandler`) records one event per
|
||||
* server creation, i.e. once per REST request, which floods debug.log on sites
|
||||
* running with WP_DEBUG and WP_DEBUG_LOG enabled.
|
||||
*
|
||||
* @return class-string<McpObservabilityHandlerInterface> Observability handler class name.
|
||||
*/
|
||||
public function observability_handler(): string {
|
||||
/**
|
||||
* Filters the observability handler class used by the MCP server.
|
||||
*
|
||||
* The value must be a class implementing the mcp-adapter's
|
||||
* McpObservabilityHandlerInterface; any other value is ignored and the
|
||||
* null handler is used instead.
|
||||
*
|
||||
* @param string $handler Observability handler class name. Default NullMcpObservabilityHandler.
|
||||
*/
|
||||
$handler = wpm_apply_filters_typed( 'string', 'wpmedia_mcp_oauth_observability_handler', NullMcpObservabilityHandler::class );
|
||||
|
||||
if ( ! is_a( $handler, McpObservabilityHandlerInterface::class, true ) ) {
|
||||
return NullMcpObservabilityHandler::class;
|
||||
}
|
||||
|
||||
return $handler;
|
||||
}
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
/**
|
||||
* MCP structured logger.
|
||||
*
|
||||
* Single choke-point for all [MCP] error_log calls so that:
|
||||
* - every log line carries a consistent prefix for grepping
|
||||
* - sensitive values (tokens, passwords) are never written
|
||||
* - callers pass structured context arrays rather than building strings
|
||||
*
|
||||
* Usage:
|
||||
* McpLogger::log( 'TOKEN', 'grant received', [ 'grant_type' => $gt ] );
|
||||
*
|
||||
* Grep all MCP logs:
|
||||
* grep '\[MCP\]' /path/to/debug.log
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Logging;
|
||||
|
||||
/**
|
||||
* McpLogger.
|
||||
*/
|
||||
class McpLogger {
|
||||
|
||||
/**
|
||||
* Write a structured [MCP] log entry.
|
||||
*
|
||||
* The entire logger is gated on WP_DEBUG_LOG AND WP_DEBUG both being true
|
||||
* (see is_debug_enabled()): when either is not truthy, nothing is written
|
||||
* at all.
|
||||
*
|
||||
* @param string $scope Short uppercase scope tag, e.g. 'TOKEN', 'VALIDATOR'.
|
||||
* @param string $message Human-readable description.
|
||||
* @param array<string, mixed> $context Key-value pairs serialised as JSON.
|
||||
* @return void
|
||||
*/
|
||||
public static function log( string $scope, string $message, array $context = [] ): void {
|
||||
if ( ! self::is_debug_enabled() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$line = sprintf(
|
||||
'[MCP][%s] %s %s',
|
||||
strtoupper( $scope ),
|
||||
$message,
|
||||
empty( $context ) ? '' : wp_json_encode( $context )
|
||||
);
|
||||
error_log( trim( $line ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether MCP debug logging is enabled.
|
||||
*
|
||||
* True when WP_DEBUG_LOG is truthy (bool true, or a string custom log file
|
||||
* path per WP 5.1+) AND WP_DEBUG is also true. WordPress core only
|
||||
* redirects PHP's error_log() output to wp-content/debug.log when
|
||||
* WP_DEBUG is true, regardless of WP_DEBUG_LOG; requiring both here avoids
|
||||
* a configuration where this gate passes but the output doesn't land
|
||||
* where an operator would expect it (wp-content/debug.log).
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private static function is_debug_enabled(): bool {
|
||||
return defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG;
|
||||
}
|
||||
|
||||
/**
|
||||
* Capture and sanitize all HTTP request headers for logging.
|
||||
*
|
||||
* - Authorization values are truncated: first 12 chars + '...' + last 6 chars.
|
||||
* - Cookie header is replaced with '<redacted>'.
|
||||
* - All other values are preserved as-is.
|
||||
*
|
||||
* @return array<string, string> Sanitized header map (lowercase names).
|
||||
*/
|
||||
public static function safe_request_headers(): array {
|
||||
$headers = [];
|
||||
|
||||
if ( function_exists( 'getallheaders' ) ) {
|
||||
// getallheaders() always returns an array on PHP 7.3+ once it exists.
|
||||
foreach ( getallheaders() as $name => $value ) {
|
||||
$key = strtolower( (string) $name );
|
||||
$headers[ $key ] = self::sanitize_header( $key, (string) $value );
|
||||
}
|
||||
}
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Capture the raw request body up to a safe size limit.
|
||||
*
|
||||
* JSON bodies are decoded and re-encoded for normalisation; form bodies
|
||||
* are returned as-is. Authorization/password fields inside the body are
|
||||
* redacted.
|
||||
*
|
||||
* @param int $max_bytes Maximum bytes to read from php://input (default 8 KB).
|
||||
* @return string Sanitised body string suitable for logging.
|
||||
*/
|
||||
public static function safe_request_body( int $max_bytes = 8192 ): string {
|
||||
$raw = (string) file_get_contents( 'php://input' );
|
||||
|
||||
if ( '' === $raw ) {
|
||||
return '(empty)';
|
||||
}
|
||||
|
||||
$raw = substr( $raw, 0, $max_bytes );
|
||||
|
||||
$decoded = json_decode( $raw, true );
|
||||
if ( is_array( $decoded ) ) {
|
||||
$decoded = self::redact_sensitive_fields( $decoded );
|
||||
return (string) wp_json_encode( $decoded );
|
||||
}
|
||||
|
||||
// Form-encoded: redact known sensitive keys.
|
||||
parse_str( $raw, $form );
|
||||
$form = self::redact_sensitive_fields( $form );
|
||||
return (string) http_build_query( $form );
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize a single header value.
|
||||
*
|
||||
* @param string $name Lowercase header name.
|
||||
* @param string $value Header value.
|
||||
* @return string Safe value for log output.
|
||||
*/
|
||||
private static function sanitize_header( string $name, string $value ): string {
|
||||
if ( 'cookie' === $name ) {
|
||||
return '<redacted>';
|
||||
}
|
||||
|
||||
if ( 'authorization' === $name ) {
|
||||
// Preserve scheme prefix (e.g. "Bearer ") and truncate the credential.
|
||||
$space = strpos( $value, ' ' );
|
||||
if ( false !== $space ) {
|
||||
$scheme = substr( $value, 0, $space + 1 );
|
||||
$credential = substr( $value, $space + 1 );
|
||||
return $scheme . self::truncate_credential( $credential );
|
||||
}
|
||||
return self::truncate_credential( $value );
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Truncate a credential string for safe logging.
|
||||
*
|
||||
* Keeps first 12 chars + '...' + last 6 chars.
|
||||
*
|
||||
* @param string $credential Raw credential value.
|
||||
* @return string Truncated representation.
|
||||
*/
|
||||
private static function truncate_credential( string $credential ): string {
|
||||
$len = strlen( $credential );
|
||||
if ( $len <= 20 ) {
|
||||
return str_repeat( '*', $len );
|
||||
}
|
||||
return substr( $credential, 0, 12 ) . '...' . substr( $credential, -6 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively redact known sensitive field names from an array.
|
||||
*
|
||||
* @param array<string, mixed> $data Input data.
|
||||
* @return array<string, mixed> Redacted copy.
|
||||
*/
|
||||
private static function redact_sensitive_fields( array $data ): array {
|
||||
$sensitive = [ 'code', 'code_verifier', 'client_secret', 'access_token', 'refresh_token', 'password' ];
|
||||
|
||||
foreach ( $data as $key => $value ) {
|
||||
if ( in_array( strtolower( (string) $key ), $sensitive, true ) ) {
|
||||
$data[ $key ] = '<redacted>';
|
||||
} elseif ( is_array( $value ) ) {
|
||||
$data[ $key ] = self::redact_sensitive_fields( $value );
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
/**
|
||||
* MCP Observability Handler.
|
||||
*
|
||||
* Bridges the MCP adapter's observability interface with this library's
|
||||
* McpLogger, providing structured request/event metrics without external
|
||||
* dependencies. Implements the single-method McpObservabilityHandlerInterface.
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Transport;
|
||||
|
||||
use WP\MCP\Infrastructure\Observability\Contracts\McpObservabilityHandlerInterface;
|
||||
use WP\MCP\Infrastructure\Observability\McpObservabilityHelperTrait;
|
||||
use WPMedia\MCP\OAuth\Logging\McpLogger;
|
||||
|
||||
/**
|
||||
* Observability handler that writes MCP events to the MCP OAuth log.
|
||||
*/
|
||||
class McpObservabilityHandler implements McpObservabilityHandlerInterface {
|
||||
use McpObservabilityHelperTrait;
|
||||
|
||||
/**
|
||||
* Record an MCP event, optionally with timing data.
|
||||
*
|
||||
* Events are written via McpLogger under the 'OBSERVABILITY' scope.
|
||||
* All events, including error/failure events, are only written when
|
||||
* both WP_DEBUG_LOG and WP_DEBUG are enabled.
|
||||
*
|
||||
* @param string $event Event name (e.g. 'mcp.request', 'mcp.component.registration').
|
||||
* @param array $tags Key-value context tags (status, method, tool_name, etc.).
|
||||
* @param float|null $duration_ms Optional request duration in milliseconds.
|
||||
* @return void
|
||||
*/
|
||||
public function record_event( string $event, array $tags = [], ?float $duration_ms = null ): void {
|
||||
$formatted_event = self::format_metric_name( $event );
|
||||
$merged_tags = self::merge_tags( $tags );
|
||||
|
||||
if ( null !== $duration_ms ) {
|
||||
$merged_tags['duration_ms'] = round( $duration_ms, 2 );
|
||||
}
|
||||
|
||||
McpLogger::log( 'OBSERVABILITY', $formatted_event, $merged_tags );
|
||||
}
|
||||
}
|
||||
Vendored
+324
@@ -0,0 +1,324 @@
|
||||
<?php
|
||||
/**
|
||||
* MCP OAuth HTTP Transport.
|
||||
*
|
||||
* Custom transport that validates a JWT Bearer token before delegating to the
|
||||
* standard MCP HttpRequestHandler. Auth is performed inside handle_request()
|
||||
* (rather than check_permission()) so we can return a proper 401 response with
|
||||
* a WWW-Authenticate challenge header — something WordPress's permission-callback
|
||||
* mechanism cannot produce.
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Transport;
|
||||
|
||||
use WP\MCP\Transport\Contracts\McpRestTransportInterface;
|
||||
use WP\MCP\Transport\Infrastructure\HttpRequestContext;
|
||||
use WP\MCP\Transport\Infrastructure\HttpRequestHandler;
|
||||
use WP\MCP\Transport\Infrastructure\McpTransportContext;
|
||||
use WP\MCP\Transport\Infrastructure\McpTransportHelperTrait;
|
||||
use WPMedia\MCP\OAuth\Auth\JWT;
|
||||
use WPMedia\MCP\OAuth\Auth\SecretManager;
|
||||
use WPMedia\MCP\OAuth\Logging\McpLogger;
|
||||
|
||||
/**
|
||||
* OAuth HTTP Transport for the MCP OAuth server.
|
||||
*/
|
||||
class OAuthHttpTransport implements McpRestTransportInterface {
|
||||
use McpTransportHelperTrait;
|
||||
|
||||
/**
|
||||
* Delegates all MCP protocol handling (sessions, JSON-RPC, etc.).
|
||||
*
|
||||
* @var HttpRequestHandler
|
||||
*/
|
||||
protected HttpRequestHandler $request_handler;
|
||||
|
||||
/**
|
||||
* Constructor — registers the REST route on rest_api_init.
|
||||
*
|
||||
* @param McpTransportContext $transport_context Transport context provided by the MCP adapter.
|
||||
*/
|
||||
public function __construct( McpTransportContext $transport_context ) {
|
||||
$this->request_handler = new HttpRequestHandler( $transport_context );
|
||||
add_action( 'rest_api_init', [ $this, 'register_routes' ], 16 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the MCP OAuth REST route.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_routes(): void {
|
||||
$server = $this->request_handler->transport_context->mcp_server;
|
||||
|
||||
register_rest_route(
|
||||
$server->get_server_route_namespace(),
|
||||
$server->get_server_route(),
|
||||
[
|
||||
'methods' => [ 'POST', 'GET', 'DELETE' ],
|
||||
'callback' => [ $this, 'handle_request' ],
|
||||
'permission_callback' => [ $this, 'check_permission' ],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Permission callback — always returns true.
|
||||
*
|
||||
* Authentication is performed in handle_request() so we can return a 401
|
||||
* response with the required WWW-Authenticate header. WordPress's built-in
|
||||
* permission-callback mechanism only allows bool|\WP_Error returns and
|
||||
* cannot set custom response headers.
|
||||
*
|
||||
* @param \WP_REST_Request $request Incoming request.
|
||||
* @return true
|
||||
*/
|
||||
public function check_permission( \WP_REST_Request $request ): bool {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming MCP request.
|
||||
*
|
||||
* Validates the JWT Bearer token first. On failure, returns a 401 response
|
||||
* with a WWW-Authenticate challenge so OAuth 2.1 clients know how to
|
||||
* authenticate. On success, establishes the WordPress user context and
|
||||
* delegates to HttpRequestHandler for full MCP protocol compliance.
|
||||
*
|
||||
* @param \WP_REST_Request $request Incoming REST request.
|
||||
* @return \WP_REST_Response MCP response.
|
||||
*/
|
||||
public function handle_request( \WP_REST_Request $request ): \WP_REST_Response {
|
||||
$user_or_error = $this->validate_bearer_token( $request );
|
||||
|
||||
if ( is_wp_error( $user_or_error ) ) {
|
||||
return $this->build_auth_error_response( $user_or_error );
|
||||
}
|
||||
|
||||
McpLogger::log(
|
||||
'TRANSPORT',
|
||||
'JWT validated, delegating to MCP handler',
|
||||
[
|
||||
'user_id' => $user_or_error->ID,
|
||||
'method' => $request->get_method(),
|
||||
]
|
||||
);
|
||||
|
||||
$context = new HttpRequestContext( $request );
|
||||
return $this->request_handler->handle_request( $context );
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the JWT Bearer token from the Authorization header.
|
||||
*
|
||||
* Extracts the token, verifies the JWT signature and expiry, checks audience,
|
||||
* confirms the anchoring Application Password has not been revoked, and calls
|
||||
* wp_set_current_user() on success.
|
||||
*
|
||||
* @param \WP_REST_Request $request Incoming REST request.
|
||||
* @return \WP_User|\WP_Error Authenticated user, or an error.
|
||||
*/
|
||||
private function validate_bearer_token( \WP_REST_Request $request ) {
|
||||
$authorization = $request->get_header( 'Authorization' );
|
||||
$route = $request->get_route();
|
||||
$method = $request->get_method();
|
||||
|
||||
McpLogger::log(
|
||||
'TRANSPORT',
|
||||
'validate_bearer_token called',
|
||||
[
|
||||
'method' => $method,
|
||||
'route' => $route,
|
||||
'headers' => McpLogger::safe_request_headers(),
|
||||
'body' => McpLogger::safe_request_body(),
|
||||
]
|
||||
);
|
||||
|
||||
if ( empty( $authorization ) || 0 !== strpos( $authorization, 'Bearer ' ) ) {
|
||||
McpLogger::log(
|
||||
'TRANSPORT',
|
||||
'unauthenticated: no Bearer token',
|
||||
[
|
||||
'authorization_header' => $authorization ? substr( $authorization, 0, 20 ) . '...' : '(empty)',
|
||||
]
|
||||
);
|
||||
return $this->unauthenticated_error();
|
||||
}
|
||||
|
||||
$token = substr( $authorization, 7 );
|
||||
$secret = SecretManager::get_secret();
|
||||
$claims = JWT::decode( $token, $secret );
|
||||
|
||||
if ( null === $claims ) {
|
||||
McpLogger::log( 'TRANSPORT', 'rejected: JWT decode failed (signature invalid or token expired)' );
|
||||
return $this->unauthenticated_error( 'invalid_token', 'JWT signature invalid or token expired.' );
|
||||
}
|
||||
|
||||
// Audience must match the MCP OAuth REST endpoint.
|
||||
$expected_aud = get_rest_url( null, 'mcp/mcp-oauth-server' );
|
||||
$token_aud = $claims['aud'] ?? '';
|
||||
|
||||
if ( $token_aud !== $expected_aud ) {
|
||||
McpLogger::log(
|
||||
'TRANSPORT',
|
||||
'rejected: JWT audience mismatch',
|
||||
[
|
||||
'token_aud' => $token_aud,
|
||||
'expected_aud' => $expected_aud,
|
||||
]
|
||||
);
|
||||
return $this->unauthenticated_error( 'invalid_token', 'JWT audience mismatch.' );
|
||||
}
|
||||
|
||||
// Issuer must be this site. A staging clone sharing the same JWT secret
|
||||
// would otherwise allow cross-site token replay — the audience already
|
||||
// embeds the site URL, but verifying iss explicitly keeps this check in
|
||||
// step with the refresh-token flow in TokenEndpoint::handle_refresh_token().
|
||||
// home_url() matches what TokenEndpoint mints into iss and the home-based
|
||||
// base get_rest_url() uses for aud.
|
||||
$expected_iss = home_url();
|
||||
$token_iss = (string) ( $claims['iss'] ?? '' );
|
||||
|
||||
if ( $token_iss !== $expected_iss ) {
|
||||
McpLogger::log(
|
||||
'TRANSPORT',
|
||||
'rejected: JWT issuer mismatch',
|
||||
[
|
||||
'token_iss' => $token_iss,
|
||||
'expected_iss' => $expected_iss,
|
||||
]
|
||||
);
|
||||
return $this->unauthenticated_error( 'invalid_token', 'JWT issuer mismatch.' );
|
||||
}
|
||||
|
||||
$user_id = (int) ( $claims['sub'] ?? 0 );
|
||||
$app_pass_uuid = (string) ( $claims['app_pass_id'] ?? '' );
|
||||
|
||||
if ( 0 === $user_id || '' === $app_pass_uuid ) {
|
||||
McpLogger::log(
|
||||
'TRANSPORT',
|
||||
'rejected: malformed JWT claims',
|
||||
[
|
||||
'has_sub' => isset( $claims['sub'] ) ? 'yes' : 'no',
|
||||
'has_app_pass_id' => isset( $claims['app_pass_id'] ) ? 'yes' : 'no',
|
||||
'claims_keys' => array_keys( $claims ),
|
||||
]
|
||||
);
|
||||
return $this->unauthenticated_error( 'invalid_token', 'Malformed JWT claims.' );
|
||||
}
|
||||
|
||||
// Application Password revocation check.
|
||||
$app_pass = \WP_Application_Passwords::get_user_application_password( $user_id, $app_pass_uuid );
|
||||
|
||||
if ( ! is_array( $app_pass ) ) {
|
||||
McpLogger::log(
|
||||
'TRANSPORT',
|
||||
'rejected: Application Password revoked or not found',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'app_pass_uuid' => $app_pass_uuid,
|
||||
]
|
||||
);
|
||||
return $this->unauthenticated_error( 'invalid_token', 'MCP session has been revoked.' );
|
||||
}
|
||||
|
||||
$user = get_user_by( 'id', $user_id );
|
||||
|
||||
if ( false === $user ) {
|
||||
McpLogger::log( 'TRANSPORT', 'rejected: user not found', [ 'user_id' => $user_id ] );
|
||||
return $this->unauthenticated_error( 'invalid_token', 'User not found.' );
|
||||
}
|
||||
|
||||
// Set the current user so that get_current_user_id() returns the correct
|
||||
// user for any library code that runs after authentication (e.g.
|
||||
// HttpSessionValidator::create_session() in wordpress/mcp-adapter).
|
||||
wp_set_current_user( $user_id );
|
||||
|
||||
McpLogger::log(
|
||||
'TRANSPORT',
|
||||
'authentication successful',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'user_login' => $user->user_login,
|
||||
'app_pass_uuid' => $app_pass_uuid,
|
||||
'token_exp' => $claims['exp'] ?? 'unknown',
|
||||
'token_scope' => $claims['scope'] ?? 'unknown',
|
||||
]
|
||||
);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a WP_Error representing a 401 Unauthorized response.
|
||||
*
|
||||
* Includes a WWW-Authenticate Bearer challenge so OAuth 2.1 clients know
|
||||
* where to find the protected-resource metadata.
|
||||
*
|
||||
* @param string $code OAuth error code (default 'unauthorized').
|
||||
* @param string $description Human-readable message.
|
||||
* @return \WP_Error
|
||||
*/
|
||||
private function unauthenticated_error( string $code = 'unauthorized', string $description = '' ): \WP_Error {
|
||||
// home_url(): the .well-known document is served via a rewrite rule, so the
|
||||
// realm and resource_metadata URL must use the Site Address base.
|
||||
$base_url = home_url();
|
||||
|
||||
$www_auth = sprintf(
|
||||
'Bearer realm="%s", resource_metadata="%s/.well-known/oauth-protected-resource"',
|
||||
esc_url( $base_url ),
|
||||
esc_url( $base_url )
|
||||
);
|
||||
|
||||
if ( '' !== $description ) {
|
||||
$www_auth .= sprintf( ', error="%s", error_description="%s"', $code, $description );
|
||||
}
|
||||
|
||||
return new \WP_Error(
|
||||
'mcp_unauthorized',
|
||||
'' !== $description ? $description : __( 'MCP authentication required.', 'mcp-oauth' ),
|
||||
[
|
||||
'status' => 401,
|
||||
'WWW-Authenticate' => $www_auth,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a 401 REST response with a WWW-Authenticate header.
|
||||
*
|
||||
* @param \WP_Error $error Authentication error.
|
||||
* @return \WP_REST_Response
|
||||
*/
|
||||
private function build_auth_error_response( \WP_Error $error ): \WP_REST_Response {
|
||||
$error_data = $error->get_error_data();
|
||||
$www_auth = is_array( $error_data ) ? ( $error_data['WWW-Authenticate'] ?? '' ) : '';
|
||||
$status = is_array( $error_data ) ? (int) ( $error_data['status'] ?? 401 ) : 401;
|
||||
|
||||
$response = new \WP_REST_Response(
|
||||
[
|
||||
'code' => $error->get_error_code(),
|
||||
'message' => $error->get_error_message(),
|
||||
'data' => [ 'status' => $status ],
|
||||
],
|
||||
$status
|
||||
);
|
||||
|
||||
if ( '' !== $www_auth ) {
|
||||
$response->header( 'WWW-Authenticate', $www_auth );
|
||||
}
|
||||
|
||||
McpLogger::log(
|
||||
'TRANSPORT',
|
||||
'JWT validation failed, returning 401',
|
||||
[
|
||||
'error_code' => $error->get_error_code(),
|
||||
'has_www_auth' => '' !== $www_auth ? 'yes' : 'no',
|
||||
]
|
||||
);
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Transport;
|
||||
|
||||
use WP\MCP\Core\McpAdapter;
|
||||
use WP\MCP\Infrastructure\ErrorHandling\ErrorLogMcpErrorHandler;
|
||||
use WPMedia\MCP\OAuth\Context;
|
||||
|
||||
class Server {
|
||||
/**
|
||||
* OAuth server context.
|
||||
*
|
||||
* @var Context
|
||||
*/
|
||||
private $context;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param Context $context OAuth server context.
|
||||
*/
|
||||
public function __construct( Context $context ) {
|
||||
$this->context = $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the MCP server with the adapter.
|
||||
*
|
||||
* Creates an isolated server at /wp-json/mcp/mcp-oauth-server using the custom
|
||||
* OAuthHttpTransport for JWT Bearer authentication.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_server(): void {
|
||||
if ( ! class_exists( McpAdapter::class ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$adapter = McpAdapter::instance();
|
||||
|
||||
$adapter->create_server(
|
||||
'mcp-oauth-server',
|
||||
'mcp',
|
||||
'mcp-oauth-server',
|
||||
'MCP OAuth Server',
|
||||
'MCP Server with OAuth 2.1 authentication',
|
||||
'v1.0.0',
|
||||
[ OAuthHttpTransport::class ],
|
||||
ErrorLogMcpErrorHandler::class,
|
||||
$this->context->observability_handler(),
|
||||
[
|
||||
'mcp-adapter/discover-abilities',
|
||||
'mcp-adapter/get-ability-info',
|
||||
'mcp-adapter/execute-ability',
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
Vendored
+114
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Transport;
|
||||
|
||||
use WP\MCP\Abilities\DiscoverAbilitiesAbility;
|
||||
use WP\MCP\Abilities\ExecuteAbilityAbility;
|
||||
use WP\MCP\Abilities\GetAbilityInfoAbility;
|
||||
use WPMedia\MCP\OAuth\Context;
|
||||
|
||||
class ServerRegistrar {
|
||||
/**
|
||||
* MCP server instance.
|
||||
*
|
||||
* @var Server
|
||||
*/
|
||||
private $server;
|
||||
|
||||
/**
|
||||
* OAuth server context.
|
||||
*
|
||||
* @var Context
|
||||
*/
|
||||
private $context;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param Server $server MCP server instance.
|
||||
* @param Context $context OAuth server context.
|
||||
*/
|
||||
public function __construct( Server $server, Context $context ) {
|
||||
$this->server = $server;
|
||||
$this->context = $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the MCP server with the adapter.
|
||||
*
|
||||
* Creates an isolated server at /wp-json/mcp/mcp-oauth-server using the custom
|
||||
* OAuthHttpTransport for JWT Bearer authentication.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_server(): void {
|
||||
if ( ! $this->context->is_enabled() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->server->register_server();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether nobody else will register the shared mcp-adapter abilities.
|
||||
*
|
||||
* True only when the mcp-adapter package's *default* server is disabled
|
||||
* via the `mcp_adapter_create_default_server` filter — the only thing
|
||||
* that normally registers the 'mcp-adapter' category and its three
|
||||
* shared abilities (McpAdapter::maybe_create_default_server()).
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function must_register_shared_abilities_ourselves(): bool {
|
||||
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- reading the mcp-adapter package's own filter, not defining a new hook.
|
||||
return ! wpm_apply_filters_typed( 'boolean', 'mcp_adapter_create_default_server', true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the 'mcp-adapter' ability category ourselves when the
|
||||
* default server (which normally owns this) is disabled.
|
||||
*
|
||||
* Must run on the `wp_abilities_api_categories_init` action specifically
|
||||
* — the Abilities API rejects category registration anywhere else.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function ensure_default_category(): void {
|
||||
if ( ! $this->must_register_shared_abilities_ourselves() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
wp_register_ability_category(
|
||||
'mcp-adapter',
|
||||
[
|
||||
'label' => 'MCP Adapter',
|
||||
'description' => 'Abilities for the MCP Adapter',
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the mcp-adapter package's shared discover-abilities/
|
||||
* get-ability-info/execute-ability abilities ourselves when the default
|
||||
* server (which normally owns them) is disabled.
|
||||
*
|
||||
* Our server's tool list reuses these three abilities rather than
|
||||
* duplicating them, but they are normally only registered by the
|
||||
* mcp-adapter package's *default* server — gated behind the
|
||||
* `mcp_adapter_create_default_server` filter, disabled in our own test
|
||||
* bootstrap and something any site could legitimately disable.
|
||||
* Registering our own server must not depend on that unrelated toggle.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function ensure_shared_abilities_registered(): void {
|
||||
if ( ! $this->must_register_shared_abilities_ourselves() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
DiscoverAbilitiesAbility::register();
|
||||
GetAbilityInfoAbility::register();
|
||||
ExecuteAbilityAbility::register();
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
/**
|
||||
* Generic view renderer — loads a named template and executes it with a
|
||||
* `$data` array in scope.
|
||||
*
|
||||
* Usage:
|
||||
* $render->view( 'consent-screen', [ 'state' => $state ] );
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Views;
|
||||
|
||||
/**
|
||||
* Render.
|
||||
*
|
||||
* Never uses `extract()` — templates read `$data['key']` directly.
|
||||
*/
|
||||
class Render {
|
||||
|
||||
/**
|
||||
* Directory templates are loaded from.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private string $templates_dir;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param string|null $templates_dir Defaults to this class's own `templates/` directory.
|
||||
*/
|
||||
public function __construct( ?string $templates_dir = null ) {
|
||||
$this->templates_dir = $templates_dir ?? __DIR__ . '/templates/';
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a named template, making `$data` available in its scope.
|
||||
*
|
||||
* Echoes directly (no internal `ob_start()`) so an exception thrown
|
||||
* mid-template doesn't leave a dangling output buffer behind.
|
||||
*
|
||||
* @param string $view Template name, without the `.php` extension.
|
||||
* @param array<string, mixed> $data Data made available to the template as `$data`.
|
||||
* @return void
|
||||
*
|
||||
* @throws \RuntimeException When the named template file does not exist.
|
||||
*/
|
||||
public function view( string $view, array $data = [] ): void { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- $data is used via the required template's scope below.
|
||||
$path = $this->templates_dir . basename( $view ) . '.php';
|
||||
|
||||
if ( ! is_file( $path ) ) {
|
||||
throw new \RuntimeException( sprintf( 'View template not found: %s', $view ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- exception message, not HTML output; Render has no WordPress dependency.
|
||||
}
|
||||
|
||||
require $path;
|
||||
}
|
||||
}
|
||||
wp-content/plugins/seo-by-rank-math/vendor/wp-media/mcp-oauth/inc/Views/templates/consent-screen.php
Vendored
+175
@@ -0,0 +1,175 @@
|
||||
<?php
|
||||
/**
|
||||
* Consent screen view template.
|
||||
*
|
||||
* Rendered by AuthorizeCallback::output_consent_screen() via Render::view().
|
||||
* Pure presentation — assumes `$data` is fully populated and pre-validated.
|
||||
*
|
||||
* @var array<string, mixed> $data {
|
||||
* @type string $state OAuth state token.
|
||||
* @type string $client_name Requesting client's display name.
|
||||
* @type string $client_id esc_url'd client_id.
|
||||
* @type string $client_uri esc_url'd client_uri (may be empty).
|
||||
* @type bool $verified Whether the client's publisher is verified.
|
||||
* @type string $publisher Verified publisher name (may be empty).
|
||||
* @type string $site_name This site's display name.
|
||||
* @type string $consent_url esc_url'd POST target for the Allow/Deny form.
|
||||
* @type string $display_href client_uri if set, otherwise client_id.
|
||||
* }
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html <?php language_attributes(); ?>>
|
||||
<head>
|
||||
<meta charset="<?php bloginfo( 'charset' ); ?>">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title><?php echo esc_html( __( 'Authorize Access', 'mcp-oauth' ) . ' — ' . $data['site_name'] ); ?></title>
|
||||
<style>
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
|
||||
background: #f0f0f1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100vh;
|
||||
padding: 20px;
|
||||
}
|
||||
.consent-card {
|
||||
background: #fff;
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 1px 3px rgba(0,0,0,.13);
|
||||
max-width: 420px;
|
||||
width: 100%;
|
||||
padding: 36px 40px 40px;
|
||||
}
|
||||
.consent-card h1 {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
color: #1d2327;
|
||||
margin-bottom: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
.client-block {
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 3px;
|
||||
padding: 14px 16px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.client-name {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
color: #1d2327;
|
||||
}
|
||||
.client-name a { color: inherit; text-decoration: none; }
|
||||
.client-name a:hover { text-decoration: underline; }
|
||||
.client-url {
|
||||
font-size: .78rem;
|
||||
color: #646970;
|
||||
word-break: break-all;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.client-url a { color: #646970; }
|
||||
.verified-badge {
|
||||
display: inline-block;
|
||||
font-size: .72rem;
|
||||
font-weight: 600;
|
||||
color: #00a32a;
|
||||
background: #edfaef;
|
||||
border: 1px solid #a7e8b1;
|
||||
border-radius: 2px;
|
||||
padding: 2px 6px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.scope-text {
|
||||
font-size: .875rem;
|
||||
color: #3c434a;
|
||||
margin-bottom: 24px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.consent-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
.btn {
|
||||
flex: 1;
|
||||
padding: 9px 14px;
|
||||
font-size: .875rem;
|
||||
font-weight: 600;
|
||||
border-radius: 3px;
|
||||
border: 1px solid transparent;
|
||||
cursor: pointer;
|
||||
text-align: center;
|
||||
}
|
||||
.btn-allow {
|
||||
background: #2271b1;
|
||||
color: #fff;
|
||||
border-color: #2271b1;
|
||||
}
|
||||
.btn-allow:hover { background: #135e96; border-color: #135e96; }
|
||||
.btn-deny {
|
||||
background: #fff;
|
||||
color: #d63638;
|
||||
border-color: #d63638;
|
||||
}
|
||||
.btn-deny:hover { background: #fcf0f1; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="consent-card">
|
||||
<h1><?php esc_html_e( 'Authorize access to your site?', 'mcp-oauth' ); ?></h1>
|
||||
|
||||
<div class="client-block">
|
||||
<div class="client-name">
|
||||
<?php if ( '' !== $data['display_href'] ) : ?>
|
||||
<a href="<?php echo esc_url( $data['display_href'] ); ?>" rel="noopener noreferrer" target="_blank"><?php echo esc_html( $data['client_name'] ); ?></a>
|
||||
<?php else : ?>
|
||||
<?php echo esc_html( $data['client_name'] ); ?>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php if ( '' !== $data['client_id'] ) : ?>
|
||||
<div class="client-url">
|
||||
<?php esc_html_e( 'ID:', 'mcp-oauth' ); ?>
|
||||
<a href="<?php echo esc_url( $data['client_id'] ); ?>" rel="noopener noreferrer" target="_blank"><?php echo esc_html( $data['client_id'] ); ?></a>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<?php if ( $data['verified'] && '' !== $data['publisher'] ) : ?>
|
||||
<div class="verified-badge">
|
||||
<?php
|
||||
/* translators: %s: publisher name */
|
||||
printf( esc_html__( 'Verified publisher: %s', 'mcp-oauth' ), esc_html( $data['publisher'] ) );
|
||||
?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<p class="scope-text">
|
||||
<?php
|
||||
printf(
|
||||
/* translators: 1: client name, 2: site name, 3: application password name */
|
||||
esc_html__( '%1$s is requesting access to the MCP tools of %2$s on your behalf. If you approve this request, an application password (%3$s) will be created for your user and securely shared with %1$s. %1$s will then inherit your user\'s permissions on this website. You can revoke this access at any time by revoking the application password.', 'mcp-oauth' ),
|
||||
'<strong>' . esc_html( $data['client_name'] ) . '</strong>',
|
||||
'<strong>' . esc_html( $data['site_name'] ) . '</strong>',
|
||||
'<strong>' . esc_html( $data['client_name'] ) . '</strong>'
|
||||
);
|
||||
?>
|
||||
</p>
|
||||
|
||||
<form method="post" action="<?php echo esc_url( $data['consent_url'] ); ?>">
|
||||
<input type="hidden" name="state" value="<?php echo esc_attr( $data['state'] ); ?>">
|
||||
<?php wp_nonce_field( 'mcp_consent_' . $data['state'], 'mcp_consent_nonce' ); ?>
|
||||
<div class="consent-actions">
|
||||
<button type="submit" name="mcp_action" value="allow" class="btn btn-allow">
|
||||
<?php esc_html_e( 'Allow', 'mcp-oauth' ); ?>
|
||||
</button>
|
||||
<button type="submit" name="mcp_action" value="deny" class="btn btn-deny">
|
||||
<?php esc_html_e( 'Deny', 'mcp-oauth' ); ?>
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user