home
This commit is contained in:
+47
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "wp-media/apply-filters-typed",
|
||||
"description": "Library for usage of WordPress filters in a safe-type way",
|
||||
"type": "library",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"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-dev": {
|
||||
"phpcompatibility/phpcompatibility-wp": "^2.0",
|
||||
"phpstan/extension-installer": "^1.4",
|
||||
"szepeviktor/phpstan-wordpress": "^1.3",
|
||||
"wp-coding-standards/wpcs": "^3",
|
||||
"wp-media/phpunit": "^3"
|
||||
},
|
||||
"autoload": {
|
||||
"files": [
|
||||
"functions.php"
|
||||
]
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"WPMedia\\ApplyFiltersTyped\\Tests\\": "tests/"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"phpcs": "phpcs --basepath=.",
|
||||
"phpstan": "vendor/bin/phpstan analyze --memory-limit=2G --no-progress",
|
||||
"test-unit": "\"vendor/bin/phpunit\" --testsuite unit --colors=always --configuration tests/Unit/phpunit.xml.dist --coverage-php tests/report/unit.cov",
|
||||
"test-integration": "\"vendor/bin/phpunit\" --testsuite integration --colors=always --configuration tests/Integration/phpunit.xml.dist --coverage-php tests/report/integration.cov",
|
||||
"run-tests": [
|
||||
"@test-unit",
|
||||
"@test-integration"
|
||||
],
|
||||
"report-code-coverage": "\"vendor/bin/phpcov\" merge tests/report --clover tests/report/coverage.clover"
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Calls the callback functions that have been added to a filter hook in a typesafe manner.
|
||||
*
|
||||
* @param string $hook_name The name of the filter hook.
|
||||
* @param mixed $value The value to filter.
|
||||
* @param mixed ...$args Additional parameters to pass to the callback functions.
|
||||
* @return mixed The filtered value after all hooked functions are applied to it.
|
||||
*/
|
||||
function wpm_apply_filters_typesafe( $hook_name, $value, ...$args ) {
|
||||
return wpm_apply_filters_typed( gettype( $value ), $hook_name, $value, ...$args );
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls the callback functions that have been added to a filter hook in a typed manner.
|
||||
*
|
||||
* @param string $type The type the return value should have.
|
||||
* @param string $hook_name The name of the filter hook.
|
||||
* @param mixed $value The value to filter.
|
||||
* @param mixed ...$args Additional parameters to pass to the callback functions.
|
||||
* @return mixed The filtered value after all hooked functions are applied to it.
|
||||
*/
|
||||
function wpm_apply_filters_typed( $type, $hook_name, $value, ...$args ) {
|
||||
$next_value = apply_filters( $hook_name, $value, ...$args ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound
|
||||
|
||||
$types = [ $type ];
|
||||
|
||||
// Union types are separated by a pipe character.
|
||||
if ( preg_match( '/\|/i', $type ) ) {
|
||||
$types = explode( '|', $type );
|
||||
}
|
||||
|
||||
foreach ( $types as $type ) {
|
||||
if ( wpm_is_type( $type, $next_value ) ) {
|
||||
return $next_value;
|
||||
}
|
||||
}
|
||||
|
||||
// None of the types matched.
|
||||
_doing_it_wrong( __FUNCTION__, sprintf( 'Return value of "%1$s" filter must be of the type "%2$s", "%3$s" returned.', esc_attr( $hook_name ), esc_attr( $type ), esc_attr( gettype( $next_value ) ) ), '1.0.1' );
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given variable is a certain type.
|
||||
*
|
||||
* Returns whether `$value` is certain type.
|
||||
*
|
||||
* @since 1.0
|
||||
*
|
||||
* @param string $type The type to check.
|
||||
* @param mixed $value The variable to check.
|
||||
*
|
||||
* @return bool Whether the variable is of the type.
|
||||
*/
|
||||
function wpm_is_type( $type, $value ) {
|
||||
$type = strtolower( $type );
|
||||
|
||||
// Check if the type is nullable.
|
||||
if ( '?' === substr( $type, 0, 1 ) ) {
|
||||
$type = substr( $type, 1 );
|
||||
|
||||
if ( is_null( $value ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Check if the type is an array of a certain type.
|
||||
if ( '[]' === substr( $type, -2 ) ) {
|
||||
if ( ! is_array( $value ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$type = substr( $type, 0, -2 );
|
||||
|
||||
foreach ( $value as $item ) {
|
||||
if ( ! wpm_is_type( $type, $item ) ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
switch ( $type ) {
|
||||
case 'boolean':
|
||||
return is_bool( $value );
|
||||
case 'integer':
|
||||
return is_int( $value );
|
||||
case 'double':
|
||||
return is_float( $value );
|
||||
case 'string':
|
||||
return is_string( $value );
|
||||
case 'array':
|
||||
return is_array( $value );
|
||||
case 'object':
|
||||
return is_object( $value );
|
||||
case 'resource':
|
||||
case 'resource (closed)':
|
||||
return is_resource( $value );
|
||||
case 'null':
|
||||
return is_null( $value );
|
||||
case 'false':
|
||||
return false === $value;
|
||||
case 'true':
|
||||
return true === $value;
|
||||
case 'unknown_type':
|
||||
return false;
|
||||
default:
|
||||
/**
|
||||
* Filters whether the variable is of the type.
|
||||
* The dynamic portion of the hook name, `$type`, refers to the type of the variable.
|
||||
*
|
||||
* @since 1.0
|
||||
*
|
||||
* @param bool $is_type Is the variable of the type. Default false.
|
||||
* @param mixed $value The variable to check.
|
||||
*/
|
||||
return apply_filters( "wpm_is_type_{$type}", false, $value );
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
{
|
||||
"name": "wp-media/wp-mixpanel",
|
||||
"description": "WordPress Mixpanel Integration",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"authors": [
|
||||
{
|
||||
"name": "WP Media",
|
||||
"homepage": "https://github.com/wp-media/wp-mixpanel",
|
||||
"role": "Developer"
|
||||
}
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/wp-media/wp-mixpanel/issues"
|
||||
},
|
||||
"config": {
|
||||
"sort-packages": true,
|
||||
"allow-plugins": {
|
||||
"dealerdirect/phpcodesniffer-composer-installer": true,
|
||||
"phpstan/extension-installer": true
|
||||
}
|
||||
},
|
||||
"require": {
|
||||
"php": ">=7.3"
|
||||
},
|
||||
"require-dev": {
|
||||
"php-stubs/wordpress-tests-stubs": "^6.5",
|
||||
"phpcompatibility/phpcompatibility-wp": "^2.0",
|
||||
"phpstan/extension-installer": "^1.3",
|
||||
"phpstan/phpstan-mockery": "^2.0",
|
||||
"phpstan/phpstan-phpunit": "^2.0",
|
||||
"roave/security-advisories": "dev-master",
|
||||
"szepeviktor/phpstan-wordpress": "^2.0",
|
||||
"wp-coding-standards/wpcs": "^3",
|
||||
"wp-media/phpunit": "^3"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"WPMedia\\Mixpanel\\": "src/"
|
||||
},
|
||||
"classmap": [
|
||||
"src/Classes/"
|
||||
]
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"WPMedia\\Mixpanel\\Tests\\": "tests/"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"phpcs": "vendor/bin/phpcs",
|
||||
"phpcs:ci": "vendor/bin/phpcs --report-full --report-checkstyle=./phpcs-report.xml",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
Vendored
+66
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This a Base class which all Mixpanel classes extend from to provide some very basic
|
||||
* debugging and logging functionality. It also serves to persist $_options across the library.
|
||||
*
|
||||
*/
|
||||
class WPMedia_Base_MixpanelBase {
|
||||
|
||||
|
||||
/**
|
||||
* Default options that can be overridden via the $options constructor arg
|
||||
* @var array
|
||||
*/
|
||||
private $_defaults = array(
|
||||
"max_batch_size" => 50, // the max batch size Mixpanel will accept is 50,
|
||||
"max_queue_size" => 1000, // the max num of items to hold in memory before flushing
|
||||
"debug" => false, // enable/disable debug mode
|
||||
"consumer" => "curl", // which consumer to use
|
||||
"host" => "api.mixpanel.com", // the host name for api calls
|
||||
"events_endpoint" => "/track", // host relative endpoint for events
|
||||
"people_endpoint" => "/engage", // host relative endpoint for people updates
|
||||
"groups_endpoint" => "/groups", // host relative endpoint for groups updates
|
||||
"use_ssl" => true, // use ssl when available
|
||||
"error_callback" => null // callback to use on consumption failures
|
||||
);
|
||||
|
||||
|
||||
/**
|
||||
* An array of options to be used by the Mixpanel library.
|
||||
* @var array
|
||||
*/
|
||||
protected $_options = array();
|
||||
|
||||
|
||||
/**
|
||||
* Construct a new MixpanelBase object and merge custom options with defaults
|
||||
* @param array $options
|
||||
*/
|
||||
public function __construct($options = array()) {
|
||||
$options = array_merge($this->_defaults, $options);
|
||||
$this->_options = $options;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Log a message to PHP's error log
|
||||
* @param $msg
|
||||
*/
|
||||
protected function _log($msg) {
|
||||
$arr = debug_backtrace();
|
||||
$class = $arr[0]['class'];
|
||||
$line = $arr[0]['line'];
|
||||
error_log ( "[ $class - line $line ] : " . $msg );
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns true if in debug mode, false if in production mode
|
||||
* @return bool
|
||||
*/
|
||||
protected function _debug() {
|
||||
return isset($this->_options["debug"]) && $this->_options["debug"] == true;
|
||||
}
|
||||
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Provides some base methods for use by a Consumer implementation
|
||||
*/
|
||||
abstract class WPMedia_ConsumerStrategies_AbstractConsumer extends WPMedia_Base_MixpanelBase {
|
||||
|
||||
/**
|
||||
* Creates a new AbstractConsumer
|
||||
* @param array $options
|
||||
*/
|
||||
function __construct($options = array()) {
|
||||
|
||||
parent::__construct($options);
|
||||
|
||||
if ($this->_debug()) {
|
||||
$this->_log("Instantiated new Consumer");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode an array to be persisted
|
||||
* @param array $params
|
||||
* @return string
|
||||
*/
|
||||
protected function _encode($params) {
|
||||
return base64_encode(json_encode($params));
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles errors that occur in a consumer
|
||||
* @param $code
|
||||
* @param $msg
|
||||
*/
|
||||
protected function _handleError($code, $msg) {
|
||||
if (isset($this->_options['error_callback'])) {
|
||||
$handler = $this->_options['error_callback'];
|
||||
call_user_func($handler, $code, $msg);
|
||||
}
|
||||
|
||||
if ($this->_debug()) {
|
||||
$arr = debug_backtrace();
|
||||
$class = get_class($arr[0]['object']);
|
||||
$line = $arr[0]['line'];
|
||||
error_log ( "[ $class - line $line ] : " . print_r($msg, true) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Number of requests/batches that will be processed in parallel.
|
||||
* @return int
|
||||
*/
|
||||
public function getNumThreads() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist a batch of messages in whatever way the implementer sees fit
|
||||
* @param array $batch an array of messages to consume
|
||||
* @return boolean success or fail
|
||||
*/
|
||||
abstract function persist($batch);
|
||||
}
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Consumes messages and sends them to a host/endpoint using cURL
|
||||
*/
|
||||
class WPMedia_ConsumerStrategies_CurlConsumer extends WPMedia_ConsumerStrategies_AbstractConsumer {
|
||||
|
||||
/**
|
||||
* @var string the host to connect to (e.g. api.mixpanel.com)
|
||||
*/
|
||||
protected $_host;
|
||||
|
||||
|
||||
/**
|
||||
* @var string the host-relative endpoint to write to (e.g. /engage)
|
||||
*/
|
||||
protected $_endpoint;
|
||||
|
||||
|
||||
/**
|
||||
* @var int connect_timeout The number of seconds to wait while trying to connect. Default is 5 seconds.
|
||||
*/
|
||||
protected $_connect_timeout;
|
||||
|
||||
|
||||
/**
|
||||
* @var int timeout The maximum number of seconds to allow cURL call to execute. Default is 30 seconds.
|
||||
*/
|
||||
protected $_timeout;
|
||||
|
||||
|
||||
/**
|
||||
* @var string the protocol to use for the cURL connection
|
||||
*/
|
||||
protected $_protocol;
|
||||
|
||||
|
||||
/**
|
||||
* @var bool|null true to fork the cURL process (using exec) or false to use PHP's cURL extension. false by default
|
||||
*/
|
||||
protected $_fork = null;
|
||||
|
||||
|
||||
/**
|
||||
* @var int number of cURL requests to run in parallel. 1 by default
|
||||
*/
|
||||
protected $_num_threads;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new CurlConsumer and assigns properties from the $options array
|
||||
* @param array $options
|
||||
* @throws Exception
|
||||
*/
|
||||
function __construct($options) {
|
||||
parent::__construct($options);
|
||||
|
||||
$this->_host = $options['host'];
|
||||
$this->_endpoint = $options['endpoint'];
|
||||
$this->_connect_timeout = isset($options['connect_timeout']) ? $options['connect_timeout'] : 5;
|
||||
$this->_timeout = isset($options['timeout']) ? $options['timeout'] : 30;
|
||||
$this->_protocol = isset($options['use_ssl']) && $options['use_ssl'] == true ? "https" : "http";
|
||||
$this->_fork = isset($options['fork']) ? ($options['fork'] == true) : false;
|
||||
$this->_num_threads = isset($options['num_threads']) ? max(1, intval($options['num_threads'])) : 1;
|
||||
|
||||
// ensure the environment is workable for the given settings
|
||||
if ($this->_fork == true) {
|
||||
$exists = function_exists('exec');
|
||||
if (!$exists) {
|
||||
throw new Exception('The "exec" function must exist to use the cURL consumer in "fork" mode. Try setting fork = false or use another consumer.');
|
||||
}
|
||||
$disabled = explode(', ', ini_get('disable_functions'));
|
||||
$enabled = !in_array('exec', $disabled);
|
||||
if (!$enabled) {
|
||||
throw new Exception('The "exec" function must be enabled to use the cURL consumer in "fork" mode. Try setting fork = false or use another consumer.');
|
||||
}
|
||||
} else {
|
||||
if (!function_exists('curl_init')) {
|
||||
throw new Exception('The cURL PHP extension is required to use the cURL consumer with fork = false. Try setting fork = true or use another consumer.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Write to the given host/endpoint using either a forked cURL process or using PHP's cURL extension
|
||||
* @param array $batch
|
||||
* @return bool
|
||||
*/
|
||||
public function persist($batch) {
|
||||
if (count($batch) > 0) {
|
||||
$url = $this->_protocol . "://" . $this->_host . $this->_endpoint;
|
||||
if ($this->_fork) {
|
||||
$data = "data=" . $this->_encode($batch);
|
||||
return $this->_execute_forked($url, $data);
|
||||
} else {
|
||||
return $this->_execute($url, $batch);
|
||||
}
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Write using the cURL php extension
|
||||
* @param $url
|
||||
* @param $batch
|
||||
* @return bool
|
||||
*/
|
||||
protected function _execute($url, $batch) {
|
||||
if ($this->_debug()) {
|
||||
$this->_log("Making blocking cURL call to $url");
|
||||
}
|
||||
|
||||
$mh = curl_multi_init();
|
||||
$chs = array();
|
||||
|
||||
$batch_size = ceil(count($batch) / $this->_num_threads);
|
||||
for ($i=0; $i<$this->_num_threads && !empty($batch); $i++) {
|
||||
$ch = curl_init();
|
||||
$chs[] = $ch;
|
||||
$data = "data=" . $this->_encode(array_splice($batch, 0, $batch_size));
|
||||
curl_setopt($ch, CURLOPT_URL, $url);
|
||||
curl_setopt($ch, CURLOPT_HEADER, 0);
|
||||
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->_connect_timeout);
|
||||
curl_setopt($ch, CURLOPT_TIMEOUT, $this->_timeout);
|
||||
curl_setopt($ch, CURLOPT_POST, 1);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
|
||||
curl_multi_add_handle($mh,$ch);
|
||||
}
|
||||
|
||||
$running = 0;
|
||||
|
||||
do {
|
||||
curl_multi_exec($mh, $running);
|
||||
curl_multi_select($mh);
|
||||
} while ($running > 0);
|
||||
|
||||
$info = curl_multi_info_read($mh);
|
||||
|
||||
$error = false;
|
||||
foreach ($chs as $ch) {
|
||||
$response = curl_multi_getcontent($ch);
|
||||
if (false === $response) {
|
||||
$this->_handleError(curl_errno($ch), curl_error($ch));
|
||||
$error = true;
|
||||
}
|
||||
elseif ("1" != trim($response)) {
|
||||
$this->_handleError(0, $response);
|
||||
$error = true;
|
||||
}
|
||||
curl_multi_remove_handle($mh, $ch);
|
||||
}
|
||||
|
||||
if (CURLE_OK != $info['result']) {
|
||||
$this->_handleError($info['result'], "cURL error with code=".$info['result']);
|
||||
$error = true;
|
||||
}
|
||||
|
||||
curl_multi_close($mh);
|
||||
return !$error;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Write using a forked cURL process
|
||||
* @param $url
|
||||
* @param $data
|
||||
* @return bool
|
||||
*/
|
||||
protected function _execute_forked($url, $data) {
|
||||
|
||||
if ($this->_debug()) {
|
||||
$this->_log("Making forked cURL call to $url");
|
||||
}
|
||||
|
||||
$exec = 'curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d ' . $data . ' "' . $url . '"';
|
||||
|
||||
if(!$this->_debug()) {
|
||||
$exec .= " >/dev/null 2>&1 &";
|
||||
}
|
||||
|
||||
exec($exec, $output, $return_var);
|
||||
|
||||
if ($return_var != 0) {
|
||||
$this->_handleError($return_var, $output);
|
||||
}
|
||||
|
||||
return $return_var == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function getConnectTimeout()
|
||||
{
|
||||
return $this->_connect_timeout;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getEndpoint()
|
||||
{
|
||||
return $this->_endpoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool|null
|
||||
*/
|
||||
public function getFork()
|
||||
{
|
||||
return $this->_fork;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getHost()
|
||||
{
|
||||
return $this->_host;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getOptions()
|
||||
{
|
||||
return $this->_options;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getProtocol()
|
||||
{
|
||||
return $this->_protocol;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function getTimeout()
|
||||
{
|
||||
return $this->_timeout;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Number of requests/batches that will be processed in parallel using curl_multi_exec.
|
||||
* @return int
|
||||
*/
|
||||
public function getNumThreads() {
|
||||
return $this->_num_threads;
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Consumes messages and writes them to a file
|
||||
*/
|
||||
class WPMedia_ConsumerStrategies_FileConsumer extends WPMedia_ConsumerStrategies_AbstractConsumer {
|
||||
|
||||
/**
|
||||
* @var string path to a file that we want to write the messages to
|
||||
*/
|
||||
private $_file;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new FileConsumer and assigns properties from the $options array
|
||||
* @param array $options
|
||||
*/
|
||||
function __construct($options) {
|
||||
parent::__construct($options);
|
||||
|
||||
// what file to write to?
|
||||
$this->_file = isset($options['file']) ? $options['file'] : dirname(__FILE__)."/../../messages.txt";
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Append $batch to a file
|
||||
* @param array $batch
|
||||
* @return bool
|
||||
*/
|
||||
public function persist($batch) {
|
||||
if (count($batch) > 0) {
|
||||
return file_put_contents($this->_file, json_encode($batch)."\n", FILE_APPEND | LOCK_EX) !== false;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
+313
@@ -0,0 +1,313 @@
|
||||
<?php
|
||||
/**
|
||||
* Portions of this class were borrowed from
|
||||
* https://github.com/segmentio/analytics-php/blob/master/lib/Analytics/Consumer/Socket.php.
|
||||
* Thanks for the work!
|
||||
*
|
||||
* WWWWWW||WWWWWW
|
||||
* W W W||W W W
|
||||
* ||
|
||||
* ( OO )__________
|
||||
* / | \
|
||||
* /o o| MIT \
|
||||
* \___/||_||__||_|| *
|
||||
* || || || ||
|
||||
* _||_|| _||_||
|
||||
* (__|__|(__|__|
|
||||
* (The MIT License)
|
||||
*
|
||||
* Copyright (c) 2013 Segment.io Inc. friends@segment.io
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
|
||||
* documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the
|
||||
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
|
||||
* Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
|
||||
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
|
||||
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
require_once(dirname(__FILE__) . "/AbstractConsumer.php");
|
||||
|
||||
/**
|
||||
* Consumes messages and writes them to host/endpoint using a persistent socket
|
||||
*/
|
||||
class WPMedia_ConsumerStrategies_SocketConsumer extends WPMedia_ConsumerStrategies_AbstractConsumer {
|
||||
|
||||
/**
|
||||
* @var string the host to connect to (e.g. api.mixpanel.com)
|
||||
*/
|
||||
private $_host;
|
||||
|
||||
|
||||
/**
|
||||
* @var string the host-relative endpoint to write to (e.g. /engage)
|
||||
*/
|
||||
private $_endpoint;
|
||||
|
||||
|
||||
/**
|
||||
* @var int connect_timeout the socket connection timeout in seconds
|
||||
*/
|
||||
private $_connect_timeout;
|
||||
|
||||
|
||||
/**
|
||||
* @var string the protocol to use for the socket connection
|
||||
*/
|
||||
private $_protocol;
|
||||
|
||||
|
||||
/**
|
||||
* @var resource holds the socket resource
|
||||
*/
|
||||
private $_socket;
|
||||
|
||||
/**
|
||||
* @var bool whether or not to wait for a response
|
||||
*/
|
||||
private $_async;
|
||||
|
||||
/**
|
||||
* @var int the port to use for the socket connection
|
||||
*/
|
||||
private $_port;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new SocketConsumer and assigns properties from the $options array
|
||||
* @param array $options
|
||||
*/
|
||||
public function __construct($options = array()) {
|
||||
parent::__construct($options);
|
||||
|
||||
|
||||
$this->_host = $options['host'];
|
||||
$this->_endpoint = $options['endpoint'];
|
||||
$this->_connect_timeout = isset($options['connect_timeout']) ? $options['connect_timeout'] : 5;
|
||||
$this->_async = isset($options['async']) && $options['async'] === false ? false : true;
|
||||
|
||||
if (array_key_exists('use_ssl', $options) && $options['use_ssl'] == true) {
|
||||
$this->_protocol = "ssl";
|
||||
$this->_port = 443;
|
||||
} else {
|
||||
$this->_protocol = "tcp";
|
||||
$this->_port = 80;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Write using a persistent socket connection.
|
||||
* @param array $batch
|
||||
* @return bool
|
||||
*/
|
||||
public function persist($batch) {
|
||||
|
||||
$socket = $this->_getSocket();
|
||||
if (!is_resource($socket)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$data = "data=".$this->_encode($batch);
|
||||
|
||||
$body = "";
|
||||
$body.= "POST ".$this->_endpoint." HTTP/1.1\r\n";
|
||||
$body.= "Host: " . $this->_host . "\r\n";
|
||||
$body.= "Content-Type: application/x-www-form-urlencoded\r\n";
|
||||
$body.= "Accept: application/json\r\n";
|
||||
$body.= "Content-length: " . strlen($data) . "\r\n";
|
||||
$body.= "\r\n";
|
||||
$body.= $data;
|
||||
|
||||
return $this->_write($socket, $body);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Return cached socket if open or create a new persistent socket
|
||||
* @return bool|resource
|
||||
*/
|
||||
private function _getSocket() {
|
||||
if(is_resource($this->_socket)) {
|
||||
|
||||
if ($this->_debug()) {
|
||||
$this->_log("Using existing socket");
|
||||
}
|
||||
|
||||
return $this->_socket;
|
||||
} else {
|
||||
|
||||
if ($this->_debug()) {
|
||||
$this->_log("Creating new socket at ".time());
|
||||
}
|
||||
|
||||
return $this->_createSocket();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to open a new socket connection, cache it, and return the resource
|
||||
* @param bool $retry
|
||||
* @return bool|resource
|
||||
*/
|
||||
private function _createSocket($retry = true) {
|
||||
try {
|
||||
$socket = pfsockopen($this->_protocol . "://" . $this->_host, $this->_port, $err_no, $err_msg, $this->_connect_timeout);
|
||||
|
||||
if ($this->_debug()) {
|
||||
$this->_log("Opening socket connection to " . $this->_protocol . "://" . $this->_host . ":" . $this->_port);
|
||||
}
|
||||
|
||||
if ($err_no != 0) {
|
||||
$this->_handleError($err_no, $err_msg);
|
||||
return $retry == true ? $this->_createSocket(false) : false;
|
||||
} else {
|
||||
// cache the socket
|
||||
$this->_socket = $socket;
|
||||
return $socket;
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
$this->_handleError($e->getCode(), $e->getMessage());
|
||||
return $retry == true ? $this->_createSocket(false) : false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to close and dereference a socket resource
|
||||
*/
|
||||
private function _destroySocket() {
|
||||
$socket = $this->_socket;
|
||||
$this->_socket = null;
|
||||
fclose($socket);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Write $data through the given $socket
|
||||
* @param $socket
|
||||
* @param $data
|
||||
* @param bool $retry
|
||||
* @return bool
|
||||
*/
|
||||
private function _write($socket, $data, $retry = true) {
|
||||
|
||||
$bytes_sent = 0;
|
||||
$bytes_total = strlen($data);
|
||||
$socket_closed = false;
|
||||
$success = true;
|
||||
$max_bytes_per_write = 8192;
|
||||
|
||||
// if we have no data to write just return true
|
||||
if ($bytes_total == 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// try to write the data
|
||||
while (!$socket_closed && $bytes_sent < $bytes_total) {
|
||||
|
||||
try {
|
||||
$bytes = fwrite($socket, $data, $max_bytes_per_write);
|
||||
|
||||
if ($this->_debug()) {
|
||||
$this->_log("Socket wrote ".$bytes." bytes");
|
||||
}
|
||||
|
||||
// if we actually wrote data, then remove the written portion from $data left to write
|
||||
if ($bytes > 0) {
|
||||
$data = substr($data, $max_bytes_per_write);
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
$this->_handleError($e->getCode(), $e->getMessage());
|
||||
$socket_closed = true;
|
||||
}
|
||||
|
||||
if (isset($bytes) && $bytes) {
|
||||
$bytes_sent += $bytes;
|
||||
} else {
|
||||
$socket_closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
// create a new socket if the current one is closed and retry the message
|
||||
if ($socket_closed) {
|
||||
|
||||
$this->_destroySocket();
|
||||
|
||||
if ($retry) {
|
||||
if ($this->_debug()) {
|
||||
$this->_log("Retrying socket write...");
|
||||
}
|
||||
$socket = $this->_getSocket();
|
||||
if ($socket) return $this->_write($socket, $data, false);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// only wait for the response in debug mode or if we explicitly want to be synchronous
|
||||
if ($this->_debug() || !$this->_async) {
|
||||
$res = $this->handleResponse(fread($socket, 2048));
|
||||
if ($res["status"] != "200") {
|
||||
$this->_handleError($res["status"], $res["body"]);
|
||||
$success = false;
|
||||
}
|
||||
}
|
||||
|
||||
return $success;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Parse the response from a socket write (only used for debugging)
|
||||
* @param $response
|
||||
* @return array
|
||||
*/
|
||||
private function handleResponse($response) {
|
||||
|
||||
$lines = explode("\n", $response);
|
||||
|
||||
// extract headers
|
||||
$headers = array();
|
||||
foreach($lines as $line) {
|
||||
$kvsplit = explode(":", $line);
|
||||
if (count($kvsplit) == 2) {
|
||||
$header = $kvsplit[0];
|
||||
$value = $kvsplit[1];
|
||||
$headers[$header] = trim($value);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// extract status
|
||||
$line_one_exploded = explode(" ", $lines[0]);
|
||||
$status = $line_one_exploded[1];
|
||||
|
||||
// extract body
|
||||
$body = $lines[count($lines) - 1];
|
||||
|
||||
// if the connection has been closed lets kill the socket
|
||||
if (isset($headers["Connection"]) and $headers['Connection'] == "close") {
|
||||
$this->_destroySocket();
|
||||
if ($this->_debug()) {
|
||||
$this->_log("Server told us connection closed so lets destroy the socket so it'll reconnect on next call");
|
||||
}
|
||||
}
|
||||
|
||||
$ret = array(
|
||||
"status" => $status,
|
||||
"body" => $body,
|
||||
);
|
||||
|
||||
return $ret;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+308
@@ -0,0 +1,308 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This is the main class for the Mixpanel PHP Library which provides all of the methods you need to track events,
|
||||
* create/update profiles and group profiles.
|
||||
*
|
||||
* Architecture
|
||||
* -------------
|
||||
*
|
||||
* This library is built such that all messages are buffered in an in-memory "queue"
|
||||
* The queue will be automatically flushed at the end of every request. Alternatively, you can call "flush()" manually
|
||||
* at any time. Flushed messages will be passed to a Consumer's "persist" method. The library comes with a handful of
|
||||
* Consumers. The "CurlConsumer" is used by default which will send the messages to Mixpanel using forked cURL processes.
|
||||
* You can implement your own custom Consumer to customize how a message is sent to Mixpanel. This can be useful when
|
||||
* you want to put messages onto a distributed queue (such as ActiveMQ or Kestrel) instead of writing to Mixpanel in
|
||||
* the user thread.
|
||||
*
|
||||
* Options
|
||||
* -------------
|
||||
*
|
||||
* <table width="100%" cellpadding="5">
|
||||
* <tr>
|
||||
* <th>Option</th>
|
||||
* <th>Description</th>
|
||||
* <th>Default</th>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>max_queue_size</td>
|
||||
* <td>The maximum number of items to buffer in memory before flushing</td>
|
||||
* <td>1000</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>debug</td>
|
||||
* <td>Enable/disable debug mode</td>
|
||||
* <td>false</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>consumer</td>
|
||||
* <td>The consumer to use for writing messages</td>
|
||||
* <td>curl</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>consumers</td>
|
||||
* <td>An array of custom consumers in the format array(consumer_key => class_name)</td>
|
||||
* <td>null</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>host</td>
|
||||
* <td>The host name for api calls (used by some consumers)</td>
|
||||
* <td>api.mixpanel.com</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>events_endpoint</td>
|
||||
* <td>The endpoint for tracking events (relative to the host)</td>
|
||||
* <td>/events</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>people_endpoint</td>
|
||||
* <td>The endpoint for making people updates (relative to the host)</td>
|
||||
* <td>/engage</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>use_ssl</td>
|
||||
* <td>Tell the consumer whether or not to use ssl (when available)</td>
|
||||
* <td>true</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>error_callback</td>
|
||||
* <td>The name of a function to be called on consumption failures</td>
|
||||
* <td>null</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>connect_timeout</td>
|
||||
* <td>In both the SocketConsumer and CurlConsumer, this is used for the connection timeout (i.e. How long it has take to actually make a connection).
|
||||
* <td>5</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>timeout</td>
|
||||
* <td>In the CurlConsumer (non-forked), it is used to determine how long the cURL call has to execute.
|
||||
* <td>30</td>
|
||||
* </tr>
|
||||
* </table>
|
||||
*
|
||||
* Example: Tracking an Event
|
||||
* -------------
|
||||
*
|
||||
* $mp = Mixpanel::getInstance("MY_TOKEN");
|
||||
*
|
||||
* $mp->track("My Event");
|
||||
*
|
||||
* Example: Setting Profile Properties
|
||||
* -------------
|
||||
*
|
||||
* $mp = Mixpanel::getInstance("MY_TOKEN", array("use_ssl" => false));
|
||||
*
|
||||
* $mp->people->set(12345, array(
|
||||
* '$first_name' => "John",
|
||||
* '$last_name' => "Doe",
|
||||
* '$email' => "john.doe@example.com",
|
||||
* '$phone' => "5555555555",
|
||||
* 'Favorite Color' => "red"
|
||||
* ));
|
||||
*
|
||||
*/
|
||||
class WPMedia_Mixpanel extends WPMedia_Base_MixpanelBase {
|
||||
|
||||
|
||||
/**
|
||||
* An instance of the MixpanelPeople class (used to create/update profiles)
|
||||
* @var WPMedia_Producers_MixpanelPeople
|
||||
*/
|
||||
public $people;
|
||||
|
||||
|
||||
/**
|
||||
* An instance of the MixpanelEvents class
|
||||
* @var WPMedia_Producers_MixpanelEvents
|
||||
*/
|
||||
private $_events;
|
||||
|
||||
/**
|
||||
* An instance of the MixpanelGroups class (used to create/update group profiles)
|
||||
* @var WPMedia_Producers_MixpanelPeople
|
||||
*/
|
||||
public $group;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Instances' list of the Mixpanel class (for singleton use, splitted by token)
|
||||
* @var WPMedia_Mixpanel[]
|
||||
*/
|
||||
private static $_instances = array();
|
||||
|
||||
|
||||
/**
|
||||
* Instantiates a new Mixpanel instance.
|
||||
* @param $token
|
||||
* @param array $options
|
||||
*/
|
||||
public function __construct($token, $options = array()) {
|
||||
parent::__construct($options);
|
||||
$this->people = new WPMedia_Producers_MixpanelPeople($token, $options);
|
||||
$this->_events = new WPMedia_Producers_MixpanelEvents($token, $options);
|
||||
$this->group = new WPMedia_Producers_MixpanelGroups($token, $options);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a singleton instance of Mixpanel
|
||||
* @param $token
|
||||
* @param array $options
|
||||
* @return WPMedia_Mixpanel
|
||||
*/
|
||||
public static function getInstance($token, $options = array()) {
|
||||
if(!isset(self::$_instances[$token])) {
|
||||
self::$_instances[$token] = new WPMedia_Mixpanel($token, $options);
|
||||
}
|
||||
return self::$_instances[$token];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add an array representing a message to be sent to Mixpanel to the in-memory queue.
|
||||
* @param array $message
|
||||
*/
|
||||
public function enqueue($message = array()) {
|
||||
$this->_events->enqueue($message);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add an array representing a list of messages to be sent to Mixpanel to a queue.
|
||||
* @param array $messages
|
||||
*/
|
||||
public function enqueueAll($messages = array()) {
|
||||
$this->_events->enqueueAll($messages);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Flush the events queue
|
||||
* @param int $desired_batch_size
|
||||
*/
|
||||
public function flush($desired_batch_size = 50) {
|
||||
$this->_events->flush($desired_batch_size);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Empty the events queue
|
||||
*/
|
||||
public function reset() {
|
||||
$this->_events->reset();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Identify the user you want to associate to tracked events. The $anon_id must be UUID v4 format and not already merged to an $identified_id.
|
||||
* All identify calls with a new and valid $anon_id will trigger a track $identify event, and merge to the $identified_id.
|
||||
* @param string|int $user_id
|
||||
* @param string|int $anon_id [optional]
|
||||
*/
|
||||
public function identify($user_id, $anon_id = null) {
|
||||
$this->_events->identify($user_id, $anon_id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Track an event defined by $event associated with metadata defined by $properties
|
||||
* @param string $event
|
||||
* @param array $properties
|
||||
*/
|
||||
public function track($event, $properties = array()) {
|
||||
$this->_events->track($event, $properties);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Register a property to be sent with every event.
|
||||
*
|
||||
* If the property has already been registered, it will be
|
||||
* overwritten. NOTE: Registered properties are only persisted for the life of the Mixpanel class instance.
|
||||
* @param string $property
|
||||
* @param mixed $value
|
||||
*/
|
||||
public function register($property, $value) {
|
||||
$this->_events->register($property, $value);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Register multiple properties to be sent with every event.
|
||||
*
|
||||
* If any of the properties have already been registered,
|
||||
* they will be overwritten. NOTE: Registered properties are only persisted for the life of the Mixpanel class
|
||||
* instance.
|
||||
* @param array $props_and_vals
|
||||
*/
|
||||
public function registerAll($props_and_vals = array()) {
|
||||
$this->_events->registerAll($props_and_vals);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Register a property to be sent with every event.
|
||||
*
|
||||
* If the property has already been registered, it will NOT be
|
||||
* overwritten. NOTE: Registered properties are only persisted for the life of the Mixpanel class instance.
|
||||
* @param $property
|
||||
* @param $value
|
||||
*/
|
||||
public function registerOnce($property, $value) {
|
||||
$this->_events->registerOnce($property, $value);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Register multiple properties to be sent with every event.
|
||||
*
|
||||
* If any of the properties have already been registered,
|
||||
* they will NOT be overwritten. NOTE: Registered properties are only persisted for the life of the Mixpanel class
|
||||
* instance.
|
||||
* @param array $props_and_vals
|
||||
*/
|
||||
public function registerAllOnce($props_and_vals = array()) {
|
||||
$this->_events->registerAllOnce($props_and_vals);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Un-register an property to be sent with every event.
|
||||
* @param string $property
|
||||
*/
|
||||
public function unregister($property) {
|
||||
$this->_events->unregister($property);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Un-register a list of properties to be sent with every event.
|
||||
* @param array $properties
|
||||
*/
|
||||
public function unregisterAll($properties) {
|
||||
$this->_events->unregisterAll($properties);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get a property that is set to be sent with every event
|
||||
* @param string $property
|
||||
* @return mixed
|
||||
*/
|
||||
public function getProperty($property)
|
||||
{
|
||||
return $this->_events->getProperty($property);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* An alias to be merged with the distinct_id. Each alias can only map to one distinct_id.
|
||||
* This is helpful when you want to associate a generated id (such as a session id) to a user id or username.
|
||||
* @param string|int $distinct_id
|
||||
* @param string|int $alias
|
||||
*/
|
||||
public function createAlias($distinct_id, $alias) {
|
||||
$this->_events->createAlias($distinct_id, $alias);
|
||||
}
|
||||
}
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
<?php
|
||||
|
||||
if (!function_exists('json_encode')) {
|
||||
throw new Exception('The JSON PHP extension is required.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides some base methods for use by a message Producer
|
||||
*/
|
||||
abstract class WPMedia_Producers_MixpanelBaseProducer extends WPMedia_Base_MixpanelBase {
|
||||
|
||||
|
||||
/**
|
||||
* @var string a token associated to a Mixpanel project
|
||||
*/
|
||||
protected $_token;
|
||||
|
||||
|
||||
/**
|
||||
* @var array a queue to hold messages in memory before flushing in batches
|
||||
*/
|
||||
private $_queue = array();
|
||||
|
||||
|
||||
/**
|
||||
* @var WPMedia_ConsumerStrategies_AbstractConsumer the consumer to use when flushing messages
|
||||
*/
|
||||
private $_consumer = null;
|
||||
|
||||
|
||||
/**
|
||||
* @var array The list of available consumers
|
||||
*/
|
||||
private $_consumers = array(
|
||||
"file" => "WPMedia_ConsumerStrategies_FileConsumer",
|
||||
"curl" => "WPMedia_ConsumerStrategies_CurlConsumer",
|
||||
"socket" => "WPMedia_ConsumerStrategies_SocketConsumer",
|
||||
);
|
||||
|
||||
|
||||
/**
|
||||
* If the queue reaches this size we'll auto-flush to prevent out of memory errors
|
||||
* @var int
|
||||
*/
|
||||
protected $_max_queue_size = 1000;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new MixpanelBaseProducer, assings Mixpanel project token, registers custom Consumers, and instantiates
|
||||
* the desired consumer
|
||||
* @param $token
|
||||
* @param array $options
|
||||
*/
|
||||
public function __construct($token, $options = array()) {
|
||||
|
||||
parent::__construct($options);
|
||||
|
||||
// register any customer consumers
|
||||
if (isset($options["consumers"])) {
|
||||
$this->_consumers = array_merge($this->_consumers, $options['consumers']);
|
||||
}
|
||||
|
||||
// set max queue size
|
||||
if (isset($options["max_queue_size"])) {
|
||||
$this->_max_queue_size = $options['max_queue_size'];
|
||||
}
|
||||
|
||||
// associate token
|
||||
$this->_token = $token;
|
||||
|
||||
if ($this->_debug()) {
|
||||
$this->_log("Using token: ".$this->_token);
|
||||
}
|
||||
|
||||
// instantiate the chosen consumer
|
||||
$this->_consumer = $this->_getConsumer();
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Flush the queue when we destruct the client with retries
|
||||
*/
|
||||
public function __destruct() {
|
||||
$attempts = 0;
|
||||
$max_attempts = 10;
|
||||
$success = false;
|
||||
while (!$success && $attempts < $max_attempts) {
|
||||
if ($this->_debug()) {
|
||||
$this->_log("destruct flush attempt #".($attempts+1));
|
||||
}
|
||||
$success = $this->flush();
|
||||
$attempts++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Iterate the queue and write in batches using the instantiated Consumer Strategy
|
||||
* @param int $desired_batch_size
|
||||
* @return bool whether or not the flush was successful
|
||||
*/
|
||||
public function flush($desired_batch_size = 50) {
|
||||
$queue_size = count($this->_queue);
|
||||
$succeeded = true;
|
||||
$num_threads = $this->_consumer->getNumThreads();
|
||||
|
||||
if ($this->_debug()) {
|
||||
$this->_log("Flush called - queue size: ".$queue_size);
|
||||
}
|
||||
|
||||
while($queue_size > 0 && $succeeded) {
|
||||
$batch_size = min(array($queue_size, $desired_batch_size*$num_threads, $this->_options['max_batch_size']*$num_threads));
|
||||
$batch = array_splice($this->_queue, 0, $batch_size);
|
||||
$succeeded = $this->_persist($batch);
|
||||
|
||||
if (!$succeeded) {
|
||||
if ($this->_debug()) {
|
||||
$this->_log("Batch consumption failed!");
|
||||
}
|
||||
$this->_queue = array_merge($batch, $this->_queue);
|
||||
|
||||
if ($this->_debug()) {
|
||||
$this->_log("added batch back to queue, queue size is now $queue_size");
|
||||
}
|
||||
}
|
||||
|
||||
$queue_size = count($this->_queue);
|
||||
|
||||
if ($this->_debug()) {
|
||||
$this->_log("Batch of $batch_size consumed, queue size is now $queue_size");
|
||||
}
|
||||
}
|
||||
return $succeeded;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Empties the queue without persisting any of the messages
|
||||
*/
|
||||
public function reset() {
|
||||
$this->_queue = array();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the in-memory queue
|
||||
* @return array
|
||||
*/
|
||||
public function getQueue() {
|
||||
return $this->_queue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current Mixpanel project token
|
||||
* @return string
|
||||
*/
|
||||
public function getToken() {
|
||||
return $this->_token;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Given a strategy type, return a new PersistenceStrategy object
|
||||
* @return WPMedia_ConsumerStrategies_AbstractConsumer
|
||||
*/
|
||||
protected function _getConsumer() {
|
||||
$key = $this->_options['consumer'];
|
||||
$Strategy = $this->_consumers[$key];
|
||||
if ($this->_debug()) {
|
||||
$this->_log("Using consumer: " . $key . " -> " . $Strategy);
|
||||
}
|
||||
$this->_options['endpoint'] = $this->_getEndpoint();
|
||||
|
||||
return new $Strategy($this->_options);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add an array representing a message to be sent to Mixpanel to a queue.
|
||||
* @param array $message
|
||||
*/
|
||||
public function enqueue($message = array()) {
|
||||
array_push($this->_queue, $message);
|
||||
|
||||
// force a flush if we've reached our threshold
|
||||
if (count($this->_queue) > $this->_max_queue_size) {
|
||||
$this->flush();
|
||||
}
|
||||
|
||||
if ($this->_debug()) {
|
||||
$this->_log("Queued message: ".json_encode($message));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add an array representing a list of messages to be sent to Mixpanel to a queue.
|
||||
* @param array $messages
|
||||
*/
|
||||
public function enqueueAll($messages = array()) {
|
||||
foreach($messages as $message) {
|
||||
$this->enqueue($message);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Given an array of messages, persist it with the instantiated Persistence Strategy
|
||||
* @param $message
|
||||
* @return mixed
|
||||
*/
|
||||
protected function _persist($message) {
|
||||
return $this->_consumer->persist($message);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Return the endpoint that should be used by a consumer that consumes messages produced by this producer.
|
||||
* @return string
|
||||
*/
|
||||
abstract function _getEndpoint();
|
||||
|
||||
}
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Provides an API to track events on Mixpanel
|
||||
*/
|
||||
class WPMedia_Producers_MixpanelEvents extends WPMedia_Producers_MixpanelBaseProducer {
|
||||
|
||||
/**
|
||||
* An array of properties to attach to every tracked event
|
||||
* @var array
|
||||
*/
|
||||
private $_super_properties = array("mp_lib" => "php");
|
||||
|
||||
|
||||
/**
|
||||
* Track an event defined by $event associated with metadata defined by $properties
|
||||
* @param string $event
|
||||
* @param array $properties
|
||||
*/
|
||||
public function track($event, $properties = array()) {
|
||||
|
||||
// if no token is passed in, use current token
|
||||
if (!isset($properties["token"])) $properties['token'] = $this->_token;
|
||||
|
||||
// if no time is passed in, use the current time
|
||||
if (!isset($properties["time"])) $properties['time'] = microtime(true);
|
||||
|
||||
$params['event'] = $event;
|
||||
$params['properties'] = array_merge($this->_super_properties, $properties);
|
||||
|
||||
$this->enqueue($params);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Register a property to be sent with every event. If the property has already been registered, it will be
|
||||
* overwritten.
|
||||
* @param string $property
|
||||
* @param mixed $value
|
||||
*/
|
||||
public function register($property, $value) {
|
||||
$this->_super_properties[$property] = $value;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Register multiple properties to be sent with every event. If any of the properties have already been registered,
|
||||
* they will be overwritten.
|
||||
* @param array $props_and_vals
|
||||
*/
|
||||
public function registerAll($props_and_vals = array()) {
|
||||
foreach($props_and_vals as $property => $value) {
|
||||
$this->register($property, $value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Register a property to be sent with every event. If the property has already been registered, it will NOT be
|
||||
* overwritten.
|
||||
* @param $property
|
||||
* @param $value
|
||||
*/
|
||||
public function registerOnce($property, $value) {
|
||||
if (!isset($this->_super_properties[$property])) {
|
||||
$this->register($property, $value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Register multiple properties to be sent with every event. If any of the properties have already been registered,
|
||||
* they will NOT be overwritten.
|
||||
* @param array $props_and_vals
|
||||
*/
|
||||
public function registerAllOnce($props_and_vals = array()) {
|
||||
foreach($props_and_vals as $property => $value) {
|
||||
if (!isset($this->_super_properties[$property])) {
|
||||
$this->register($property, $value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Un-register an property to be sent with every event.
|
||||
* @param string $property
|
||||
*/
|
||||
public function unregister($property) {
|
||||
unset($this->_super_properties[$property]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Un-register a list of properties to be sent with every event.
|
||||
* @param array $properties
|
||||
*/
|
||||
public function unregisterAll($properties) {
|
||||
foreach($properties as $property) {
|
||||
$this->unregister($property);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get a property that is set to be sent with every event
|
||||
* @param string $property
|
||||
* @return mixed
|
||||
*/
|
||||
public function getProperty($property) {
|
||||
return $this->_super_properties[$property];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Identify the user you want to associate to tracked events. The $anon_id must be UUID v4 format (optionally with the
|
||||
* prefix '$device:') and not already merged to an $identified_id. All identify calls with a new and valid $anon_id will
|
||||
* trigger a track $identify event, and merge to the $identified_id.
|
||||
* @param string|int $user_id
|
||||
* @param string|int $anon_id [optional]
|
||||
*/
|
||||
public function identify($user_id, $anon_id = null) {
|
||||
$this->register("distinct_id", $user_id);
|
||||
|
||||
$UUIDv4 = '/^(\$device:)?[a-zA-Z0-9]*-[a-zA-Z0-9]*-[a-zA-Z0-9]*-[a-zA-Z0-9]*-[a-zA-Z0-9]*$/i';
|
||||
if (!empty($anon_id)) {
|
||||
if (preg_match($UUIDv4, $anon_id) !== 1) {
|
||||
/* not a valid uuid */
|
||||
error_log("Running Identify method (identified_id: $user_id, anon_id: $anon_id) failed, anon_id not in UUID v4 format");
|
||||
} else {
|
||||
$this->track('$identify', array(
|
||||
'$identified_id' => $user_id,
|
||||
'$anon_id' => $anon_id
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* An alias to be merged with the distinct_id. Each alias can only map to one distinct_id.
|
||||
* This is helpful when you want to associate a generated id (such as a session id) to a user id or username.
|
||||
*
|
||||
* Because aliasing can be extremely vulnerable to race conditions and ordering issues, we'll make a synchronous
|
||||
* call directly to Mixpanel when this method is called. If it fails we'll throw an Exception as subsequent
|
||||
* events are likely to be incorrectly tracked.
|
||||
* @param string|int $distinct_id
|
||||
* @param string|int $alias
|
||||
* @return array $msg
|
||||
* @throws Exception
|
||||
*/
|
||||
public function createAlias($distinct_id, $alias) {
|
||||
$msg = array(
|
||||
"event" => '$create_alias',
|
||||
"properties" => array("distinct_id" => $distinct_id, "alias" => $alias, "token" => $this->_token)
|
||||
);
|
||||
|
||||
// Save the current fork/async options
|
||||
$old_fork = isset($this->_options['fork']) ? $this->_options['fork'] : false;
|
||||
$old_async = isset($this->_options['async']) ? $this->_options['async'] : false;
|
||||
|
||||
// Override fork/async to make the new consumer synchronous
|
||||
$this->_options['fork'] = false;
|
||||
$this->_options['async'] = false;
|
||||
|
||||
// The name is ambiguous, but this creates a new consumer with current $this->_options
|
||||
$consumer = $this->_getConsumer();
|
||||
$success = $consumer->persist(array($msg));
|
||||
|
||||
// Restore the original fork/async settings
|
||||
$this->_options['fork'] = $old_fork;
|
||||
$this->_options['async'] = $old_async;
|
||||
|
||||
if (!$success) {
|
||||
error_log("Creating Mixpanel Alias (distinct id: $distinct_id, alias: $alias) failed");
|
||||
throw new Exception("Tried to create an alias but the call was not successful");
|
||||
} else {
|
||||
return $msg;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the "events" endpoint
|
||||
* @return string
|
||||
*/
|
||||
function _getEndpoint() {
|
||||
return $this->_options['events_endpoint'];
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Provides an API to create/update group profiles on Mixpanel
|
||||
*/
|
||||
class WPMedia_Producers_MixpanelGroups extends WPMedia_Producers_MixpanelBaseProducer {
|
||||
|
||||
/**
|
||||
* Internal method to prepare a message given the message data
|
||||
* @param $group_key
|
||||
* @param $group_id
|
||||
* @param $operation
|
||||
* @param $value
|
||||
* @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the group Profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time
|
||||
* @return array
|
||||
*/
|
||||
private function _constructPayload($group_key, $group_id, $operation, $value, $ignore_time = false) {
|
||||
$payload = array(
|
||||
'$token' => $this->_token,
|
||||
'$group_key' => $group_key,
|
||||
'$group_id' => $group_id,
|
||||
'$time' => microtime(true),
|
||||
$operation => $value
|
||||
);
|
||||
if ($ignore_time === true) $payload['$ignore_time'] = true;
|
||||
return $payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set properties on a group profile. If the group profile does not exist, it creates it with these properties.
|
||||
* If it does exist, it sets the properties to these values, overwriting existing values.
|
||||
* @param string|int $group_key the group_key used for groups in Project Settings
|
||||
* @param string|int $group_id the group id used for the group profile
|
||||
* @param array $props associative array of properties to set on the group profile
|
||||
* @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the group profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time
|
||||
*/
|
||||
public function set($group_key, $group_id, $props, $ignore_time = false) {
|
||||
$payload = $this->_constructPayload($group_key, $group_id, '$set', $props, $ignore_time);
|
||||
$this->enqueue($payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set properties on a group profile. If the Group profile does not exist, it creates it with these properties.
|
||||
* If it does exist, it sets the properties to these values but WILL NOT overwrite existing values.
|
||||
* @param string|int $group_key the group_key used for groups in Project Settings
|
||||
* @param string|int $group_id the group id used for the group profile
|
||||
* @param array $props associative array of properties to set on the group profile
|
||||
* @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the group profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time
|
||||
*/
|
||||
public function setOnce($group_key, $group_id, $props, $ignore_time = false) {
|
||||
$payload = $this->_constructPayload($group_key, $group_id, '$set_once', $props, $ignore_time);
|
||||
$this->enqueue($payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unset properties on a group profile. If the group does not exist, it creates it with no properties.
|
||||
* If it does exist, it unsets these properties. NOTE: In other libraries we use 'unset' which is
|
||||
* a reserved word in PHP.
|
||||
* @param string|int $group_key the group_key used for groups in Project Settings
|
||||
* @param string|int $group_id the group id used for the group profile
|
||||
* @param array $props associative array of properties to unset on the group profile
|
||||
* @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the group profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time
|
||||
*/
|
||||
public function remove($group_key, $group_id, $props, $ignore_time = false) {
|
||||
$payload = $this->_constructPayload($group_key, $group_id, '$remove', $props, $ignore_time);
|
||||
$this->enqueue($payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds $val to a list located at $prop. If the property does not exist, it will be created. If $val is a string
|
||||
* and the list is empty or does not exist, a new list with one value will be created.
|
||||
* @param string|int $group_key the group_key used for groups in Project Settings
|
||||
* @param string|int $group_id the group id used for the group profile
|
||||
* @param string $prop the property that holds the list
|
||||
* @param string|array $val items to add to the list
|
||||
* @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the group profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time
|
||||
*/
|
||||
public function union($group_key, $group_id, $prop, $val, $ignore_time = false) {
|
||||
$payload = $this->_constructPayload($group_key, $group_id, '$union', array("$prop" => $val), $ignore_time);
|
||||
$this->enqueue($payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete this group profile from Mixpanel
|
||||
* @param string|int $group_key the group_key used for groups in Project Settings
|
||||
* @param string|int $group_id the group id used for the group profile
|
||||
* @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time
|
||||
*/
|
||||
public function deleteGroup($group_key, $group_id, $ignore_time = false) {
|
||||
$payload = $this->_constructPayload($group_key, $group_id, '$delete', "", $ignore_time);
|
||||
$this->enqueue($payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the "groups" endpoint
|
||||
* @return string
|
||||
*/
|
||||
function _getEndpoint() {
|
||||
return $this->_options['groups_endpoint'];
|
||||
}
|
||||
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Provides an API to create/update profiles on Mixpanel
|
||||
*/
|
||||
class WPMedia_Producers_MixpanelPeople extends WPMedia_Producers_MixpanelBaseProducer {
|
||||
|
||||
/**
|
||||
* Internal method to prepare a message given the message data
|
||||
* @param $distinct_id
|
||||
* @param $operation
|
||||
* @param $value
|
||||
* @param null $ip
|
||||
* @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time
|
||||
* @param boolean $ignore_alias If the $ignore_alias property is true, an alias look up will not be performed after ingestion. Otherwise, a lookup for the distinct ID will be performed, and replaced if a match is found
|
||||
* @return array
|
||||
*/
|
||||
private function _constructPayload($distinct_id, $operation, $value, $ip = null, $ignore_time = false, $ignore_alias = false) {
|
||||
$payload = array(
|
||||
'$token' => $this->_token,
|
||||
'$distinct_id' => $distinct_id,
|
||||
'$time' => microtime(true),
|
||||
$operation => $value
|
||||
);
|
||||
if ($ip !== null) $payload['$ip'] = $ip;
|
||||
if ($ignore_time === true) $payload['$ignore_time'] = true;
|
||||
if ($ignore_alias === true) $payload['$ignore_alias'] = true;
|
||||
return $payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set properties on a user record. If the profile does not exist, it creates it with these properties.
|
||||
* If it does exist, it sets the properties to these values, overwriting existing values.
|
||||
* @param string|int $distinct_id the distinct_id or alias of a user
|
||||
* @param array $props associative array of properties to set on the profile
|
||||
* @param string|null $ip the ip address of the client (used for geo-location)
|
||||
* @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time
|
||||
* @param boolean $ignore_alias If the $ignore_alias property is true, an alias look up will not be performed after ingestion. Otherwise, a lookup for the distinct ID will be performed, and replaced if a match is found
|
||||
*/
|
||||
public function set($distinct_id, $props, $ip = null, $ignore_time = false, $ignore_alias = false) {
|
||||
$payload = $this->_constructPayload($distinct_id, '$set', $props, $ip, $ignore_time, $ignore_alias);
|
||||
$this->enqueue($payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set properties on a user record. If the profile does not exist, it creates it with these properties.
|
||||
* If it does exist, it sets the properties to these values but WILL NOT overwrite existing values.
|
||||
* @param string|int $distinct_id the distinct_id or alias of a user
|
||||
* @param array $props associative array of properties to set on the profile
|
||||
* @param string|null $ip the ip address of the client (used for geo-location)
|
||||
* @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time
|
||||
* @param boolean $ignore_alias If the $ignore_alias property is true, an alias look up will not be performed after ingestion. Otherwise, a lookup for the distinct ID will be performed, and replaced if a match is found
|
||||
*/
|
||||
public function setOnce($distinct_id, $props, $ip = null, $ignore_time = false, $ignore_alias = false) {
|
||||
$payload = $this->_constructPayload($distinct_id, '$set_once', $props, $ip, $ignore_time, $ignore_alias);
|
||||
$this->enqueue($payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unset properties on a user record. If the profile does not exist, it creates it with no properties.
|
||||
* If it does exist, it unsets these properties. NOTE: In other libraries we use 'unset' which is
|
||||
* a reserved word in PHP.
|
||||
* @param string|int $distinct_id the distinct_id or alias of a user
|
||||
* @param array $props associative array of properties to unset on the profile
|
||||
* @param string|null $ip the ip address of the client (used for geo-location)
|
||||
* @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time
|
||||
* @param boolean $ignore_alias If the $ignore_alias property is true, an alias look up will not be performed after ingestion. Otherwise, a lookup for the distinct ID will be performed, and replaced if a match is found
|
||||
*/
|
||||
public function remove($distinct_id, $props, $ip = null, $ignore_time = false, $ignore_alias = false) {
|
||||
$payload = $this->_constructPayload($distinct_id, '$unset', $props, $ip, $ignore_time, $ignore_alias);
|
||||
$this->enqueue($payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the value of a property on a user record. If the profile does not exist, it creates it and sets the
|
||||
* property to the increment value.
|
||||
* @param string|int $distinct_id the distinct_id or alias of a user
|
||||
* @param $prop string the property to increment
|
||||
* @param int $val the amount to increment the property by
|
||||
* @param string|null $ip the ip address of the client (used for geo-location)
|
||||
* @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time
|
||||
* @param boolean $ignore_alias If the $ignore_alias property is true, an alias look up will not be performed after ingestion. Otherwise, a lookup for the distinct ID will be performed, and replaced if a match is found
|
||||
*/
|
||||
public function increment($distinct_id, $prop, $val, $ip = null, $ignore_time = false, $ignore_alias = false) {
|
||||
$payload = $this->_constructPayload($distinct_id, '$add', array("$prop" => $val), $ip, $ignore_time, $ignore_alias);
|
||||
$this->enqueue($payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds $val to a list located at $prop. If the property does not exist, it will be created. If $val is a string
|
||||
* and the list is empty or does not exist, a new list with one value will be created.
|
||||
* @param string|int $distinct_id the distinct_id or alias of a user
|
||||
* @param string $prop the property that holds the list
|
||||
* @param string|array $val items to add to the list
|
||||
* @param string|null $ip the ip address of the client (used for geo-location)
|
||||
* @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time
|
||||
* @param boolean $ignore_alias If the $ignore_alias property is true, an alias look up will not be performed after ingestion. Otherwise, a lookup for the distinct ID will be performed, and replaced if a match is found
|
||||
*/
|
||||
public function append($distinct_id, $prop, $val, $ip = null, $ignore_time = false, $ignore_alias = false) {
|
||||
$operation = gettype($val) == "array" ? '$union' : '$append';
|
||||
$payload = $this->_constructPayload($distinct_id, $operation, array("$prop" => $val), $ip, $ignore_time, $ignore_alias);
|
||||
$this->enqueue($payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a transaction to the user's profile for revenue tracking
|
||||
* @param string|int $distinct_id the distinct_id or alias of a user
|
||||
* @param string $amount the transaction amount e.g. "20.50"
|
||||
* @param null $timestamp the timestamp of when the transaction occurred (default to current timestamp)
|
||||
* @param string|null $ip the ip address of the client (used for geo-location)
|
||||
* @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time
|
||||
* @param boolean $ignore_alias If the $ignore_alias property is true, an alias look up will not be performed after ingestion. Otherwise, a lookup for the distinct ID will be performed, and replaced if a match is found
|
||||
*/
|
||||
public function trackCharge($distinct_id, $amount, $timestamp = null, $ip = null, $ignore_time = false, $ignore_alias = false) {
|
||||
$timestamp = $timestamp == null ? time() : $timestamp;
|
||||
$date_iso = date("c", $timestamp);
|
||||
$transaction = array(
|
||||
'$time' => $date_iso,
|
||||
'$amount' => $amount
|
||||
);
|
||||
$val = array('$transactions' => $transaction);
|
||||
$payload = $this->_constructPayload($distinct_id, '$append', $val, $ip, $ignore_time, $ignore_alias);
|
||||
$this->enqueue($payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all transactions stored on a user's profile
|
||||
* @param string|int $distinct_id the distinct_id or alias of a user
|
||||
* @param string|null $ip the ip address of the client (used for geo-location)
|
||||
* @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time
|
||||
* @param boolean $ignore_alias If the $ignore_alias property is true, an alias look up will not be performed after ingestion. Otherwise, a lookup for the distinct ID will be performed, and replaced if a match is found
|
||||
*/
|
||||
public function clearCharges($distinct_id, $ip = null, $ignore_time = false, $ignore_alias = false) {
|
||||
$payload = $this->_constructPayload($distinct_id, '$set', array('$transactions' => array()), $ip, $ignore_time, $ignore_alias);
|
||||
$this->enqueue($payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete this profile from Mixpanel
|
||||
* @param string|int $distinct_id the distinct_id or alias of a user
|
||||
* @param string|null $ip the ip address of the client (used for geo-location)
|
||||
* @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time
|
||||
* @param boolean $ignore_alias If the $ignore_alias property is true, an alias look up will not be performed after ingestion. Otherwise, a lookup for the distinct ID will be performed, and replaced if a match is found
|
||||
*/
|
||||
public function deleteUser($distinct_id, $ip = null, $ignore_time = false, $ignore_alias = false) {
|
||||
$payload = $this->_constructPayload($distinct_id, '$delete', "", $ip, $ignore_time, $ignore_alias);
|
||||
$this->enqueue($payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the "engage" endpoint
|
||||
* @return string
|
||||
*/
|
||||
function _getEndpoint() {
|
||||
return $this->_options['people_endpoint'];
|
||||
}
|
||||
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\Mixpanel;
|
||||
|
||||
class Optin {
|
||||
/**
|
||||
* The plugin slug.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $plugin_slug;
|
||||
|
||||
/**
|
||||
* The capability required to enable/disable the opt-in.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $capability;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param string $plugin_slug The plugin slug.
|
||||
* @param string $capability The capability required to enable/disable the opt-in.
|
||||
*/
|
||||
public function __construct( string $plugin_slug, string $capability ) {
|
||||
$this->plugin_slug = $plugin_slug;
|
||||
$this->capability = $capability;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the opt-in is enabled.
|
||||
*
|
||||
* @return bool True if the opt-in is enabled, false otherwise.
|
||||
*/
|
||||
public function is_enabled(): bool {
|
||||
if ( ! current_user_can( $this->capability ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$optin = get_option( $this->plugin_slug . '_mixpanel_optin', false );
|
||||
|
||||
if ( ! $optin ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if tracking is allowed.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function can_track(): bool {
|
||||
return (bool) get_option( $this->plugin_slug . '_mixpanel_optin', false );
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable the opt-in.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function enable(): void {
|
||||
if ( $this->is_enabled() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
update_option( $this->plugin_slug . '_mixpanel_optin', true );
|
||||
|
||||
/**
|
||||
* Fires when the Mixpanel opt-in status changes to enabled.
|
||||
*
|
||||
* @param bool $status The opt-in status.
|
||||
*/
|
||||
do_action( $this->plugin_slug . '_mixpanel_optin_changed', true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable the opt-in.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function disable(): void {
|
||||
if ( ! $this->is_enabled() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
delete_option( $this->plugin_slug . '_mixpanel_optin' );
|
||||
|
||||
/**
|
||||
* Fires when the Mixpanel opt-in status changes to disabled.
|
||||
*
|
||||
* @param bool $status The opt-in status.
|
||||
*/
|
||||
do_action( $this->plugin_slug . '_mixpanel_optin_changed', false );
|
||||
}
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\Mixpanel;
|
||||
|
||||
use WPMedia_Mixpanel;
|
||||
|
||||
class Tracking {
|
||||
const HOST = 'api-eu.mixpanel.com';
|
||||
|
||||
const LIB_URL = 'https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js';
|
||||
|
||||
/**
|
||||
* Mixpanel instance
|
||||
*
|
||||
* @var WPMedia_Mixpanel
|
||||
*/
|
||||
private $mixpanel;
|
||||
|
||||
/**
|
||||
* Mixpanel token
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $token;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param string $mixpanel_token Mixpanel token.
|
||||
* @param mixed[] $options Options for Mixpanel instance.
|
||||
*/
|
||||
public function __construct( string $mixpanel_token, array $options = [] ) {
|
||||
$mixpanel_options = array_merge(
|
||||
[
|
||||
'host' => self::HOST,
|
||||
'events_endpoint' => '/track/?ip=0',
|
||||
],
|
||||
$options
|
||||
);
|
||||
|
||||
$this->token = $mixpanel_token;
|
||||
$this->mixpanel = WPMedia_Mixpanel::getInstance(
|
||||
$this->token,
|
||||
$mixpanel_options
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if debug mode is enabled
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function is_debug(): bool {
|
||||
$debug = ( defined( 'WP_DEBUG' ) ? constant( 'WP_DEBUG' ) : false )
|
||||
&& ( defined( 'WP_DEBUG_LOG' ) ? constant( 'WP_DEBUG_LOG' ) : false );
|
||||
|
||||
/**
|
||||
* Filters whether Mixpanel debug mode is enabled.
|
||||
*
|
||||
* @param bool $debug Debug mode value.
|
||||
*/
|
||||
return apply_filters( 'wp_media_mixpanel_debug', $debug );
|
||||
}
|
||||
|
||||
/**
|
||||
* Log event to error log if debug mode is enabled
|
||||
*
|
||||
* @param string $event Event name.
|
||||
* @param mixed[] $properties Event properties.
|
||||
*/
|
||||
private function log_event( string $event, array $properties ): void {
|
||||
if ( ! $this->is_debug() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
error_log( 'Mixpanel event: ' . $event . ' ' . var_export( $properties, true ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.PHP.DevelopmentFunctions.error_log_var_export
|
||||
}
|
||||
|
||||
/**
|
||||
* Track an event in Mixpanel
|
||||
*
|
||||
* @param string $event Event name.
|
||||
* @param mixed[] $properties Event properties.
|
||||
*/
|
||||
public function track( string $event, array $properties ): void {
|
||||
$this->log_event( $event, $properties );
|
||||
|
||||
$this->mixpanel->track( $event, $properties );
|
||||
}
|
||||
|
||||
/**
|
||||
* Identify a user in Mixpanel
|
||||
*
|
||||
* @param string $user_id User ID.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function identify( string $user_id ): void {
|
||||
$this->mixpanel->identify( $this->hash( $user_id ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a user property in Mixpanel
|
||||
*
|
||||
* @param string $user_id User ID.
|
||||
* @param string $property Property name.
|
||||
* @param mixed $value Property value.
|
||||
*/
|
||||
public function set_user_property( string $user_id, string $property, $value ): void {
|
||||
$this->mixpanel->people->set(
|
||||
$user_id,
|
||||
[
|
||||
$property => $value,
|
||||
],
|
||||
'0'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hash a value using sha224
|
||||
*
|
||||
* @param string $value Value to hash.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function hash( string $value ): string {
|
||||
return hash( 'sha224', $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the WordPress version
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_wp_version(): string {
|
||||
$version = preg_replace( '@^(\d\.\d+).*@', '\1', get_bloginfo( 'version' ) );
|
||||
|
||||
if ( null === $version ) {
|
||||
$version = '0.0';
|
||||
}
|
||||
|
||||
return $version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the PHP version
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_php_version(): string {
|
||||
$version = preg_replace( '@^(\d\.\d+).*@', '\1', phpversion() );
|
||||
|
||||
if ( null === $version ) {
|
||||
$version = '0.0';
|
||||
}
|
||||
|
||||
return $version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the active theme
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_current_theme(): string {
|
||||
$theme = wp_get_theme();
|
||||
|
||||
return $theme->get( 'Name' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of active plugins names
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function get_active_plugins(): array {
|
||||
$plugins = [];
|
||||
$active_plugins = (array) get_option( 'active_plugins', [] );
|
||||
$all_plugins = get_plugins();
|
||||
|
||||
foreach ( $active_plugins as $plugin_path ) {
|
||||
if ( ! is_string( $plugin_path ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( ! isset( $all_plugins[ $plugin_path ] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$plugins[] = $all_plugins[ $plugin_path ]['Name'];
|
||||
}
|
||||
|
||||
return $plugins;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Mixpanel token
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_token(): string {
|
||||
return $this->token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the Mixpanel script & initialize it
|
||||
*/
|
||||
public function add_script(): void {
|
||||
?>
|
||||
<!-- start Mixpanel --><script>
|
||||
const MIXPANEL_CUSTOM_LIB_URL = "<?php echo esc_js( self::LIB_URL ); ?>";
|
||||
(function (f, b) { if (!b.__SV) { var e, g, i, h; window.mixpanel = b; b._i = []; b.init = function (e, f, c) { function g(a, d) { var b = d.split("."); 2 == b.length && ((a = a[b[0]]), (d = b[1])); a[d] = function () { a.push([d].concat(Array.prototype.slice.call(arguments, 0))); }; } var a = b; "undefined" !== typeof c ? (a = b[c] = []) : (c = "mixpanel"); a.people = a.people || []; a.toString = function (a) { var d = "mixpanel"; "mixpanel" !== c && (d += "." + c); a || (d += " (stub)"); return d; }; a.people.toString = function () { return a.toString(1) + ".people (stub)"; }; i = "disable time_event track track_pageview track_links track_forms track_with_groups add_group set_group remove_group register register_once alias unregister identify name_tag set_config reset opt_in_tracking opt_out_tracking has_opted_in_tracking has_opted_out_tracking clear_opt_in_out_tracking start_batch_senders people.set people.set_once people.unset people.increment people.append people.union people.track_charge people.clear_charges people.delete_user people.remove".split( " "); for (h = 0; h < i.length; h++) g(a, i[h]); var j = "set set_once union unset remove delete".split(" "); a.get_group = function () { function b(c) { d[c] = function () { call2_args = arguments; call2 = [c].concat(Array.prototype.slice.call(call2_args, 0)); a.push([e, call2]); }; } for ( var d = {}, e = ["get_group"].concat( Array.prototype.slice.call(arguments, 0)), c = 0; c < j.length; c++) b(j[c]); return d; }; b._i.push([e, f, c]); }; b.__SV = 1.2; e = f.createElement("script"); e.type = "text/javascript"; e.async = !0; e.src = "undefined" !== typeof MIXPANEL_CUSTOM_LIB_URL ? MIXPANEL_CUSTOM_LIB_URL : "file:" === f.location.protocol && "//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js".match(/^\/\//) ? "https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js" : "//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js"; g = f.getElementsByTagName("script")[0]; g.parentNode.insertBefore(e, g); } })(document, window.mixpanel || []);
|
||||
mixpanel.init( '<?php echo esc_js( $this->token ); ?>', {
|
||||
api_host: "https://<?php echo esc_js( self::HOST ); ?>",
|
||||
id: false,
|
||||
property_blacklist: ['$initial_referrer', '$current_url', '$initial_referring_domain', '$referrer', '$referring_domain']
|
||||
} );
|
||||
</script><!-- end Mixpanel -->
|
||||
<?php
|
||||
}
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\Mixpanel;
|
||||
|
||||
class TrackingPlugin extends Tracking {
|
||||
/**
|
||||
* Plugin name & version
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $plugin;
|
||||
|
||||
/**
|
||||
* Brand name
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $brand;
|
||||
|
||||
/**
|
||||
* Application name
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $app;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param string $mixpanel_token Mixpanel token.
|
||||
* @param string $plugin Plugin name.
|
||||
* @param string $brand Brand name.
|
||||
* @param string $app Application name.
|
||||
*/
|
||||
public function __construct( string $mixpanel_token, string $plugin, string $brand = '', string $app = '' ) {
|
||||
$options = [
|
||||
'consumer' => 'wp',
|
||||
'consumers' => [
|
||||
'wp' => 'WPMedia\\Mixpanel\\WPConsumer',
|
||||
],
|
||||
];
|
||||
|
||||
parent::__construct( $mixpanel_token, $options );
|
||||
|
||||
$this->plugin = $plugin;
|
||||
$this->brand = $brand;
|
||||
$this->app = $app;
|
||||
}
|
||||
|
||||
/**
|
||||
* Track an event in Mixpanel with plugin context
|
||||
*
|
||||
* @param string $event Event name.
|
||||
* @param mixed[] $properties Event properties.
|
||||
* @param string $event_capability The capability required to track the event.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function track( string $event, array $properties, string $event_capability = '' ): void {
|
||||
/**
|
||||
* Filter the default capability required to track a specific event.
|
||||
*
|
||||
* @param string $capability The capability required to track the event.
|
||||
* @param string $event The event name.
|
||||
* @param string $app The application name.
|
||||
*/
|
||||
$default = apply_filters( 'wp_mixpanel_event_capability', 'manage_options', $event, $this->app );
|
||||
|
||||
if ( empty( $event_capability ) ) {
|
||||
$event_capability = $default;
|
||||
}
|
||||
|
||||
if ( ! current_user_can( $event_capability ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->track_direct( $event, $properties );
|
||||
}
|
||||
|
||||
/**
|
||||
* Track an event directly in Mixpanel, bypassing capability checks.
|
||||
*
|
||||
* @param string $event Event name.
|
||||
* @param mixed[] $properties Event properties.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function track_direct( string $event, array $properties ): void {
|
||||
$host = wp_parse_url( get_home_url(), PHP_URL_HOST );
|
||||
|
||||
if ( ! $host ) {
|
||||
$host = '';
|
||||
}
|
||||
|
||||
$defaults = [
|
||||
'domain' => $this->hash( $host ),
|
||||
'wp_version' => $this->get_wp_version(),
|
||||
'php_version' => $this->get_php_version(),
|
||||
'plugin' => strtolower( $this->plugin ),
|
||||
'brand' => strtolower( $this->brand ),
|
||||
'application' => strtolower( $this->app ),
|
||||
];
|
||||
|
||||
$properties = array_merge( $properties, $defaults );
|
||||
|
||||
parent::track( ucfirst( $event ), $properties );
|
||||
}
|
||||
|
||||
/**
|
||||
* Track opt-in status change in Mixpanel
|
||||
*
|
||||
* @param bool $status Opt-in status.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function track_optin( $status ): void {
|
||||
$this->track(
|
||||
'WordPress Plugin Data Consent Changed',
|
||||
[
|
||||
'opt_in_status' => $status,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the Mixpanel script & initialize it
|
||||
*/
|
||||
public function add_script(): void {
|
||||
/**
|
||||
* Filter the default capability required to track with JS.
|
||||
*
|
||||
* @param string $capability The capability required to track the event.
|
||||
* @param string $app The application name.
|
||||
*/
|
||||
$capability = apply_filters( 'wp_mixpanel_js_track_capability', 'manage_options', $this->app );
|
||||
|
||||
if ( ! current_user_can( $capability ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
parent::add_script();
|
||||
}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\Mixpanel;
|
||||
|
||||
use WPMedia_ConsumerStrategies_AbstractConsumer;
|
||||
|
||||
/**
|
||||
* Consumes messages and sends them to a host/endpoint using WordPress's HTTP API
|
||||
*/
|
||||
class WPConsumer extends WPMedia_ConsumerStrategies_AbstractConsumer {
|
||||
|
||||
/**
|
||||
* Number of seconds to allow the request to execute.
|
||||
*
|
||||
* Not configurable: analytics must never delay a response. Also the lowest value
|
||||
* WordPress honours, as it clamps the cURL timeout to a minimum of 1 second.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
const REQUEST_TIMEOUT = 1;
|
||||
|
||||
/**
|
||||
* The host to connect to (e.g. api.mixpanel.com)
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $host;
|
||||
|
||||
/**
|
||||
* The host-relative endpoint to write to (e.g. /engage)
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $endpoint;
|
||||
|
||||
/**
|
||||
* The protocol to use for the cURL connection
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $protocol;
|
||||
|
||||
/**
|
||||
* Creates a new WPConsumer and assigns properties from the $options array
|
||||
*
|
||||
* The request timeout and blocking behaviour are fixed, and cannot be set here.
|
||||
*
|
||||
* @param array{host: string, endpoint: string, use_ssl?: bool} $options Options for the consumer.
|
||||
*/
|
||||
public function __construct( $options ) {
|
||||
parent::__construct( $options );
|
||||
|
||||
$this->host = $options['host'];
|
||||
$this->endpoint = $options['endpoint'];
|
||||
$this->protocol = isset( $options['use_ssl'] ) && ( true === $options['use_ssl'] ) ? 'https' : 'http';
|
||||
}
|
||||
|
||||
/**
|
||||
* Send post request to the given host/endpoint using WordPress's HTTP API
|
||||
*
|
||||
* @param mixed[] $batch Batch of data to send to mixpanel.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function persist( $batch ) {
|
||||
if ( count( $batch ) <= 0 ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$url = $this->protocol . '://' . $this->host . $this->endpoint;
|
||||
$data = 'data=' . $this->_encode( $batch );
|
||||
|
||||
// Non-blocking still waits up to the timeout, it only discards the response:
|
||||
// the timeout is what bounds the cost of a degraded endpoint.
|
||||
$response = wp_remote_post(
|
||||
$url,
|
||||
[
|
||||
'timeout' => self::REQUEST_TIMEOUT,
|
||||
'blocking' => false,
|
||||
'body' => $data,
|
||||
]
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
$this->_handleError( $response->get_error_code(), $response->get_error_message() );
|
||||
}
|
||||
|
||||
/*
|
||||
* Report the batch as consumed even on failure. Returning false would make the
|
||||
* producer re-queue it and retry the flush up to 10 times at shutdown, once per
|
||||
* producer, multiplying the cost of an unreachable endpoint.
|
||||
*
|
||||
* @see \WPMedia_Producers_MixpanelBaseProducer::__destruct()
|
||||
*/
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user