Add docs
This commit is contained in:
@@ -0,0 +1,688 @@
|
||||
MageSail
|
||||
|
||||
Copyright (C) MageSail contributors.
|
||||
|
||||
|
||||
|
||||
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.
|
||||
|
||||
|
||||
|
||||
The full license text follows.
|
||||
|
||||
|
||||
|
||||
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>.
|
||||
+7
-395
@@ -1,399 +1,11 @@
|
||||
# Deep Dive into MageSail: File & Folder Structure, Code Flow, and Inner Workings
|
||||
# MageSail module breakdown (deprecated)
|
||||
|
||||
Welcome to a comprehensive breakdown of the **MageSail** Magento 2 extension (module name: `MageSail_Magesail`). This module integrates **Holesail**—a peer-to-peer tunneling library—for exposing local Magento dev environments securely via crypto keys (Private or Public modes). I'll dissect the structure, explain how components interact, trace the code flow (especially tunnel start/stop), highlight key mechanisms, and touch on extensibility.
|
||||
This file used to hold a long narrative breakdown of the module. It went out of date as NGINX map tooling, tunnel store provisioning, and request plugins were added.
|
||||
|
||||
MageSail follows Magento 2's standard module conventions: it's a self-contained directory under `app/code/MageSail/Magesail/` (or `vendor/magesail/magesail/` post-Composer install). The module is lightweight (~50 files total, mostly config/XML), with a hybrid PHP/Node.js backend. PHP handles Magento integration (admin UI, config, cron), while Node.js powers the tunnel via Holesail.
|
||||
**Use the maintained documentation instead:**
|
||||
|
||||
**Module Version**: 1.0.1 (as per `etc/module.xml` and `composer.json`).
|
||||
**Core Tech Stack**:
|
||||
- **PHP**: Magento 2 framework (controllers, blocks, cron, setup).
|
||||
- **Node.js**: Holesail (^2.3.2) for P2P tunneling (DHT discovery, Noise crypto).
|
||||
- **Dependencies**: Auto-installed via npm in `scripts/`; no external services.
|
||||
- **[Documentation index](../docs/README.md)** — subject-based guides (installation, configuration, routing, NGINX, cron, PHP reference, troubleshooting).
|
||||
- **[Tunnel + base URL + NGINX deep dive](doc/TUNNEL_BASE_URL_REDIRECT.md)** — detailed redirect and map behavior.
|
||||
- **[Root README](../README.md)** — quick start and feature summary.
|
||||
|
||||
---
|
||||
|
||||
## 1. Overall Folder Structure
|
||||
|
||||
MageSail adheres to Magento 2's modular layout. Here's a tree view (non-exhaustive; excludes auto-generated files like `generated/`):
|
||||
|
||||
```
|
||||
app/code/MageSail/Magesail/ # Root module dir
|
||||
├── Block/ # View blocks (PHP classes for template data)
|
||||
│ └── Adminhtml/
|
||||
│ └── Tunnel.php # Status block for admin UI
|
||||
├── Composer/ # (Empty; no custom autoloader)
|
||||
├── Controller/ # Admin controllers (handle HTTP requests)
|
||||
│ └── Adminhtml/
|
||||
│ └── Tunnel/
|
||||
│ ├── Index.php # Main: start/stop tunnel
|
||||
│ └── Status.php # AJAX: poll tunnel status/key
|
||||
├── Cron/ # Cron jobs
|
||||
│ └── DailyMonitor.php # Monitors/cleans crashed tunnels
|
||||
├── etc/ # Module config (XML declarations)
|
||||
│ ├── acl.xml # ACL permissions
|
||||
│ ├── crontab.xml # Cron schedule
|
||||
│ ├── module.xml # Module metadata/sequence
|
||||
│ └── adminhtml/ # Admin-specific config
|
||||
│ ├── menu.xml # Admin menu entries
|
||||
│ ├── routes.xml # Admin routes (URL mapping)
|
||||
│ └── system.xml # Config fields (Stores > Config)
|
||||
├── registration.php # Module registrar (autoloads)
|
||||
├── Setup/ # DB schema/install scripts
|
||||
│ └── InstallSchema.php # Creates logs table
|
||||
├── scripts/ # Node.js runtime (Holesail server)
|
||||
│ ├── package.json # npm deps (Holesail + transitives)
|
||||
│ ├── package-lock.json # Locked deps (huge; ~200 entries)
|
||||
│ └── start-server.js # Entry: Spawns Holesail server
|
||||
└── view/ # Frontend assets (admin templates/layouts)
|
||||
└── adminhtml/
|
||||
├── layout/
|
||||
│ └── magesail_tunnel_index.xml # Page layout
|
||||
└── templates/
|
||||
└── tunnel/
|
||||
└── index.phtml # Admin UI template
|
||||
```
|
||||
|
||||
- **Total Size**: ~5MB (mostly `package-lock.json` bloat from Holesail's deps like Sodium crypto, HyperDHT).
|
||||
- **Autoloading**: Via `composer.json` (PSR-4: `MageSail\\Magesail\\` → root) + `registration.php`.
|
||||
- **Vendor Dir**: Post-install, Holesail's `node_modules/` (~200 pkgs) lives in `scripts/` (ignored in Git).
|
||||
|
||||
**Key Patterns**:
|
||||
- **Admin-Focused**: All UI/logic in `adminhtml/` (no frontend).
|
||||
- **Hybrid Runtime**: PHP orchestrates Node via shell exec (`nohup node ...`).
|
||||
- **State Management**: Files in `var/` (PID, key, logs) + DB table for persistence.
|
||||
- **No Assets**: No JS/CSS bundles; uses Magento's jQuery for polling.
|
||||
|
||||
---
|
||||
|
||||
## 2. Detailed File Breakdown by Category
|
||||
|
||||
### 2.1 Core Module Files (`registration.php`, `etc/module.xml`, `composer.json`)
|
||||
- **`registration.php`**: Registers the module with Magento's component system.
|
||||
```php
|
||||
<?php
|
||||
\Magento\Framework\Component\ComponentRegistrar::register(
|
||||
\Magento\Framework\Component\ComponentRegistrar::MODULE,
|
||||
'MageSail_Magesail',
|
||||
__DIR__
|
||||
);
|
||||
```
|
||||
- **Role**: Tells Magento: "This dir is a module named `MageSail_Magesail`."
|
||||
- **Flow**: Loaded early in bootstrap; enables autoloading.
|
||||
|
||||
- **`etc/module.xml`**: Declares module identity and dependencies.
|
||||
```xml
|
||||
<module name="MageSail_Magesail" setup_version="1.0.1">
|
||||
<sequence>
|
||||
<module name="Magento_Backend"/> <!-- Admin UI dep -->
|
||||
<module name="Magento_Config"/> <!-- Config dep -->
|
||||
</sequence>
|
||||
</module>
|
||||
```
|
||||
- **Role**: Sets version (for upgrades); sequences after core modules.
|
||||
- **Flow**: During `setup:upgrade`, checks version; runs setup scripts if bumped.
|
||||
|
||||
- **`composer.json`**: Module packaging.
|
||||
```json
|
||||
{
|
||||
"name": "magesail/magesail",
|
||||
"type": "magento2-module",
|
||||
"version": "1.0.1",
|
||||
"require": { "php": "~8.1" },
|
||||
"autoload": {
|
||||
"files": ["registration.php"],
|
||||
"psr-4": { "MageSail\\Magesail\\": "" }
|
||||
}
|
||||
}
|
||||
```
|
||||
- **Role**: Enables Composer install (`composer require magesail/magesail`); autoloads classes.
|
||||
- **Flow**: Vendor dir population; no extra deps (Holesail is npm-side).
|
||||
|
||||
### 2.2 Admin UI & Routing (`etc/adminhtml/`, `view/adminhtml/`, `Controller/`, `Block/`)
|
||||
These form the admin dashboard at `/admin/magesail/tunnel/index`.
|
||||
|
||||
- **`etc/adminhtml/routes.xml`**: Maps URLs to controllers.
|
||||
```xml
|
||||
<router id="admin">
|
||||
<route id="magesail" frontName="magesail">
|
||||
<module name="MageSail_Magesail" />
|
||||
</route>
|
||||
</router>
|
||||
```
|
||||
- **Role**: `/admin/magesail/*` → `Controller\Adminhtml\Tunnel\*`.
|
||||
- **Flow**: Request to `/magesail/tunnel/index` loads `Index.php`.
|
||||
|
||||
- **`etc/adminhtml/menu.xml`**: Adds menu item.
|
||||
```xml
|
||||
<menu>
|
||||
<add id="MageSail_Magesail::tunnel" title="Holesail Tunnel" ... parent="Magento_Backend::system" />
|
||||
<add id="MageSail_Magesail::tunnel_index" title="Manage Tunnel" action="magesail/tunnel/index" ... />
|
||||
</menu>
|
||||
```
|
||||
- **Role**: "System > Holesail Tunnel" in sidebar.
|
||||
- **Flow**: ACL-checked; renders via layout.
|
||||
|
||||
- **`etc/adminhtml/system.xml`**: Config form fields.
|
||||
```xml
|
||||
<section id="magesail" ...>
|
||||
<group id="settings">
|
||||
<field id="mode" type="select" ...> <!-- Yes/No for Private/Public -->
|
||||
<field id="port" type="text" default="80" ...>
|
||||
</group>
|
||||
</section>
|
||||
```
|
||||
- **Role**: UI in "Stores > Config > General > Holesail Tunnel".
|
||||
- **Flow**: Saves to `core_config_data` (scopes: default/website/store); read via `ScopeConfigInterface`.
|
||||
|
||||
- **`view/adminhtml/layout/magesail_tunnel_index.xml`**: Page skeleton.
|
||||
```xml
|
||||
<page ...>
|
||||
<body>
|
||||
<referenceContainer name="content">
|
||||
<block class="MageSail\Magesail\Block\Adminhtml\Tunnel" name="magesail.tunnel" template="MageSail_Magesail::tunnel/index.phtml" />
|
||||
</referenceContainer>
|
||||
</body>
|
||||
</page>
|
||||
```
|
||||
- **Role**: Injects block into content area.
|
||||
- **Flow**: Renders `index.phtml` with block data.
|
||||
|
||||
- **`view/adminhtml/templates/tunnel/index.phtml`**: UI template.
|
||||
- **Logic**: Checks `$block->getTunnelStatus()`; shows start/stop buttons, key display, jQuery poll (every 3s to `/magesail/tunnel/status`).
|
||||
- **Flow**: POST to `Index.php` for actions; AJAX to `Status.php` for updates. Escapes output for security.
|
||||
|
||||
- **`Block/Adminhtml/Tunnel.php`**: Data provider for template.
|
||||
```php
|
||||
class Tunnel extends Template {
|
||||
public function getTunnelStatus() {
|
||||
$pidFile = $this->getPidFile(); // var/magesail.pid
|
||||
// Check file, PID validity via shell 'ps -p $pid'
|
||||
// Return ['running' => bool, 'pid' => int, 'key' => string|null]
|
||||
}
|
||||
}
|
||||
```
|
||||
- **Role**: Reads `var/magesail.{pid,key}`; uses `Shell` for process check.
|
||||
- **Flow**: Called in template; caches nothing (stateless).
|
||||
|
||||
- **`Controller/Adminhtml/Tunnel/Index.php`**: Handles start/stop.
|
||||
```php
|
||||
class Index extends \Magento\Backend\App\Action {
|
||||
public function execute() {
|
||||
$action = $this->getRequest()->getParam('action'); // 'start' or 'stop'
|
||||
if ($action === 'start') {
|
||||
// Validate config, spawn 'nohup node scripts/start-server.js ... & echo $!'
|
||||
// Capture PID, write to var/magesail.pid
|
||||
} elseif ($action === 'stop') {
|
||||
// 'kill $pid'; unlink files
|
||||
}
|
||||
// Redirect or render page
|
||||
}
|
||||
}
|
||||
```
|
||||
- **Role**: Orchestrates shell exec; messages via `MessageManager`.
|
||||
- **Flow**: See Section 3.
|
||||
|
||||
- **`Controller/Adminhtml/Tunnel/Status.php`**: AJAX endpoint.
|
||||
- **Logic**: Mirrors `Tunnel.php::getTunnelStatus()`; JSON response.
|
||||
- **Flow**: Polled by template JS; updates key in real-time.
|
||||
|
||||
### 2.3 Config & Permissions (`etc/acl.xml`)
|
||||
- **`etc/acl.xml`**: Defines resources.
|
||||
```xml
|
||||
<resource id="MageSail_Magesail::tunnel" title="Holesail Tunnel">
|
||||
<resource id="MageSail_Magesail::config" title="Configuration" />
|
||||
</resource>
|
||||
```
|
||||
- **Role**: `_isAllowed()` checks in controllers (e.g., `return $this->_authorization->isAllowed('MageSail_Magesail::tunnel');`).
|
||||
- **Flow**: Admin user ACL; denies unauthorized access.
|
||||
|
||||
### 2.4 Database & Setup (`Setup/InstallSchema.php`)
|
||||
- **Logic**: Creates `magesail_logs` table (ID, message, created_at).
|
||||
```php
|
||||
$table = $setup->getConnection()->newTable($setup->getTable('magesail_logs'))
|
||||
->addColumn('id', Table::TYPE_INTEGER, null, ['identity' => true, ...])
|
||||
// ... message (TEXT 255), timestamp
|
||||
->setComment('Magesail Tunnel Logs');
|
||||
$setup->getConnection()->createTable($table);
|
||||
```
|
||||
- **Role**: Basic logging (unused in core code; extensible).
|
||||
- **Flow**: Runs on `setup:upgrade` if version changes.
|
||||
|
||||
### 2.5 Cron (`etc/crontab.xml`, `Cron/DailyMonitor.php`)
|
||||
- **`etc/crontab.xml`**: Schedules job.
|
||||
```xml
|
||||
<job name="magesail_monitor" instance="MageSail\Magesail\Cron\DailyMonitor" method="execute">
|
||||
<schedule>0 0 * * *</schedule> <!-- Midnight daily -->
|
||||
</job>
|
||||
```
|
||||
- **Role**: Queues in `cron_schedule` table.
|
||||
|
||||
- **`Cron/DailyMonitor.php`**: Executor.
|
||||
```php
|
||||
class DailyMonitor {
|
||||
public function execute() {
|
||||
$pidFile = ...; // Check PID via shell 'ps'
|
||||
if (stale) { unlink PID/key; $this->logger->warning('Crashed; cleaned.'); }
|
||||
$this->logger->info('Monitor executed.');
|
||||
}
|
||||
}
|
||||
```
|
||||
- **Role**: Housekeeping; logs to `system.log`.
|
||||
- **Flow**: Magento cron runner invokes; injectable `LoggerInterface`, `Shell`.
|
||||
|
||||
### 2.6 Node.js Layer (`scripts/`)
|
||||
- **`package.json`**: Declares Holesail dep.
|
||||
```json
|
||||
{
|
||||
"dependencies": { "holesail": "^2.3.2" }
|
||||
}
|
||||
```
|
||||
- **Role**: `npm install` pulls ~200 pkgs (e.g., `hyperdht`, `sodium-universal` for crypto/DHT).
|
||||
|
||||
- **`package-lock.json`**: Locked versions (huge; includes integrity hashes for security).
|
||||
|
||||
- **`start-server.js`**: Tunnel launcher.
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const Holesail = require('holesail');
|
||||
const args = JSON.parse(process.argv[2] || '{}'); // e.g., {port:80, secure:true, keyfile:'../var/magesail.key'}
|
||||
const hs = new Holesail({
|
||||
server: true,
|
||||
secure: args.secure, // Private (true) vs Public (false)
|
||||
port: args.port,
|
||||
host: '127.0.0.1'
|
||||
});
|
||||
hs.ready().then(() => {
|
||||
const url = hs.info.url; // e.g., 'hs1abc...def' (key only, no full URL)
|
||||
fs.writeFileSync(args.keyfile, url);
|
||||
console.log(`Server ready: ${url} (PID: ${process.pid})`);
|
||||
});
|
||||
// SIGINT/SIGTERM: hs.close(); unlink keyfile
|
||||
```
|
||||
- **Role**: Instantiates Holesail server; derives keypair from seed (Private mode uses shared seed for auth; Public discards private key).
|
||||
- **Flow**: PHP spawns via `shell->execute("cd scripts && nohup node start-server.js '$jsonArgs' > log & echo $!")`; captures PID.
|
||||
|
||||
---
|
||||
|
||||
## 3. How It Works: End-to-End Code Flow
|
||||
|
||||
### 3.1 Initialization (Install/Enable)
|
||||
1. Composer install → Copies to `vendor/`; runs `registration.php`.
|
||||
2. `bin/magento module:enable` + `setup:upgrade`:
|
||||
- Loads `module.xml` → Runs `InstallSchema.php` (DB table).
|
||||
- Registers routes/menu/ACL/system.xml.
|
||||
3. Config save → Writes to `core_config_data` (e.g., `magesail/settings/mode=1`).
|
||||
|
||||
### 3.2 Admin UI Flow (Start/Stop Tunnel)
|
||||
1. User visits `/admin/magesail/tunnel/index`:
|
||||
- Router (`routes.xml`) → `Index.php::execute()` (GET: renders page).
|
||||
- Layout (`magesail_tunnel_index.xml`) → `Tunnel.php` block → `index.phtml` template.
|
||||
- Template calls `$block->getTunnelStatus()` → Checks `var/magesail.pid` + shell `ps`.
|
||||
|
||||
2. **Start Action** (POST `action=start`):
|
||||
- `Index.php`: Validates port/secure from config (`ScopeConfigInterface`).
|
||||
- Shell exec: `cd scripts && nohup node start-server.js '{"port":80,"secure":true,...}' > var/log/magesail_tunnel.log 2>&1 & echo $!`
|
||||
- Captures PID → Writes to `var/magesail.pid`.
|
||||
- `start-server.js`: Parses args → `new Holesail({server:true, secure:..., port:...})`.
|
||||
- `hs.ready()`: DHT bootstrap, key gen (Private: seed→keypair, announce public; Public: random public only).
|
||||
- Writes key to `var/magesail.key` → Logs "Server ready: hs1abc...".
|
||||
- Redirect + success message; template polls `/status` (AJAX via jQuery).
|
||||
|
||||
3. **Status Poll** (`/magesail/tunnel/status`):
|
||||
- `Status.php::execute()` → Mirrors `getTunnelStatus()` → JSON `['running'=>true, 'key'=>'hs1abc...']`.
|
||||
- Template JS: Updates UI every 3s until key appears.
|
||||
|
||||
4. **Stop Action** (POST `action=stop`):
|
||||
- `Index.php`: Reads PID → Shell `kill $pid`.
|
||||
- Unlinks `var/magesail.{pid,key}`.
|
||||
- `start-server.js` (on SIGTERM): `hs.close()` → Unlinks key (optional).
|
||||
|
||||
5. **Tunnel Runtime**:
|
||||
- Node process: Listens on `127.0.0.1:80`, proxies via P2P (Holesail handles DHT/Noise).
|
||||
- Client: `holesail client --key hs1abc...` → Discovers server, verifies (Private mode), tunnels traffic.
|
||||
|
||||
### 3.3 Cron Flow
|
||||
- Magento cron: Invokes `DailyMonitor::execute()` at midnight.
|
||||
- Checks PID via shell; cleans if dead → Logs warning.
|
||||
- Extensible: Inject config for auto-restart.
|
||||
|
||||
### 3.4 Error Handling & Security
|
||||
- **Shell Escapes**: Uses `Shell` class (Magento's safe exec); args JSON-encoded.
|
||||
- **ACL**: Controllers check `::tunnel` resource.
|
||||
- **File Perms**: `var/` must be writable (775); no sudo.
|
||||
- **Crypto**: Holesail's Sodium/Noise (Ed25519 keys); Private mode enforces auth.
|
||||
- **Logs**: Node stdout to `magesail_tunnel.log`; PHP to `system.log`/`exception.log`.
|
||||
|
||||
---
|
||||
|
||||
## 4. Key Mechanisms & Code Snippets
|
||||
|
||||
### 4.1 State Files in `var/`
|
||||
- `magesail.pid`: Raw PID (e.g., "12345").
|
||||
- `magesail.key`: Crypto key (e.g., "hs1abc123def456").
|
||||
- `log/magesail_tunnel.log`: Node output (e.g., DHT bootstrap, connections).
|
||||
|
||||
**Snippet (Status Check)**:
|
||||
```php
|
||||
// In Tunnel.php/Status.php
|
||||
$pid = (int) trim(file_get_contents($pidFile));
|
||||
if ($pid <= 0 || !$this->shell->execute("ps -p $pid > /dev/null 2>&1")) {
|
||||
unlink($pidFile); // Cleanup
|
||||
return ['running' => false];
|
||||
}
|
||||
$key = file_exists($keyFile) ? trim(file_get_contents($keyFile)) : null;
|
||||
```
|
||||
|
||||
### 4.2 Node Spawn (Hybrid Bridge)
|
||||
**PHP Side**:
|
||||
```php
|
||||
$jsArgs = json_encode(['port' => $port, 'secure' => $secure, 'keyfile' => $keyFile, 'logfile' => $logFile]);
|
||||
$cmd = "cd $scriptDir && nohup node start-server.js '$jsArgs' > $logFile 2>&1 & echo \$!";
|
||||
$output = $this->shell->execute($cmd); // Returns PID
|
||||
```
|
||||
|
||||
**JS Side** (Key Gen):
|
||||
```js
|
||||
// In start-server.js; Holesail abstracts: secure=true → seed-derived keypair
|
||||
hs.ready().then(() => {
|
||||
const key = hs.info.url; // e.g., z32-encoded public key (Private) or public-only
|
||||
fs.writeFileSync(keyFile, key);
|
||||
});
|
||||
```
|
||||
|
||||
### 4.3 Private vs Public Mode
|
||||
- **Config Read**: `$this->scopeConfig->getValue('magesail/settings/mode')` (1=Private).
|
||||
- **Holesail Mapping**: `secure: args.secure` → Private: Uses seed for shared secret; Public: No auth, discards private key.
|
||||
- **Key Sharing**: Always the key string; client must match mode.
|
||||
|
||||
---
|
||||
|
||||
## 5. Integration Points & Extensibility
|
||||
|
||||
- **Magento Hooks**:
|
||||
- **Config**: Scoped reads (website/store); extend `system.xml` for more fields (e.g., custom seed).
|
||||
- **Events**: None dispatched; add in `Index.php` (e.g., `$this->eventManager->dispatch('magesail_tunnel_start', ['pid' => $pid]);`).
|
||||
- **Observers**: Hook `adminhtml_controller_action_predispatch_start` for pre-actions.
|
||||
- **DI**: All classes injectable (e.g., override `Shell` for custom exec).
|
||||
|
||||
- **Holesail Customization**:
|
||||
- Edit `start-server.js`: Add middleware (e.g., rate limiting), custom DHT bootstraps.
|
||||
- Seed Override: Pass `seed: 'custom-string'` in Holesail ctor for persistent Private keys.
|
||||
|
||||
- **Extensions Ideas**:
|
||||
- **Frontend UI**: Add `frontend/` routes for non-admin access.
|
||||
- **Auto-Restart**: Config flag + shell respawn in cron.
|
||||
- **Multi-Port**: Array field; spawn multiple Nodes.
|
||||
- **DB Logging**: Insert to `magesail_logs` on start/stop.
|
||||
- **Tests**: Add `Test/` (PHPUnit for PHP; Mocha for JS).
|
||||
|
||||
- **Performance**: Low overhead (Node ~50MB RAM; polls lightweight). Scales to 1 tunnel/module.
|
||||
|
||||
---
|
||||
|
||||
## 6. Potential Gotchas & Best Practices
|
||||
- **Shell Deps**: Assumes `ps`, `kill`, `nohup` available (Linux/macOS).
|
||||
- **Key Expiry**: Holesail keys ~24h idle; cron can restart.
|
||||
- **Debug**: Set `MAGE_MODE=developer`; tail logs; manual Node run.
|
||||
- **Upgrades**: Bump `setup_version` in `module.xml` → Re-run schema.
|
||||
- **Security**: Private keys = secrets; store in `var/` (gitignore'd); rotate often.
|
||||
Module code lives under this directory (`MageSail\Magesail` PSR-4 root).
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace MageSail\Magesail\Model;
|
||||
|
||||
use Magento\Framework\App\Request\Http;
|
||||
|
||||
/**
|
||||
* Hostname-only tunnel detection against persisted tunnel base URLs (nginx global map without MageSail headers).
|
||||
*/
|
||||
class TunnelHostnameMatcher
|
||||
{
|
||||
public function __construct(
|
||||
private readonly TunnelStoreState $tunnelStoreState
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* When HTTP_HOST matches unsecure or secure tunnel base URL host, return the persisted store code.
|
||||
*/
|
||||
public function getStoreCodeIfRequestHostMatchesState(Http $request): ?string
|
||||
{
|
||||
$state = $this->tunnelStoreState->read();
|
||||
if ($state === null) {
|
||||
return null;
|
||||
}
|
||||
$requestHost = self::hostFromHttpHost($request->getServer('HTTP_HOST'));
|
||||
if ($requestHost === null) {
|
||||
return null;
|
||||
}
|
||||
foreach ([$state['unsecure_base_url'], $state['secure_base_url']] as $baseUrl) {
|
||||
if ($baseUrl === '') {
|
||||
continue;
|
||||
}
|
||||
$configuredHost = self::hostFromBaseUrl($baseUrl);
|
||||
if ($configuredHost !== null && strcasecmp($requestHost, $configuredHost) === 0) {
|
||||
return $state['store_code'];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static function hostFromHttpHost(?string $httpHost): ?string
|
||||
{
|
||||
if ($httpHost === null || $httpHost === '') {
|
||||
return null;
|
||||
}
|
||||
$parsed = parse_url('http://' . $httpHost);
|
||||
if ($parsed === false || !isset($parsed['host'])) {
|
||||
return null;
|
||||
}
|
||||
return $parsed['host'];
|
||||
}
|
||||
|
||||
public static function hostFromBaseUrl(string $baseUrl): ?string
|
||||
{
|
||||
$parsed = parse_url($baseUrl);
|
||||
if ($parsed === false || !isset($parsed['host'])) {
|
||||
return null;
|
||||
}
|
||||
return $parsed['host'];
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ namespace MageSail\Magesail\Model;
|
||||
use Magento\Framework\App\Request\Http;
|
||||
|
||||
/**
|
||||
* Detects MageSail tunnel proxy (header / query / server) on the current request.
|
||||
* Detects MageSail tunnel proxy (header / query / server / hostname vs persisted tunnel URLs) on the request.
|
||||
*/
|
||||
class TunnelRequestDetector
|
||||
{
|
||||
@@ -14,6 +14,11 @@ class TunnelRequestDetector
|
||||
private const QUERY_PARAM_STORE = 'magesail_store';
|
||||
private const SERVER_HEADER = 'HTTP_X_MAGESAIL_STORE_CODE';
|
||||
|
||||
public function __construct(
|
||||
private readonly TunnelHostnameMatcher $tunnelHostnameMatcher
|
||||
) {
|
||||
}
|
||||
|
||||
public function getTunnelStoreCode(Http $request): ?string
|
||||
{
|
||||
$value = $request->getParam(self::QUERY_PARAM_STORE);
|
||||
@@ -37,6 +42,6 @@ class TunnelRequestDetector
|
||||
return trim((string) $v);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
return $this->tunnelHostnameMatcher->getStoreCodeIfRequestHostMatchesState($request);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ use Magento\Backend\App\Area\FrontNameResolver;
|
||||
use Magento\Framework\App\Request\Http;
|
||||
use Magento\Framework\App\RequestInterface;
|
||||
use MageSail\Magesail\Model\TunnelRequestDetector;
|
||||
use MageSail\Magesail\Model\TunnelStoreState;
|
||||
|
||||
/**
|
||||
* When the tunnel is used, HTTP_HOST is often dev.myshop.local while default backend base URLs point at production.
|
||||
@@ -16,13 +15,14 @@ use MageSail\Magesail\Model\TunnelStoreState;
|
||||
*
|
||||
* Bypass host validation when: (1) tunnel proxy headers/query are present, or (2) the request host matches the
|
||||
* tunnel store base URLs from provisioned state (browser opened admin URL directly without X-MageSail-Store-Code).
|
||||
*
|
||||
* @see TunnelRequestDetector::getTunnelStoreCode() for detection (includes hostname match via persisted state).
|
||||
*/
|
||||
class TunnelBackendFrontNameResolverPlugin
|
||||
{
|
||||
public function __construct(
|
||||
private readonly RequestInterface $request,
|
||||
private readonly TunnelRequestDetector $tunnelRequestDetector,
|
||||
private readonly TunnelStoreState $tunnelStoreState
|
||||
private readonly TunnelRequestDetector $tunnelRequestDetector
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ class TunnelBackendFrontNameResolverPlugin
|
||||
if (!$checkHost || !$this->request instanceof Http) {
|
||||
return $result;
|
||||
}
|
||||
if (!$this->shouldBypassBackendHostCheck($this->request)) {
|
||||
if ($this->tunnelRequestDetector->getTunnelStoreCode($this->request) === null) {
|
||||
return $result;
|
||||
}
|
||||
if ($subject->isHostBackend()) {
|
||||
@@ -48,58 +48,4 @@ class TunnelBackendFrontNameResolverPlugin
|
||||
}
|
||||
return $proceed(false);
|
||||
}
|
||||
|
||||
private function shouldBypassBackendHostCheck(Http $request): bool
|
||||
{
|
||||
if ($this->tunnelRequestDetector->getTunnelStoreCode($request) !== null) {
|
||||
return true;
|
||||
}
|
||||
return $this->requestHostMatchesTunnelStoreUrls($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hostname-only match (tunnel unsecure/secure may differ in scheme/port from the current request).
|
||||
*/
|
||||
private function requestHostMatchesTunnelStoreUrls(Http $request): bool
|
||||
{
|
||||
$state = $this->tunnelStoreState->read();
|
||||
if ($state === null) {
|
||||
return false;
|
||||
}
|
||||
$requestHost = $this->hostFromHttpHost($request->getServer('HTTP_HOST'));
|
||||
if ($requestHost === null) {
|
||||
return false;
|
||||
}
|
||||
foreach ([$state['unsecure_base_url'], $state['secure_base_url']] as $baseUrl) {
|
||||
if ($baseUrl === '') {
|
||||
continue;
|
||||
}
|
||||
$configuredHost = $this->hostFromBaseUrl($baseUrl);
|
||||
if ($configuredHost !== null && strcasecmp($requestHost, $configuredHost) === 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private function hostFromHttpHost(?string $httpHost): ?string
|
||||
{
|
||||
if ($httpHost === null || $httpHost === '') {
|
||||
return null;
|
||||
}
|
||||
$parsed = parse_url('http://' . $httpHost);
|
||||
if ($parsed === false || !isset($parsed['host'])) {
|
||||
return null;
|
||||
}
|
||||
return $parsed['host'];
|
||||
}
|
||||
|
||||
private function hostFromBaseUrl(string $baseUrl): ?string
|
||||
{
|
||||
$parsed = parse_url($baseUrl);
|
||||
if ($parsed === false || !isset($parsed['host'])) {
|
||||
return null;
|
||||
}
|
||||
return $parsed['host'];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,21 +6,20 @@ namespace MageSail\Magesail\Plugin\Store;
|
||||
use Magento\Framework\App\Request\Http;
|
||||
use Magento\Framework\App\RequestInterface;
|
||||
use Magento\Store\Model\BaseUrlChecker;
|
||||
use MageSail\Magesail\Model\TunnelRequestDetector;
|
||||
|
||||
/**
|
||||
* When request has magesail_store (tunnel proxy), consider base URL valid so no 301 is issued.
|
||||
* When request is a MageSail tunnel (header/query or hostname vs persisted tunnel URLs), skip base-URL 301.
|
||||
*/
|
||||
class BaseUrlCheckerTunnelPlugin
|
||||
{
|
||||
private const QUERY_PARAM_STORE = 'magesail_store';
|
||||
private const SERVER_HEADER = 'HTTP_X_MAGESAIL_STORE_CODE';
|
||||
|
||||
/** @var RequestInterface */
|
||||
private $request;
|
||||
|
||||
public function __construct(RequestInterface $request)
|
||||
{
|
||||
$this->request = $request;
|
||||
public function __construct(
|
||||
private readonly RequestInterface $request,
|
||||
private readonly TunnelRequestDetector $tunnelRequestDetector
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -56,25 +55,9 @@ class BaseUrlCheckerTunnelPlugin
|
||||
|
||||
private function hasTunnelStore(Http $request): bool
|
||||
{
|
||||
$value = $request->getParam(self::QUERY_PARAM_STORE);
|
||||
if ($value !== null && $value !== '' && trim((string) $value) !== '') {
|
||||
if ($this->tunnelRequestDetector->getTunnelStoreCode($request) !== null) {
|
||||
return true;
|
||||
}
|
||||
if (method_exists($request, 'getQueryValue')) {
|
||||
$value = $request->getQueryValue(self::QUERY_PARAM_STORE);
|
||||
if ($value !== null && $value !== '' && trim((string) $value) !== '') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
$uri = $request->getRequestUri();
|
||||
if ($uri !== null && str_contains((string) $uri, self::QUERY_PARAM_STORE . '=')) {
|
||||
return true;
|
||||
}
|
||||
$value = $request->getServer(self::SERVER_HEADER);
|
||||
if ($value !== null && $value !== '' && trim((string) $value) !== '') {
|
||||
return true;
|
||||
}
|
||||
// Fallback: superglobals (e.g. if request was built before query string was available)
|
||||
return $this->hasTunnelStoreFromSuperglobals();
|
||||
}
|
||||
|
||||
|
||||
@@ -4,22 +4,27 @@ declare(strict_types=1);
|
||||
namespace MageSail\Magesail\Plugin\Store;
|
||||
|
||||
use Magento\Framework\App\FrontController;
|
||||
use Magento\Framework\App\Request\Http;
|
||||
use Magento\Framework\App\RequestInterface;
|
||||
use Magento\Framework\App\ResponseInterface;
|
||||
use MageSail\Magesail\Model\TunnelRequestDetector;
|
||||
|
||||
/**
|
||||
* When request has X-MageSail-Store-Code (tunnel proxy), skip the base URL redirect
|
||||
* When the request is a MageSail tunnel (header/query or hostname vs persisted tunnel URLs), skip the base URL redirect
|
||||
* so developers can use http://127.0.0.1:port without being redirected to the store's base URL.
|
||||
*/
|
||||
class SkipBaseUrlRedirectForTunnelPlugin
|
||||
{
|
||||
/** $_SERVER key for X-MageSail-Store-Code (web server passes headers as HTTP_*). */
|
||||
private const SERVER_HEADER_STORE_CODE = 'HTTP_X_MAGESAIL_STORE_CODE';
|
||||
/** Query param fallback when server strips custom headers (proxy appends this). */
|
||||
private const QUERY_PARAM_STORE = 'magesail_store';
|
||||
private const SERVER_HEADER = 'HTTP_X_MAGESAIL_STORE_CODE';
|
||||
|
||||
public function __construct(
|
||||
private readonly TunnelRequestDetector $tunnelRequestDetector
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Skip base URL redirect when tunnel store header is present.
|
||||
* Skip base URL redirect when tunnel is detected.
|
||||
*
|
||||
* @param \Magento\Store\App\FrontController\Plugin\RequestPreprocessor $subject
|
||||
* @param callable $proceed
|
||||
@@ -35,34 +40,26 @@ class SkipBaseUrlRedirectForTunnelPlugin
|
||||
\Closure $chain,
|
||||
RequestInterface $request
|
||||
) {
|
||||
if ($this->hasTunnelStoreHeader($request)) {
|
||||
if ($this->hasTunnel($request)) {
|
||||
$request->setDispatched(false);
|
||||
return $chain($request);
|
||||
}
|
||||
return $proceed($frontController, $chain, $request);
|
||||
}
|
||||
|
||||
private function hasTunnelStoreHeader(RequestInterface $request): bool
|
||||
private function hasTunnel(RequestInterface $request): bool
|
||||
{
|
||||
$value = $request->getParam(self::QUERY_PARAM_STORE);
|
||||
if ($value !== null && $value !== '' && trim((string) $value) !== '') {
|
||||
if ($request instanceof Http && $this->tunnelRequestDetector->getTunnelStoreCode($request) !== null) {
|
||||
return true;
|
||||
}
|
||||
if (!$request instanceof \Magento\Framework\App\Request\Http) {
|
||||
return false;
|
||||
}
|
||||
/** @var \Magento\Framework\App\Request\Http $request */
|
||||
if (method_exists($request, 'getQueryValue')) {
|
||||
$value = $request->getQueryValue(self::QUERY_PARAM_STORE);
|
||||
if ($value !== null && $value !== '' && trim((string) $value) !== '') {
|
||||
if (!empty($_GET[self::QUERY_PARAM_STORE]) && trim((string) $_GET[self::QUERY_PARAM_STORE]) !== '') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
$uri = $request->getRequestUri();
|
||||
if ($uri !== null && str_contains((string) $uri, self::QUERY_PARAM_STORE . '=')) {
|
||||
$uri = $_SERVER['REQUEST_URI'] ?? '';
|
||||
if ($uri !== '' && str_contains($uri, self::QUERY_PARAM_STORE . '=')) {
|
||||
return true;
|
||||
}
|
||||
$value = $request->getServer(self::SERVER_HEADER_STORE_CODE);
|
||||
return $value !== null && $value !== '' && trim((string) $value) !== '';
|
||||
$h = $_SERVER[self::SERVER_HEADER] ?? '';
|
||||
return $h !== '' && trim((string) $h) !== '';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,16 +8,20 @@ use Magento\Framework\App\RequestInterface;
|
||||
use Magento\Framework\UrlInterface;
|
||||
use Magento\Store\Model\Store;
|
||||
use MageSail\Magesail\Model\TunnelRequestDetector;
|
||||
use MageSail\Magesail\Model\TunnelStoreState;
|
||||
|
||||
/**
|
||||
* With tunnel proxy, HTTP_HOST is dev.myshop.local but store base URLs point at production (e.g. s1.x64.world).
|
||||
* Rewrite scheme/host for page/link base URLs only — never for static/media/js or asset bases break (404).
|
||||
* When persisted tunnel base URLs use a different path than production (e.g. no /pub/), use the tunnel path so
|
||||
* backend URI validation matches the browser.
|
||||
*/
|
||||
class TunnelStoreBaseUrlPlugin
|
||||
{
|
||||
public function __construct(
|
||||
private readonly RequestInterface $request,
|
||||
private readonly TunnelRequestDetector $tunnelRequestDetector
|
||||
private readonly TunnelRequestDetector $tunnelRequestDetector,
|
||||
private readonly TunnelStoreState $tunnelStoreState
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -51,9 +55,37 @@ class TunnelStoreBaseUrlPlugin
|
||||
return $result;
|
||||
}
|
||||
$scheme = $this->request->isSecure() ? 'https' : 'http';
|
||||
$path = $parts['path'] ?? '/';
|
||||
$path = $this->pathForTunnelRewrite($scheme, $parts['path'] ?? '/');
|
||||
$query = isset($parts['query']) ? '?' . $parts['query'] : '';
|
||||
$fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
|
||||
return $scheme . '://' . $requestHost . $path . $query . $fragment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer path from persisted tunnel base URL (matches holesail vhost) when production base path differs.
|
||||
*/
|
||||
private function pathForTunnelRewrite(string $scheme, string $fallbackPath): string
|
||||
{
|
||||
$state = $this->tunnelStoreState->read();
|
||||
if ($state === null) {
|
||||
return $fallbackPath;
|
||||
}
|
||||
$preferSecure = $scheme === 'https';
|
||||
$ref = $preferSecure ? $state['secure_base_url'] : $state['unsecure_base_url'];
|
||||
if (trim($ref) === '') {
|
||||
$ref = $preferSecure ? $state['unsecure_base_url'] : $state['secure_base_url'];
|
||||
}
|
||||
if (trim($ref) === '') {
|
||||
return $fallbackPath;
|
||||
}
|
||||
$parsed = parse_url($ref);
|
||||
if ($parsed === false) {
|
||||
return $fallbackPath;
|
||||
}
|
||||
$path = $parsed['path'] ?? '';
|
||||
if ($path === '' || $path === null) {
|
||||
return '/';
|
||||
}
|
||||
return $path;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "magesail/magesail",
|
||||
"description": "Holesail P2P tunnel integration for Magento 2 Admin — expose local dev via hs:// keys.",
|
||||
"type": "magento2-module",
|
||||
"version": "1.0.2",
|
||||
"version": "1.0.3",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"keywords": [
|
||||
"magento2",
|
||||
|
||||
@@ -2,94 +2,77 @@
|
||||
|
||||
[](https://magento.com/) [](https://www.php.net/) [](LICENSE)
|
||||
|
||||
**Full documentation:** [docs/README.md](docs/README.md) (installation, configuration, NGINX, routing plugins, troubleshooting).
|
||||
|
||||
## Overview
|
||||
|
||||
MageSail is a Magento 2 extension that integrates **Holesail** (a secure, peer-to-peer tunneling tool based on HyperDHT and Hyperswarm) to expose your local Magento development site to the internet without traditional port forwarding, VPNs, or ngrok-like services. It creates an encrypted tunnel that generates a shareable crypto key, allowing remote access to your local server (e.g., via the key `hs://s000hs1abc...def` in a Holesail client).
|
||||
MageSail is a Magento 2 extension that integrates **[Holesail](https://www.npmjs.com/package/holesail)** (P2P tunneling with HyperDHT / Hyperswarm) so you can expose a local Magento dev site without traditional port forwarding or a central SaaS relay. A shareable key (e.g. `hs://…`) allows remote clients to reach your local HTTP/HTTPS port.
|
||||
|
||||
### Key Features
|
||||
- **Secure Tunneling**: Optional end-to-end encryption using Noise protocol and Sodium crypto primitives.
|
||||
- **Admin Panel Integration**: Start, stop, and monitor tunnels directly from the Magento Admin (System > Holesail Tunnel).
|
||||
- **Auto-Generated Keys**: Share a unique, one-time crypto key for access; regenerates on restart.
|
||||
- **PID Management**: Tracks and cleans up Node.js processes to prevent zombie tunnels.
|
||||
- **Cron Monitoring**: Daily checks for crashed tunnels with optional auto-restart (configurable).
|
||||
- **Logging**: Comprehensive logs for debugging, stored in `var/log/magesail_tunnel.log`.
|
||||
- **Lightweight**: Leverages Holesail's efficient P2P networking; no external services required.
|
||||
- **Magento-Native**: Uses Magento's shell executor, filesystem, and config scopes for seamless integration.
|
||||
**Version:** package `1.0.3` — see [`Magesail/composer.json`](Magesail/composer.json) and [`Magesail/etc/module.xml`](Magesail/etc/module.xml) (`setup_version`).
|
||||
|
||||
This extension is ideal for:
|
||||
- Sharing dev sites with clients/teams without deploying to staging.
|
||||
- Remote debugging during development.
|
||||
- Quick demos or QA sessions.
|
||||
### Key features
|
||||
|
||||
## Private vs Public Keys
|
||||
- **Secure tunneling** — Private (authenticated) vs public Holesail modes, mapped to **Secure Tunnel** Yes/No in Admin.
|
||||
- **Admin lifecycle** — Start/stop tunnel under **System → Holesail Tunnel → Manage Tunnel**; status polling and log tail via AJAX.
|
||||
- **Tunnel store view** — On start, provisions store code **`magesail_tunnel`** with base URLs you supply (aligned with holesail-browser / your vhost). Torn down on stop (with safety rules if that store is the website default).
|
||||
- **NGINX global map** — Optional append/remove of `map $http_host $MAGE_RUN_CODE` / `$MAGE_RUN_TYPE` lines plus `nginx -t` and reload (or wrapper script). Admin screen: **System → Holesail Tunnel → NGINX Global Map**.
|
||||
- **Storefront / admin routing** — Plugins detect tunnel traffic via header **`X-MageSail-Store-Code`**, query **`magesail_store`**, `___store`, or **hostname** vs persisted tunnel URLs; adjust `MAGE_RUN_*`, backend front name resolution, generated base URLs, and **skip redirect-to-base** where appropriate.
|
||||
- **PID and logs** — `var/magesail.pid`, `var/magesail.key`, `var/log/magesail_tunnel.log`; optional DB rows in **`magesail_logs`**.
|
||||
- **Cron** — Daily job cleans stale PID/key; optional **auto-restart** when the Node process died (config-driven, no custom cron code required).
|
||||
|
||||
Holesail supports two connection modes: **Private** (default, secure) and **Public** (open sharing). These correspond to the "Secure Tunnel" setting in MageSail (Yes = Private, No = Public). The terminology aligns with Private/Public Keys, where:
|
||||
Good for client demos, remote QA, and team access without deploying to staging.
|
||||
|
||||
### Private Keys
|
||||
Private keys are the default mode in Holesail and provide authenticated access.
|
||||
## Private vs public keys (Holesail)
|
||||
|
||||
When you start a tunnel in Private mode:
|
||||
- A custom private seed is generated.
|
||||
- From this seed, a keypair is derived: a **Private Key** (kept secret on the server) and a **Public Key** (announced on the P2P DHT network for discovery).
|
||||
- The **Public Key** acts like an "address" (similar to an SSH public key or IP)—peers can find your server via DHT but cannot connect without authentication.
|
||||
- When sharing, you provide the full **seed** to trusted parties (e.g., team members).
|
||||
- On the client side, the seed derives the same keypair. During connection, the shared private key is verified by the server.
|
||||
- If the key mismatches or no key is provided, the server silently rejects the connection.
|
||||
Holesail supports **private** (default, authenticated) and **public** (open) modes. In Admin, **Secure Tunnel** = **Yes** means private mode, **No** means public.
|
||||
|
||||
**Security Analogy**: Treat Private keys like SSH private keys—do **not** share with untrusted parties. Sharing allows the recipient to derive the keypair and connect securely. If someone starts a server with your private key, it could hijack the tunnel.
|
||||
### Private mode
|
||||
|
||||
**Use Case**: Personal/team access where authentication is required (e.g., dev handoff to a specific QA engineer).
|
||||
- A seed derives a keypair; the server keeps authentication material; peers need the shared secret to connect.
|
||||
- Treat shared seeds like SSH private keys: only share with trusted parties.
|
||||
|
||||
### Public Keys
|
||||
Public mode is for open sharing without authentication.
|
||||
### Public mode
|
||||
|
||||
In this mode:
|
||||
- A random keypair is generated, but the **Private Key** is discarded immediately.
|
||||
- Only the **Public Key** is announced on the P2P DHT and becomes your shareable **Public Key** (e.g., `hs://0000hs1abc...def`).
|
||||
- No private key verification occurs—anyone with the public key can connect directly.
|
||||
- The public key serves as a discoverable "address" on the network.
|
||||
- A discoverable public address; anyone with the key can reach the tunnel endpoint.
|
||||
- Protect sensitive data with Magento’s own auth (customer login, admin ACL, etc.).
|
||||
|
||||
**Security Analogy**: Treat Public keys like domain names on a public server—anyone can access the endpoint. If sensitive data is exposed, protect it with Magento's built-in auth (e.g., admin login, passwords) rather than relying on the tunnel.
|
||||
|
||||
**Use Case**: Quick, unauthenticated demos or public previews (e.g., client walkthrough without sharing secrets).
|
||||
|
||||
In MageSail, the "Secure Tunnel" config toggles between these modes.
|
||||
|
||||
Private mode is recommended for most dev sharing to enforce key-based auth.
|
||||
Private mode is recommended for most dev sharing.
|
||||
|
||||
## Requirements
|
||||
|
||||
- **Magento 2**: 2.4.0+ (tested on 2.4.6+)
|
||||
- **PHP**: 8.1+
|
||||
- **Node.js**: 18+ (for the Holesail server script; installed via package manager)
|
||||
- **npm**: For installing Holesail dependencies (runs automatically on first start)
|
||||
- **Server Environment**: Linux/macOS (Windows untested; may require WSL). Root/sudo not required, but shell access needed for `ps` and `kill`.
|
||||
- **Composer**: For module installation.
|
||||
- **Magento 2**: 2.4.x (see Composer constraints in [`Magesail/composer.json`](Magesail/composer.json)).
|
||||
- **PHP**: 8.1, 8.2, or 8.3.
|
||||
- **Node.js**: 18+ for `start-server.js`.
|
||||
- **npm**: Install dependencies under `Magesail/scripts/`.
|
||||
- **OS**: Linux/macOS typical; Windows untested (WSL may work). Shell tools: `ps`, `kill`, `nohup`.
|
||||
- **Composer**: For packaged installs.
|
||||
|
||||
**Dependencies Installed Automatically**:
|
||||
- Holesail (^2.3.2+) and its transitive deps (e.g., HyperDHT, Sodium-Univeral for crypto).
|
||||
Holesail and npm dependencies are pulled when you run `npm install` in the scripts directory (see [docs/scripts.md](docs/scripts.md)).
|
||||
|
||||
## Installation
|
||||
|
||||
### Step 1: Install (Composer or clone)
|
||||
### 1. Install the package
|
||||
|
||||
**Composer (Packagist or VCS path repo)** — package name `magesail/magesail`; module root is `MageSail/Magesail` inside the package:
|
||||
**Composer** — package name `magesail/magesail`:
|
||||
|
||||
```bash
|
||||
composer require magesail/magesail:^1.0
|
||||
```
|
||||
|
||||
If the package is not on Packagist yet, add a path or VCS repository in the project `composer.json`, then `composer require magesail/magesail:@dev`. After install, set **Stores > Configuration > Holesail Tunnel > Scripts directory** to the absolute path of the `scripts` folder (e.g. `<magento-root>/vendor/magesail/magesail/scripts`).
|
||||
If the package is not on Packagist, add a path or VCS repository in the project `composer.json`, then `composer require magesail/magesail:@dev`.
|
||||
|
||||
**Clone into app/code**:
|
||||
Set **Stores → Configuration → General → Holesail Tunnel → Scripts directory** to the absolute path of the folder that contains `start-server.js`, e.g. `<magento-root>/vendor/magesail/magesail/scripts`.
|
||||
|
||||
**Git clone under `app/code`:**
|
||||
|
||||
```bash
|
||||
cd <magento-root>/app/code/
|
||||
git clone [email protected]:snxraven/MageSail.git
|
||||
git clone <repository-url> MageSail
|
||||
```
|
||||
|
||||
### Step 2: Enable the Module
|
||||
Run the following commands:
|
||||
Module root: `app/code/MageSail/Magesail/`.
|
||||
|
||||
### 2. Enable the module
|
||||
|
||||
```bash
|
||||
php bin/magento module:enable MageSail_Magesail
|
||||
@@ -98,104 +81,104 @@ php bin/magento setup:di:compile
|
||||
php bin/magento cache:flush
|
||||
```
|
||||
|
||||
### Step 3: Verify Installation
|
||||
- Check module status: `php bin/magento module:status MageSail_Magesail` (should show "enabled").
|
||||
- Admin menu: Navigate to **System > Holesail Tunnel** (new entry under System Tools).
|
||||
- Database: A `magesail_logs` table should be created in your Magento DB for logging.
|
||||
### 3. Verify
|
||||
|
||||
- `php bin/magento module:status MageSail_Magesail` → enabled.
|
||||
- Admin: **System → Holesail Tunnel** (Manage Tunnel, NGINX Global Map).
|
||||
- Database: table **`magesail_logs`**.
|
||||
|
||||
### 4. Node dependencies (one-time)
|
||||
|
||||
### Step 4: Install Node Dependencies (One-Time)
|
||||
Install the holesail library:
|
||||
```bash
|
||||
cd <magento-root>/app/code/MageSail/Magesail/scripts
|
||||
npm install [email protected]
|
||||
# or: cd <magento-root>/vendor/magesail/magesail/scripts
|
||||
npm install
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
All settings are managed via the Magento Admin under **Stores > Configuration > General > Holesail Tunnel**.
|
||||
All settings: **Stores → Configuration → General → Holesail Tunnel**.
|
||||
|
||||
### Available Settings
|
||||
| Field | Type | Default | Description |
|
||||
|-------|------|---------|-------------|
|
||||
| **Secure Tunnel** | Select (Yes/No) | Yes | Private (authenticated) vs Public mode. |
|
||||
| **Port** | Text | 80 | Local port; start action allows **80 or 443** only. |
|
||||
| **Scripts directory** | Text | *(empty)* | Absolute path to the folder containing `start-server.js`. Empty = `app/code/MageSail/Magesail/scripts` under Magento root. |
|
||||
| **Auto-restart on crash** | Yes/No | No | Daily cron restarts the tunnel if the Node process died. |
|
||||
### Tunnel settings
|
||||
|
||||
- **Scope**: Default (global), Website, or Store View.
|
||||
- **Save Config**: After changes, flush cache: `php bin/magento cache:flush config`.
|
||||
| Field | Default | Description |
|
||||
|-------|---------|-------------|
|
||||
| **Secure Tunnel** | Yes | Private vs public Holesail mode. |
|
||||
| **Port** | 80 | Local port; **Start Tunnel** only allows **80** or **443**. |
|
||||
| **Scripts directory** | *(empty)* | Absolute path to `start-server.js` folder. Empty = default under `app/code/MageSail/Magesail/scripts` from Magento root. |
|
||||
| **Auto-restart on crash** | No | If Yes, the **daily** cron job restarts the tunnel after detecting a dead PID (uses this port and secure mode). |
|
||||
|
||||
**Advanced Config (Optional)**:
|
||||
- Edit `app/etc/config.php` directly for CLI-only setups:
|
||||
```php
|
||||
'magesail' => [
|
||||
'settings' => [
|
||||
'mode' => 1,
|
||||
'port' => '80',
|
||||
'script_path' => '', // optional absolute path to scripts/
|
||||
'auto_restart' => 0
|
||||
]
|
||||
]
|
||||
```
|
||||
Scoped globally / per website / per store view. After changes: `php bin/magento cache:flush config`.
|
||||
|
||||
### NGINX configuration
|
||||
|
||||
Used when you manage `MAGE_RUN_CODE` / `MAGE_RUN_TYPE` via a shared **global map** file (e.g. Ansible). Fields include **Global map file path**, **nginx binary path**, **Temporary PID file** (for isolated `nginx -t`), **Reload wrapper script** (when PHP cannot `nginx -s reload`), map variable names, **MAGE_RUN_TYPE** value, and **Disable base URL redirect for tunnel**. See [docs/configuration.md](docs/configuration.md) and [docs/nginx-global-map.md](docs/nginx-global-map.md).
|
||||
|
||||
**Advanced (`app/etc/config.php`):** you can set `magesail/settings/*` and `magesail/nginx/*` keys to match `system.xml` paths.
|
||||
|
||||
## Usage
|
||||
|
||||
### Starting the Tunnel
|
||||
1. Log in to Magento Admin.
|
||||
2. Go to **System > Holesail Tunnel**.
|
||||
3. If no tunnel is running, click **Start Tunnel**.
|
||||
- Validates config (port must be 80/443; secure mode optional).
|
||||
- Spawns a background Node.js process via `nohup` (logs to `var/log/magesail_tunnel.log`).
|
||||
- PID saved to `var/magesail.pid`; key to `var/magesail.key`.
|
||||
### Admin menu
|
||||
|
||||
4. Wait ~10-30 seconds for the key to generate (polls via AJAX every 3s).
|
||||
5. Once ready: **"Tunnel is running (PID: 12345). Share this key: hs://s0001abc...def"**
|
||||
- **System → Holesail Tunnel → Manage Tunnel** — start/stop, base URLs, key display, log snippet.
|
||||
- **System → Holesail Tunnel → NGINX Global Map** — edit/validate/reload the configured map file (requires config ACL).
|
||||
|
||||
### Sharing and Accessing the Tunnel
|
||||
- **Share the Key**: Copy the crypto key (e.g., `hs://s000hs1abc...def`).
|
||||
- **Remote Access**:
|
||||
- Use a Holesail client: `holesail hs://s000hs1abc...def` (proxies to HTTPS/HTTP based on port).
|
||||
- Holesail will automatically detect the client port and address configuration, use the `--port` switch to change the local port of needed, for example `holesail hs://s000hs1abc...def --port 1234` will be able to be connected to via `curl 127.0.0.1:1234`
|
||||
- Suggested, is to edit your `/etc/hosts` file to add your `baseURL` which resolves to `127.0.0.1`
|
||||
- Example host line: `127.0.0.1 example-shop.com`
|
||||
- SSL Certificates will most likely be invalid, however, you may bypass the warnings and continue development and access within Magento.
|
||||
- Tunnels persist until stopped (P2P connections auto-reconnect).
|
||||
### Starting the tunnel
|
||||
|
||||
### Stopping the Tunnel
|
||||
- From Admin: Click **Stop Tunnel** (sends `kill <pid>`; cleans PID/key files).
|
||||
- Manual: `kill $(cat var/magesail.pid)` or delete `var/magesail.pid`.
|
||||
1. Open **Manage Tunnel**.
|
||||
2. Enter **Tunnel base URL (unsecure)** (required). It must match the hostname you use in the browser / holesail-browser vhost (including `http` vs `https`).
|
||||
3. Optionally set **Tunnel base URL (secure)** and **Use secure URLs on storefront and in admin**.
|
||||
4. Click **Start Tunnel**.
|
||||
|
||||
The module creates/updates the **`magesail_tunnel`** store view, persists **`var/magesail_tunnel_store.json`**, may update the NGINX map, then starts Node. PID is stored in **`var/magesail.pid`**; the Holesail key in **`var/magesail.key`**. The UI polls **`magesail/tunnel/status`** until the key appears.
|
||||
|
||||
If the map was updated but nginx could not reload (common for the PHP user), follow the on-screen hint or [docs/nginx-global-map.md](docs/nginx-global-map.md).
|
||||
|
||||
### Proxy / client routing
|
||||
|
||||
So Magento resolves the tunnel store, your proxy or browser can use:
|
||||
|
||||
- Header: **`X-MageSail-Store-Code: magesail_tunnel`**
|
||||
- Query: **`magesail_store=magesail_tunnel`**
|
||||
- Or native: **`___store=magesail_tunnel`**
|
||||
|
||||
If the request host matches the provisioned tunnel base URL host, detection can work without those hints. Details: [docs/request-routing-and-plugins.md](docs/request-routing-and-plugins.md).
|
||||
|
||||
### Sharing access
|
||||
|
||||
- Copy the **hs://…** (or key string shown) for Holesail clients.
|
||||
- Local port override example: `holesail hs://… --port 1234` then `curl http://127.0.0.1:1234/`.
|
||||
- You may add the shop hostname to `/etc/hosts` pointing at `127.0.0.1` when using a local listener.
|
||||
- TLS to localhost often uses dev certs; browsers may warn.
|
||||
|
||||
### Stopping the tunnel
|
||||
|
||||
Use **Stop Tunnel** in Admin (kills PID, cleans files, removes map lines, tears down the tunnel store when allowed). Manual: `kill $(cat var/magesail.pid)` and remove stale `var/magesail.*` if needed.
|
||||
|
||||
### Monitoring
|
||||
- **Admin Dashboard**: Real-time status (running/stopped, PID, key).
|
||||
- **Logs**: Tail `var/log/magesail_tunnel.log` for Node.js output:
|
||||
```bash
|
||||
tail -f var/log/magesail_tunnel.log
|
||||
```
|
||||
- Example: `Server ready: hs://s0001abc...def (written to var/magesail.key)`
|
||||
- **Database Logs**: Table `magesail_logs` records start/stop, cron cleanup, and auto-restart events.
|
||||
|
||||
### Cron Monitoring
|
||||
- Enabled by default: Runs daily at midnight (`0 0 * * *`).
|
||||
- Checks PID; cleans stale files on crash.
|
||||
- Logs warnings to `var/log/system.log` (e.g., "Magesail tunnel crashed; cleaned up PID files.").
|
||||
- **Auto-Restart**: Not enabled by default. Extend `Cron/DailyMonitor.php` for custom logic:
|
||||
```php
|
||||
// In execute(): if (!$isRunning && $this->scopeConfig->getValue('magesail/settings/auto_restart')) { /* restart code */ }
|
||||
```
|
||||
- **UI** — running state, PID, key.
|
||||
- **File log** — `tail -f var/log/magesail_tunnel.log`
|
||||
- **Database** — `magesail_logs` for start/stop/cron messages.
|
||||
|
||||
### Cron
|
||||
|
||||
- **Schedule:** daily at midnight (`0 0 * * *`), [`Magesail/etc/crontab.xml`](Magesail/etc/crontab.xml).
|
||||
- **Behavior:** If the PID file exists but the process is dead, stale files are cleaned and a warning is logged. With **Auto-restart on crash** = **Yes**, the job calls the same start path as Admin (port 80/443 only).
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| **"Error starting tunnel: Command failed"** | Node.js missing or npm install failed. | Install Node 18+: `curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - && sudo apt-get install -y nodejs`. Then `cd scripts && npm install`. |
|
||||
| **"Invalid port"** | Non-numeric or invalid value. | Set to 80/443 in config; validate with `netstat -tuln \| grep :80`. |
|
||||
| **PID file stale (ghost process)** | Crash without cleanup. | Delete `var/magesail.pid` and restart. Cron auto-cleans daily. |
|
||||
| **Key not updating in UI** | AJAX poll fails. | Check browser console; ensure `magesail/tunnel/status` endpoint accessible. |
|
||||
| **Access denied (key)** | Public mode + auth mismatch. | Use correct client mode or enable Private. |
|
||||
| **High CPU/Memory** | Multiple tunnels. | Stop old ones: `ps aux \| grep start-server.js`. Limit to one via cron. |
|
||||
Short table — expanded in [docs/troubleshooting.md](docs/troubleshooting.md).
|
||||
|
||||
### Debug Steps
|
||||
1. **Permissions**: Ensure `var/` writable: `chmod -R 775 var/`.
|
||||
2. **Logs**: Enable debug in `start-server.js` (add `console.log`); tail file.
|
||||
3. **Holesail Standalone**: Test without Magento: `npm i -g holesail && holesail --live 80`.
|
||||
4. **Module Reinstall**: `php bin/magento module:disable MageSail_Magesail && php bin/magento setup:upgrade`.
|
||||
| Issue | Suggestion |
|
||||
|-------|------------|
|
||||
| Start fails / “Command failed” | Node/npm path for PHP user; run `npm install` in **Scripts directory**. |
|
||||
| “Tunnel base URL is required” | Fill unsecure base URL before start. |
|
||||
| Invalid port | Config must allow 80 or 443 for start. |
|
||||
| Stale PID | Delete `var/magesail.pid` or wait for cron; check for zombie `start-server.js`. |
|
||||
| 301 to production URL | Tunnel plugins + NGINX map + reload; see [docs/tunnel-store-and-multistore.md](docs/tunnel-store-and-multistore.md). |
|
||||
| Reload / map permission errors | Map file writable by PHP user; wrapper + sudoers — [Magesail/scripts/README-NGINX-RELOAD.md](Magesail/scripts/README-NGINX-RELOAD.md). |
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the **GNU General Public License v3.0 or later** — see [LICENSE](LICENSE) and [`Magesail/composer.json`](Magesail/composer.json).
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# MageSail documentation
|
||||
|
||||
MageSail (`MageSail_Magesail`) integrates [Holesail](https://www.npmjs.com/package/holesail) with Magento 2 Admin: tunnel lifecycle, optional NGINX global-map updates, and storefront routing for tunneled hosts.
|
||||
|
||||
## Guides
|
||||
|
||||
| Document | Description |
|
||||
|----------|-------------|
|
||||
| [overview.md](overview.md) | Purpose, stack, high-level request flow |
|
||||
| [installation.md](installation.md) | Composer vs `app/code`, enablement, Node/npm |
|
||||
| [configuration.md](configuration.md) | All Admin config paths (tunnel + NGINX) |
|
||||
| [admin-ui.md](admin-ui.md) | System → Holesail Tunnel screens and actions |
|
||||
| [tunnel-store-and-multistore.md](tunnel-store-and-multistore.md) | Store view `magesail_tunnel`, base URLs, state files |
|
||||
| [request-routing-and-plugins.md](request-routing-and-plugins.md) | DI plugins, headers, and base-URL behavior |
|
||||
| [nginx-global-map.md](nginx-global-map.md) | Map file edits, `nginx -t`, reload, permissions |
|
||||
| [cron-and-monitoring.md](cron-and-monitoring.md) | Daily cron, auto-restart, DB logs |
|
||||
| [php-classes-reference.md](php-classes-reference.md) | PHP classes by layer (quick index) |
|
||||
| [scripts.md](scripts.md) | Node scripts, nginx helpers, probes |
|
||||
| [troubleshooting.md](troubleshooting.md) | Common failures and fixes |
|
||||
|
||||
## Deeper dives (in the module tree)
|
||||
|
||||
- [Tunnel, base URL redirect, and NGINX](../Magesail/doc/TUNNEL_BASE_URL_REDIRECT.md) — long-form analysis of redirect bypass and map integration.
|
||||
- [NGINX reload from PHP](../Magesail/scripts/README-NGINX-RELOAD.md) — PHP user vs master process, sudoers, wrapper script.
|
||||
|
||||
## Root entry point
|
||||
|
||||
The repository [README.md](../README.md) is the quick start; this directory is the full split-by-topic reference.
|
||||
@@ -0,0 +1,56 @@
|
||||
# Admin UI
|
||||
|
||||
Admin route prefix: **`magesail`** (see [`Magesail/etc/adminhtml/routes.xml`](../Magesail/etc/adminhtml/routes.xml)). URLs are under your Magento admin base (`/admin_xxx/magesail/...`).
|
||||
|
||||
## Menu: System → Holesail Tunnel
|
||||
|
||||
Defined in [`Magesail/etc/adminhtml/menu.xml`](../Magesail/etc/adminhtml/menu.xml).
|
||||
|
||||
### Manage Tunnel
|
||||
|
||||
- **Action**: `magesail/tunnel/index` → [`Controller/Adminhtml/Tunnel/Index.php`](../Magesail/Controller/Adminhtml/Tunnel/Index.php)
|
||||
- **Layout / template**: [`view/adminhtml/layout/magesail_tunnel_index.xml`](../Magesail/view/adminhtml/layout/magesail_tunnel_index.xml), [`view/adminhtml/templates/tunnel/index.phtml`](../Magesail/view/adminhtml/templates/tunnel/index.phtml)
|
||||
- **Block**: [`Block/Adminhtml/Tunnel.php`](../Magesail/Block/Adminhtml/Tunnel.php)
|
||||
|
||||
**Stopped state**
|
||||
|
||||
- **Tunnel base URL (unsecure)** — required before **Start Tunnel**; must match the hostname you use in the browser / holesail-browser vhost.
|
||||
- **Tunnel base URL (secure)** — optional; see [tunnel-store-and-multistore.md](tunnel-store-and-multistore.md).
|
||||
- **Use secure URLs on storefront and in admin** — optional checkbox; drives scoped `web/secure/*` flags when provisioning.
|
||||
|
||||
**Start** sends an AJAX (or form) request with `action=start` and the URL fields; the controller provisions the tunnel store, updates NGINX map if configured, then starts Node.
|
||||
|
||||
**Stop** tears down the tunnel process, removes map lines, and deletes the tunnel store view when safe (see provisioner / logs).
|
||||
|
||||
**While running**
|
||||
|
||||
- Status banner (PID, key when available).
|
||||
- Link to **Stores configuration: Holesail Tunnel**.
|
||||
- If the map was updated but reload failed, a warning suggests manual reload or configuring **Reload wrapper script** (see [nginx-global-map.md](nginx-global-map.md)).
|
||||
|
||||
### AJAX / JSON endpoints
|
||||
|
||||
| Path | Controller | Purpose |
|
||||
|------|------------|---------|
|
||||
| `magesail/tunnel/status` | [`Tunnel/Status.php`](../Magesail/Controller/Adminhtml/Tunnel/Status.php) | JSON tunnel status (running, PID, key) for UI polling. |
|
||||
| `magesail/tunnel/logtail` | [`Tunnel/Logtail.php`](../Magesail/Controller/Adminhtml/Tunnel/Logtail.php) | JSON tail of last lines of `var/log/magesail_tunnel.log` for the dashboard. |
|
||||
|
||||
Start/stop can return JSON when the request is AJAX (`X-Requested-With: XMLHttpRequest` or `ajax=1`).
|
||||
|
||||
### NGINX Global Map
|
||||
|
||||
- **Action**: `magesail/nginx/map` → [`Controller/Adminhtml/Nginx/Map.php`](../Magesail/Controller/Adminhtml/Nginx/Map.php)
|
||||
- **Block / template**: [`Block/Adminhtml/Nginx/Map.php`](../Magesail/Block/Adminhtml/Nginx/Map.php), [`view/adminhtml/templates/nginx/map.phtml`](../Magesail/view/adminhtml/templates/nginx/map.phtml)
|
||||
|
||||
Full-screen tools for the configured **global map** file: read raw content, write, parse into blocks, save blocks, run **`nginx -t`** via a minimal generated config, trigger reload (or wrapper), and diagnostics. Sub-actions are selected with request param **`action`**: `read`, `write`, `validate`, `reload`, `parse`, `save_blocks`, `diagnostics` (AJAX/JSON when `X-Requested-With: XMLHttpRequest` or `ajax=1`).
|
||||
|
||||
Requires **`MageSail_Magesail::config`** ACL resource. Operational details: [nginx-global-map.md](nginx-global-map.md).
|
||||
|
||||
## ACL
|
||||
|
||||
[`Magesail/etc/acl.xml`](../Magesail/etc/acl.xml):
|
||||
|
||||
- **`MageSail_Magesail::tunnel`** — Manage Tunnel and related tunnel actions.
|
||||
- **`MageSail_Magesail::config`** — Configuration section and NGINX Global Map menu item.
|
||||
|
||||
Assign roles under **System → Permissions → User Roles**.
|
||||
@@ -0,0 +1,41 @@
|
||||
# Configuration
|
||||
|
||||
All paths below are under **Stores → Configuration → General → Holesail Tunnel** unless noted. XML sources: [`Magesail/etc/adminhtml/system.xml`](../Magesail/etc/adminhtml/system.xml), defaults in [`Magesail/etc/config.xml`](../Magesail/etc/config.xml).
|
||||
|
||||
## Settings (tunnel)
|
||||
|
||||
| Config path | Admin label | Notes |
|
||||
|-------------|-------------|--------|
|
||||
| `magesail/settings/mode` | **Secure Tunnel** | Yes = private (authenticated) Holesail mode; No = public discoverable key. |
|
||||
| `magesail/settings/port` | **Port** | Configured local port; **Start Tunnel** only allows **80** or **443**. |
|
||||
| `magesail/settings/script_path` | **Scripts directory** | Absolute path to folder containing `start-server.js`. Empty = default under `app/code/MageSail/Magesail/scripts` relative to Magento root. |
|
||||
| `magesail/settings/auto_restart` | **Auto-restart on crash** | When Yes, daily cron may restart the tunnel after cleaning a stale PID (see [cron-and-monitoring.md](cron-and-monitoring.md)). |
|
||||
|
||||
Scoped at **Default**, **Website**, or **Store View**. After changes: `php bin/magento cache:flush config`.
|
||||
|
||||
## NGINX Configuration
|
||||
|
||||
| Config path | Admin label | Notes |
|
||||
|-------------|-------------|--------|
|
||||
| `magesail/nginx/global_map_path` | **Global map file path** | Absolute path to the shared map file (e.g. Ansible-managed) containing `map $http_host $MAGE_RUN_CODE` / `$MAGE_RUN_TYPE` blocks. |
|
||||
| `magesail/nginx/nginx_binary` | **nginx binary path** | Default `nginx` on `PATH`; use full path (e.g. `/usr/sbin/nginx`) if PHP cannot find it. |
|
||||
| `magesail/nginx/test_pid_path` | **Temporary PID file** | Used by minimal `nginx -t -c …` validation config; leave empty for a temp path writable by PHP. |
|
||||
| `magesail/nginx/reload_wrapper_script` | **Reload wrapper script** | Optional executable Magento runs instead of `nginx -s reload` (often needed so the PHP user can signal the master). See [nginx-global-map.md](nginx-global-map.md). |
|
||||
| `magesail/nginx/map_source_variable` | **Map source variable** | First argument of `map` (without `$`), usually `http_host`. |
|
||||
| `magesail/nginx/map_run_code_variable` | **MAGE_RUN_CODE map variable** | Second map name for store code, usually `MAGE_RUN_CODE`. |
|
||||
| `magesail/nginx/map_run_type_variable` | **MAGE_RUN_TYPE map variable** | Second map name for run type, usually `MAGE_RUN_TYPE`. |
|
||||
| `magesail/nginx/map_run_type_value` | **Value for MAGE_RUN_TYPE line** | Usually `store` when `MAGE_RUN_CODE` is a store view code. |
|
||||
| `magesail/nginx/disable_base_url_redirect` | **Disable base URL redirect for tunnel** | When Yes, sets scoped redirect behavior for the tunnel store view during provisioning (see tunnel store doc). |
|
||||
|
||||
## Defaults from `config.xml`
|
||||
|
||||
For the NGINX group, defaults include:
|
||||
|
||||
- `map_source_variable` = `http_host`
|
||||
- `map_run_code_variable` = `MAGE_RUN_CODE`
|
||||
- `map_run_type_variable` = `MAGE_RUN_TYPE`
|
||||
- `map_run_type_value` = `store`
|
||||
|
||||
## Optional `app/etc/config.php`
|
||||
|
||||
You can mirror `magesail/settings/*` (and nginx keys if needed) in `config.php` for environment-specific deploys; same paths as above.
|
||||
@@ -0,0 +1,32 @@
|
||||
# Cron and monitoring
|
||||
|
||||
## Schedule
|
||||
|
||||
[`Magesail/etc/crontab.xml`](../Magesail/etc/crontab.xml) registers **`magesail_monitor`** in the default group:
|
||||
|
||||
- **Cron expression**: `0 0 * * *` (daily at midnight server time).
|
||||
|
||||
## Job implementation
|
||||
|
||||
[`Cron/DailyMonitor.php`](../Magesail/Cron/DailyMonitor.php):
|
||||
|
||||
1. If `var/magesail.pid` exists, checks whether the PID is still alive (`TunnelStatus::isProcessAlive`).
|
||||
2. If the PID file existed but the process is **not** running:
|
||||
- Calls `TunnelStatus::cleanupStaleState()` (cleans PID/key and related state per implementation).
|
||||
- Logs to **`magesail_logs`** via [`MagesailLog::add`](../Magesail/Model/MagesailLog.php) and to **`system.log`** with a warning.
|
||||
- If **`magesail/settings/auto_restart`** is **Yes**, calls `TunnelManager::start()` with port and secure mode from config (port must be **80** or **443**). Success/failure is logged.
|
||||
3. Always logs an info line that the monitor ran.
|
||||
|
||||
## Auto-restart
|
||||
|
||||
Controlled only by Admin config **Auto-restart on crash** — no code changes in `DailyMonitor` are required.
|
||||
|
||||
## Database log table
|
||||
|
||||
[`MagesailLog`](../Magesail/Model/MagesailLog.php) inserts into **`magesail_logs`** (`message`, `created_at`), created by [`Setup/InstallSchema.php`](../Magesail/Setup/InstallSchema.php). Messages are truncated to 255 characters.
|
||||
|
||||
## File logs
|
||||
|
||||
- **Node / Holesail stdout**: `var/log/magesail_tunnel.log` (path may be centralized in `TunnelStatus`).
|
||||
|
||||
Use the Admin tunnel page log tail (`magesail/tunnel/logtail`) or `tail -f` on the server.
|
||||
@@ -0,0 +1,61 @@
|
||||
# Installation
|
||||
|
||||
## Requirements
|
||||
|
||||
- **Magento 2**: 2.4.x (framework alignment via Composer; see [`Magesail/composer.json`](../Magesail/composer.json)).
|
||||
- **PHP**: 8.1, 8.2, or 8.3 (`~8.1||~8.2||~8.3` in composer).
|
||||
- **Node.js**: 18+ recommended for the Holesail script.
|
||||
- **npm**: To install dependencies under `Magesail/scripts/`.
|
||||
- **Shell**: `ps`, `kill`, `nohup` (Linux/macOS typical).
|
||||
|
||||
## Composer
|
||||
|
||||
Package name: **`magesail/magesail`**. The Magento module files live under the `Magesail/` directory inside the package.
|
||||
|
||||
```bash
|
||||
composer require magesail/magesail:^1.0
|
||||
```
|
||||
|
||||
If the package is not on Packagist, add a **path** or **VCS** repository in the project `composer.json`, then require `@dev` or a branch alias.
|
||||
|
||||
After a **vendor** install, set **Stores → Configuration → Holesail Tunnel → Scripts directory** to the absolute path of the `scripts` folder, for example:
|
||||
|
||||
`<magento-root>/vendor/magesail/magesail/scripts`
|
||||
|
||||
(Adjust if your Composer package root differs; the field must point at the directory containing `start-server.js`.)
|
||||
|
||||
## Clone into `app/code`
|
||||
|
||||
```bash
|
||||
cd <magento-root>/app/code/
|
||||
git clone <your-remote-url> MageSail
|
||||
```
|
||||
|
||||
Module root: `app/code/MageSail/Magesail/`.
|
||||
|
||||
## Enable the module
|
||||
|
||||
```bash
|
||||
php bin/magento module:enable MageSail_Magesail
|
||||
php bin/magento setup:upgrade
|
||||
php bin/magento setup:di:compile
|
||||
php bin/magento cache:flush
|
||||
```
|
||||
|
||||
## Node dependencies
|
||||
|
||||
One-time (from the `scripts` directory — use the path that matches your install):
|
||||
|
||||
```bash
|
||||
cd <magento-root>/app/code/MageSail/Magesail/scripts
|
||||
# or: cd <magento-root>/vendor/magesail/magesail/scripts
|
||||
npm install
|
||||
```
|
||||
|
||||
[`package.json`](../Magesail/scripts/package.json) pins Holesail; keep `node_modules/` out of VCS unless your workflow requires otherwise.
|
||||
|
||||
## Verification
|
||||
|
||||
- `php bin/magento module:status MageSail_Magesail` → enabled.
|
||||
- Admin: **System → Holesail Tunnel** appears.
|
||||
- Database: table `magesail_logs` after `setup:upgrade` (see [`Setup/InstallSchema.php`](../Magesail/Setup/InstallSchema.php)).
|
||||
@@ -0,0 +1,33 @@
|
||||
# NGINX global map
|
||||
|
||||
MageSail can **append** and **remove** lines inside your existing **`map $http_host $MAGE_RUN_CODE`** and **`map $http_host $MAGE_RUN_TYPE`** blocks so the tunneled hostname sets PHP-FPM bootstrap params without hand-editing Ansible.
|
||||
|
||||
Implementation: [`NginxGlobalMapManager`](../Magesail/Model/NginxGlobalMapManager.php), [`NginxMapParser`](../Magesail/Model/NginxMapParser.php), configured under **Stores → Configuration → Holesail Tunnel → NGINX Configuration** (see [configuration.md](configuration.md)).
|
||||
|
||||
## Validation strategy
|
||||
|
||||
Magento generates a **minimal** `nginx` config that only includes your global map file, with its own `pid` path and empty `events` / `http` stubs. It runs:
|
||||
|
||||
`nginx -t -c <minimal.conf>`
|
||||
|
||||
That validates **map syntax** without loading the full production `nginx.conf`, avoiding duplicate `pid` directives and `/run/nginx.pid` permission problems.
|
||||
|
||||
## Reload
|
||||
|
||||
After a successful test, MageSail attempts **`nginx -s reload`** (or the configured **Reload wrapper script**). The PHP-FPM user often **cannot** signal the nginx master (`Operation not permitted`). In that case:
|
||||
|
||||
- Reload nginx manually (`sudo systemctl reload nginx`, etc.), or
|
||||
- Install a small wrapper plus **sudoers** so the web user may run only that script — see [Magesail/scripts/README-NGINX-RELOAD.md](../Magesail/scripts/README-NGINX-RELOAD.md) and the probe [Magesail/scripts/nginx-reload-probe.php](../Magesail/scripts/nginx-reload-probe.php).
|
||||
|
||||
## File permissions
|
||||
|
||||
The **global map file** must be **writable by the PHP user** (e.g. `www-data`). Typical fixes: group ownership, ACL, or deployment user alignment. Details and examples: [Magesail/doc/TUNNEL_BASE_URL_REDIRECT.md](../Magesail/doc/TUNNEL_BASE_URL_REDIRECT.md) (permissions section).
|
||||
|
||||
## Admin tools
|
||||
|
||||
**System → Holesail Tunnel → NGINX Global Map** exposes read/write/validate/reload/diagnostics over the same path (see [admin-ui.md](admin-ui.md)).
|
||||
|
||||
## Further reading
|
||||
|
||||
- [Tunnel, base URL redirect, and NGINX](../Magesail/doc/TUNNEL_BASE_URL_REDIRECT.md) — end-to-end redirect and map behavior.
|
||||
- [README-NGINX-RELOAD.md](../Magesail/scripts/README-NGINX-RELOAD.md) — wrapper + sudoers patterns.
|
||||
@@ -0,0 +1,32 @@
|
||||
# Overview
|
||||
|
||||
MageSail exposes a local Magento instance (typically ports **80** or **443**) through a **Holesail** P2P tunnel. Admins start and stop the tunnel from **System → Holesail Tunnel**, optionally provisioning a dedicated **store view** and **NGINX `map`** entries so the tunneled hostname runs the correct store without manual multistore edits.
|
||||
|
||||
## Components
|
||||
|
||||
- **PHP (Magento module)** — Admin UI, config, cron, process management (`TunnelManager`, `TunnelStatus`), store provisioning (`TunnelStoreProvisioner`), NGINX map file updates (`NginxGlobalMapManager`, `NginxMapParser`), logging (`MagesailLog`).
|
||||
- **Node.js** — [`Magesail/scripts/start-server.js`](../Magesail/scripts/start-server.js) runs Holesail as a server; stdout goes to `var/log/magesail_tunnel.log`.
|
||||
|
||||
## High-level flow
|
||||
|
||||
1. Admin configures **Stores → Configuration → General → Holesail Tunnel** (secure mode, port, scripts path, auto-restart, NGINX paths).
|
||||
2. **Start Tunnel** submits tunnel base URL(s); the module provisions store `magesail_tunnel`, persists state under `var/`, may append lines to the configured **global map** file, then spawns Node.
|
||||
3. Incoming HTTP(S) requests can be bound to the tunnel store via **header**, **query**, **`___store`**, **hostname match** against persisted base URLs, or **NGINX `MAGE_RUN_*`** when the map is active.
|
||||
4. Plugins adjust **admin front name resolution**, **store base URLs** for links, and **skip redirect-to-base** for tunnel traffic so local/proxy URLs stay usable.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
admin[Admin_StartStop] --> node[Holesail_Node]
|
||||
admin --> provision[TunnelStoreProvisioner]
|
||||
provision --> state[var_magesail_state]
|
||||
admin --> nginx[NginxGlobalMapManager]
|
||||
request[HttpRequest] --> detector[TunnelRequestDetector]
|
||||
detector --> storePlugin[StoreFromMageSailHeaderPlugin]
|
||||
storePlugin --> magento[Magento_front_pipeline]
|
||||
```
|
||||
|
||||
## Related reading
|
||||
|
||||
- [Tunnel store and multistore](tunnel-store-and-multistore.md)
|
||||
- [Request routing and plugins](request-routing-and-plugins.md)
|
||||
- [NGINX global map](nginx-global-map.md)
|
||||
@@ -0,0 +1,56 @@
|
||||
# PHP classes reference
|
||||
|
||||
Module namespace: **`MageSail\Magesail`**. Paths are relative to [`Magesail/`](../Magesail/).
|
||||
|
||||
## Controllers (`Controller/Adminhtml/`)
|
||||
|
||||
| Class | File | Responsibility |
|
||||
|-------|------|------------------|
|
||||
| `Tunnel\Index` | `Controller/Adminhtml/Tunnel/Index.php` | Tunnel page; start/stop with store provisioning and NGINX map updates; JSON/AJAX responses. |
|
||||
| `Tunnel\Status` | `Controller/Adminhtml/Tunnel/Status.php` | JSON status for UI polling. |
|
||||
| `Tunnel\Logtail` | `Controller/Adminhtml/Tunnel/Logtail.php` | JSON tail of tunnel log file. |
|
||||
| `Nginx\Map` | `Controller/Adminhtml/Nginx/Map.php` | NGINX Global Map UI actions: read, write, validate, reload, parse, save_blocks, diagnostics. |
|
||||
|
||||
## Blocks (`Block/Adminhtml/`)
|
||||
|
||||
| Class | File | Responsibility |
|
||||
|-------|------|------------------|
|
||||
| `Tunnel` | `Block/Adminhtml/Tunnel.php` | Tunnel dashboard data: status URLs, log path, tunnel store state, form key. |
|
||||
| `Nginx\Map` | `Block/Adminhtml/Nginx/Map.php` | NGINX map page block data. |
|
||||
|
||||
## Models (`Model/`)
|
||||
|
||||
| Class | File | Responsibility |
|
||||
|-------|------|------------------|
|
||||
| `TunnelManager` | `Model/TunnelManager.php` | Start/stop Node Holesail process; script path resolution; shell invocation. |
|
||||
| `TunnelStatus` | `Model/TunnelStatus.php` | PID/key/log paths; process alive checks; cleanup helpers. |
|
||||
| `TunnelStoreProvisioner` | `Model/TunnelStoreProvisioner.php` | Create/delete tunnel store view; scoped base URLs; orchestrates map remove on teardown. |
|
||||
| `TunnelStoreState` | `Model/TunnelStoreState.php` | Read/write `var/magesail_tunnel_store.json`. |
|
||||
| `TunnelRequestDetector` | `Model/TunnelRequestDetector.php` | Resolve tunnel store code from request (query, header, URI, hostname). |
|
||||
| `TunnelHostnameMatcher` | `Model/TunnelHostnameMatcher.php` | Hostname match against persisted tunnel base URLs. |
|
||||
| `AdminPathDetector` | `Model/AdminPathDetector.php` | Detect admin area paths / configured admin front name. |
|
||||
| `NginxGlobalMapManager` | `Model/NginxGlobalMapManager.php` | Read/write global map file; insert/remove tunnel lines; validate and reload nginx. |
|
||||
| `NginxMapParser` | `Model/NginxMapParser.php` | Parse and manipulate map blocks in the file content. |
|
||||
| `MagesailLog` | `Model/MagesailLog.php` | Persist short messages to `magesail_logs` table. |
|
||||
|
||||
## Cron (`Cron/`)
|
||||
|
||||
| Class | File | Responsibility |
|
||||
|-------|------|------------------|
|
||||
| `DailyMonitor` | `Cron/DailyMonitor.php` | Daily health check, stale cleanup, optional auto-restart. |
|
||||
|
||||
## Plugins (`Plugin/`)
|
||||
|
||||
See [request-routing-and-plugins.md](request-routing-and-plugins.md) for behavior; files live under `Plugin/App/Request/`, `Plugin/Backend/App/Area/`, `Plugin/Store/`, `Plugin/FrontController/`.
|
||||
|
||||
## Setup
|
||||
|
||||
| Class | File | Responsibility |
|
||||
|-------|------|------------------|
|
||||
| `InstallSchema` | `Setup/InstallSchema.php` | Creates `magesail_logs` table. |
|
||||
|
||||
## Scripts shipped as PHP (not autoloaded as module code)
|
||||
|
||||
| File | Responsibility |
|
||||
|------|------------------|
|
||||
| [`Magesail/scripts/nginx-reload-probe.php`](../Magesail/scripts/nginx-reload-probe.php) | CLI probe for nginx test/reload as the PHP user. |
|
||||
@@ -0,0 +1,50 @@
|
||||
# Request routing and plugins
|
||||
|
||||
Plugins are registered in [`Magesail/etc/di.xml`](../Magesail/etc/di.xml) (global) and [`Magesail/etc/frontend/di.xml`](../Magesail/etc/frontend/di.xml) (frontend area only).
|
||||
|
||||
## Tunnel detection
|
||||
|
||||
[`TunnelRequestDetector`](../Magesail/Model/TunnelRequestDetector.php) resolves an effective tunnel store code from, in order:
|
||||
|
||||
1. Query parameter **`magesail_store`**
|
||||
2. Header **`X-MageSail-Store-Code`** (also `HTTP_X_MAGESAIL_SERVER` path via server var)
|
||||
3. Parsing **`magesail_store`** from the request URI query string if needed
|
||||
4. [`TunnelHostnameMatcher`](../Magesail/Model/TunnelHostnameMatcher.php) — compares `HTTP_HOST` to persisted tunnel base URL hosts from `var/magesail_tunnel_store.json`
|
||||
|
||||
Native Magento **`___store=magesail_tunnel`** continues to work where Magento already honors it.
|
||||
|
||||
## Global `di.xml` plugins
|
||||
|
||||
| Target | Plugin class | Role |
|
||||
|--------|----------------|------|
|
||||
| `Magento\Framework\App\Request\Http` | [`AdminFrontNameFromPathPlugin`](../Magesail/Plugin/App/Request/AdminFrontNameFromPathPlugin.php) | When the store code appears as the first path segment (e.g. `/magesail_tunnel/admin_xxx/...`), `getFrontName()` would mis-detect the area; scan path segments for the configured admin front name. |
|
||||
| `Magento\Framework\App\Request\Http` | [`StoreFromMageSailHeaderPlugin`](../Magesail/Plugin/App/Request/StoreFromMageSailHeaderPlugin.php) | For **non-admin** paths, if a tunnel store code is detected, `getServerValue` returns it for `MAGE_RUN_CODE` and `store` for `MAGE_RUN_TYPE`. On **admin** paths, forces website scope and empty run code so admin does not stay stuck on the tunnel store. |
|
||||
| `Magento\Backend\App\Area\FrontNameResolver` | [`TunnelBackendFrontNameResolverPlugin`](../Magesail/Plugin/Backend/App/Area/TunnelBackendFrontNameResolverPlugin.php) | When host-based backend detection would fail (tunnel host vs production backend URL), allow adminhtml resolution if tunnel detection says we are on a tunnel (header/query or hostname match). |
|
||||
| `Magento\Store\Model\Store` | [`TunnelStoreBaseUrlPlugin`](../Magesail/Plugin/Store/TunnelStoreBaseUrlPlugin.php) | For link/direct/web base URL types, rewrite scheme/host to match the tunneled request so generated URLs stay on the tunnel host (without breaking static/media URL types). |
|
||||
|
||||
## Frontend `di.xml` plugins
|
||||
|
||||
| Target | Plugin class | Role |
|
||||
|--------|----------------|------|
|
||||
| `Magento\Framework\App\FrontController` | [`EnsureTunnelParamPlugin`](../Magesail/Plugin/FrontController/EnsureTunnelParamPlugin.php) | Runs **before** the Store RequestPreprocessor (`sortOrder` 10 vs 50): copies tunnel indicators from superglobals into the request so later plugins see `magesail_store` even if the Request object was built early. |
|
||||
| `Magento\Store\App\FrontController\Plugin\RequestPreprocessor` | [`SkipBaseUrlRedirectForTunnelPlugin`](../Magesail/Plugin/Store/SkipBaseUrlRedirectForTunnelPlugin.php) | Short-circuits the redirect-to-base pipeline when tunnel traffic is detected (e.g. `127.0.0.1:port` vs store base URL). |
|
||||
| `Magento\Store\Model\BaseUrlChecker` | [`BaseUrlCheckerTunnelPlugin`](../Magesail/Plugin/Store/BaseUrlCheckerTunnelPlugin.php) | Disables or satisfies base URL checks for tunnel requests so the preprocessor does not emit a 301/302 to the configured base URL. |
|
||||
|
||||
## Mental model
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph detect [Detection]
|
||||
Q[magesail_store_query]
|
||||
H[X-MageSail-Store-Code_header]
|
||||
HOST[HTTP_HOST_vs_state]
|
||||
end
|
||||
detect --> TRD[TunnelRequestDetector]
|
||||
TRD --> SF[StoreFromMageSailHeaderPlugin]
|
||||
TRD --> TBU[TunnelStoreBaseUrlPlugin]
|
||||
TRD --> SK[SkipBaseUrlRedirectForTunnelPlugin]
|
||||
TRD --> BUC[BaseUrlCheckerTunnelPlugin]
|
||||
TRD --> BF[TunnelBackendFrontNameResolverPlugin]
|
||||
```
|
||||
|
||||
For Magento core behavior that triggers base-URL redirects, see [Magesail/doc/TUNNEL_BASE_URL_REDIRECT.md](../Magesail/doc/TUNNEL_BASE_URL_REDIRECT.md).
|
||||
@@ -0,0 +1,29 @@
|
||||
# Scripts
|
||||
|
||||
## Node: Holesail server
|
||||
|
||||
| File | Role |
|
||||
|------|------|
|
||||
| [`Magesail/scripts/start-server.js`](../Magesail/scripts/start-server.js) | Main entry: starts Holesail in server mode; writes key file; logs readiness. |
|
||||
| [`Magesail/scripts/package.json`](../Magesail/scripts/package.json) | Declares `holesail` dependency range. |
|
||||
| [`Magesail/scripts/package-lock.json`](../Magesail/scripts/package-lock.json) | Locked dependency tree. |
|
||||
|
||||
Run `npm install` in `scripts/` after clone or deploy. **`node_modules/`** is normally **not** committed (large tree); CI or admins install on the server.
|
||||
|
||||
## Optional Node utilities
|
||||
|
||||
| File | Role |
|
||||
|------|------|
|
||||
| [`Magesail/scripts/test-proxy-redirect.js`](../Magesail/scripts/test-proxy-redirect.js) | Development/testing helper (proxy/redirect experiments). |
|
||||
| [`Magesail/scripts/start-server.js`](../Magesail/scripts/start-server.js) | (Primary — listed above.) |
|
||||
|
||||
## Shell / PHP helpers
|
||||
|
||||
| File | Role |
|
||||
|------|------|
|
||||
| [`Magesail/scripts/nginx-reload-probe.php`](../Magesail/scripts/nginx-reload-probe.php) | Diagnose `nginx -t` and reload as the PHP-FPM user; see [README-NGINX-RELOAD.md](../Magesail/scripts/README-NGINX-RELOAD.md). |
|
||||
| [`Magesail/scripts/magesail-nginx-reload.sh.example`](../Magesail/scripts/magesail-nginx-reload.sh.example) | Example wrapper for safe reload via sudoers. |
|
||||
|
||||
## Documentation in-tree
|
||||
|
||||
- [README-NGINX-RELOAD.md](../Magesail/scripts/README-NGINX-RELOAD.md)
|
||||
@@ -0,0 +1,57 @@
|
||||
# Troubleshooting
|
||||
|
||||
## Tunnel will not start
|
||||
|
||||
| Symptom | Likely cause | What to try |
|
||||
|---------|----------------|-------------|
|
||||
| **Command failed** / Node error | `node` missing or not on PATH for PHP user | Install Node 18+; confirm `sudo -u www-data which node`. |
|
||||
| | `npm install` not run in `scripts/` | Run `npm install` in the configured **Scripts directory**. |
|
||||
| **Invalid port** | Config not 80/443 | Set **Port** to 80 or 443 under Holesail Tunnel settings. |
|
||||
| **Tunnel base URL is required** | Empty unsecure URL on start | Fill **Tunnel base URL (unsecure)** to match your browser/proxy host. |
|
||||
|
||||
## PID / process
|
||||
|
||||
| Symptom | Likely cause | What to try |
|
||||
|---------|----------------|-------------|
|
||||
| Stale **magesail.pid** | Crash without cleanup | Delete `var/magesail.pid` (and key if present); start again. Daily cron also cleans stale state. |
|
||||
| Multiple Node processes | Repeated starts | `ps aux \| grep start-server`; stop extras; use Admin **Stop Tunnel**. |
|
||||
|
||||
## Admin / storefront on tunnel
|
||||
|
||||
| Symptom | Likely cause | What to try |
|
||||
|---------|----------------|-------------|
|
||||
| Admin **404** on tunnel host | Backend host validation | Ensure tunnel detection fires: header `X-MageSail-Store-Code`, query `magesail_store`, or hostname matches provisioned base URL. See [request-routing-and-plugins.md](request-routing-and-plugins.md). |
|
||||
| **301** to production base URL | Redirect-to-base | Confirm tunnel plugins active (module enabled, `setup:di:compile`, cache flush). For NGINX stacks, confirm map lines exist and nginx was reloaded. |
|
||||
| Wrong store | Map / header mismatch | Align **MAGE_RUN_CODE** with `magesail_tunnel` for the tunneled host; or pass `___store=magesail_tunnel`. |
|
||||
|
||||
## NGINX map and reload
|
||||
|
||||
| Symptom | Likely cause | What to try |
|
||||
|---------|----------------|-------------|
|
||||
| Map not updating | Path wrong or not writable | Verify **Global map file path**; ensure PHP user can write the file. See [nginx-global-map.md](nginx-global-map.md) and [TUNNEL_BASE_URL_REDIRECT.md](../Magesail/doc/TUNNEL_BASE_URL_REDIRECT.md). |
|
||||
| **`nginx -t` OK, reload fails** | PHP user cannot signal master | Configure **Reload wrapper script** + sudoers; see [README-NGINX-RELOAD.md](../Magesail/scripts/README-NGINX-RELOAD.md). |
|
||||
| Map syntax error | Manual edit conflict | Use **NGINX Global Map** Admin actions or fix file on disk; run probe script as PHP user. |
|
||||
|
||||
## AJAX / UI
|
||||
|
||||
| Symptom | Likely cause | What to try |
|
||||
|---------|----------------|-------------|
|
||||
| Key never appears | `magesail/tunnel/status` blocked | Browser console / network tab; check Admin ACL and form key. |
|
||||
|
||||
## Holesail client
|
||||
|
||||
| Symptom | Likely cause | What to try |
|
||||
|---------|----------------|-------------|
|
||||
| Cannot connect (private mode) | Wrong or missing seed/key | Use the exact key material Holesail expects for private mode. |
|
||||
| Public mode too open | Expected | Use Magento auth; do not rely on tunnel for authorization. |
|
||||
|
||||
## Module recovery
|
||||
|
||||
```bash
|
||||
php bin/magento module:status MageSail_Magesail
|
||||
php bin/magento cache:flush
|
||||
php bin/magento setup:upgrade
|
||||
php bin/magento setup:di:compile
|
||||
```
|
||||
|
||||
If disabling: `php bin/magento module:disable MageSail_Magesail` then `setup:upgrade` (stops using plugins; does not remove DB table by itself).
|
||||
@@ -0,0 +1,41 @@
|
||||
# Tunnel store and multistore
|
||||
|
||||
## Store view code
|
||||
|
||||
MageSail provisions a dedicated store view with code **`magesail_tunnel`** (constant `TunnelStoreProvisioner::STORE_CODE` in [`TunnelStoreProvisioner.php`](../Magesail/Model/TunnelStoreProvisioner.php)).
|
||||
|
||||
It is created on the **default website**’s **default store group** when you **Start Tunnel** with valid base URLs.
|
||||
|
||||
## Base URLs
|
||||
|
||||
You must supply at least **Tunnel base URL (unsecure)** in Admin. It should match the hostname users see in the browser when using holesail-browser (or your proxy), including scheme (`http` vs `https`).
|
||||
|
||||
Optional **Tunnel base URL (secure)** and **Use secure URLs on storefront and in admin** drive scoped configuration:
|
||||
|
||||
- `web/unsecure/base_url`
|
||||
- `web/secure/base_url`
|
||||
- Optionally `web/secure/use_in_frontend` and `web/secure/use_in_adminhtml`
|
||||
|
||||
## Persisted state: `var/magesail_tunnel_store.json`
|
||||
|
||||
[`TunnelStoreState`](../Magesail/Model/TunnelStoreState.php) writes JSON containing `store_id`, `store_code`, base URLs, `use_secure_urls`, and optionally `nginx_pending_reload`. The Admin tunnel page prefills the URL fields from this file when the tunnel is stopped.
|
||||
|
||||
## Teardown
|
||||
|
||||
**Stop Tunnel** (or provisioner teardown paths) will:
|
||||
|
||||
- Remove MageSail lines from the NGINX global map when configured.
|
||||
- Run validation / reload (same constraints as start — see [nginx-global-map.md](nginx-global-map.md)).
|
||||
- Delete the store view **unless** it is the **website default** store (Magento would be left without a default); in that case the module logs a warning and skips delete.
|
||||
|
||||
If the Node process dies and **auto-restart** is **No**, stale PID cleanup can trigger teardown of the store and state (see [`TunnelStatus`](../Magesail/Model/TunnelStatus.php) / [`DailyMonitor`](../Magesail/Cron/DailyMonitor.php) flow). If **auto-restart** is **Yes**, state is kept so cron can restart the process without re-entering URLs.
|
||||
|
||||
## Aligning proxy, NGINX, and Magento
|
||||
|
||||
For PHP-FPM to receive `MAGE_RUN_CODE` / `MAGE_RUN_TYPE` for the tunneled host, the **global map** must include the tunnel hostname (MageSail can insert those lines on start). See [nginx-global-map.md](nginx-global-map.md).
|
||||
|
||||
For requests that **do not** go through that map (e.g. some local proxies), you can still select the tunnel store using headers or query parameters — see [request-routing-and-plugins.md](request-routing-and-plugins.md).
|
||||
|
||||
## Deep dive
|
||||
|
||||
The module’s long-form write-up of redirect behavior and map interaction lives in [Magesail/doc/TUNNEL_BASE_URL_REDIRECT.md](../Magesail/doc/TUNNEL_BASE_URL_REDIRECT.md).
|
||||
Reference in New Issue
Block a user