Runway 1.0.1
This commit is contained in:
1 parent
dcf819146b
commit
ce217fc952
259 files changed
+22226
-206
No files matched your search
@@ -0,0 +1,10 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [2.1.0] — 2026-10-21
|
||||
|
||||
First public release of `contact`: an embeddable contact-form widget whose submissions are both emailed over the
|
||||
site's own SMTP relay and stored as site data for the console, with CAPTCHA (when the site has one) and a
|
||||
honeypot against spam. Requires SPI `1.0.0` (Runway `1.0.0` or later). Licensed under the GNU AGPL v3.0 with an additional permission for
|
||||
plugins (`LICENSE`, `LICENSE-EXCEPTION`).
|
||||
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are 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.
|
||||
|
||||
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.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
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 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 work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
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 AGPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
@@ -0,0 +1,44 @@
|
||||
Runway — additional permission for plugins
|
||||
(an additional permission under section 7 of the GNU Affero General Public License, version 3)
|
||||
|
||||
Copyright (C) 2026 Quest ICT SAS de CV
|
||||
|
||||
Runway is free software: you can redistribute it and/or modify it under the terms of the
|
||||
GNU Affero General Public License as published by the Free Software Foundation, version 3
|
||||
(the file LICENSE), with the additional permission below. Runway 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 Affero General Public
|
||||
License for more details.
|
||||
|
||||
1. Definitions
|
||||
|
||||
"Runway" means the Runway kernel and every Runway plugin whose source carries this file.
|
||||
|
||||
"Published SPI" means the public classes and interfaces of the runway-spi artifact
|
||||
(the package mx.quest.runway.spi and its subpackages), together with the public classes
|
||||
and interfaces of any package named "spi" that a part of Runway publishes for other
|
||||
plugins to use (for example mx.quest.search.spi).
|
||||
|
||||
"Plugin" means an independent module that Runway loads as a plugin, that interacts with
|
||||
Runway only through the Published SPI, and that is not based on any part of Runway other
|
||||
than the Published SPI.
|
||||
|
||||
2. Permission
|
||||
|
||||
As an additional permission, the copyright holder gives you permission to combine Runway
|
||||
with Plugins, and to convey and run the resulting combination, without the terms of the
|
||||
GNU Affero General Public License applying to those Plugins. You may license, convey and
|
||||
run your Plugins under terms of your choice, provided that you continue to meet the terms
|
||||
of the GNU Affero General Public License for Runway itself, including offering the
|
||||
Corresponding Source of Runway, and of any modification you make to it, as that license
|
||||
requires.
|
||||
|
||||
3. Testing
|
||||
|
||||
Compiling a Plugin's tests against the runway-spi-testkit artifact, and running them, does
|
||||
not by itself make the Plugin subject to the GNU Affero General Public License.
|
||||
|
||||
4. Modified versions
|
||||
|
||||
If you modify Runway, you may extend this additional permission to your version, but you
|
||||
are not obliged to do so. If you do not wish to, delete this file from your version.
|
||||
@@ -0,0 +1,63 @@
|
||||
# Runway Contact plugin
|
||||
|
||||
A **contact form** for [Runway](../README.md): an embeddable form content widget that **POSTs** to an anonymous
|
||||
`/contact/submit` route, which **both emails** each submission over the site's own SMTP relay **and stores** it as
|
||||
tenant-owned data (read in the console) — belt-and-suspenders, so a message is never lost even if SMTP is down.
|
||||
CAPTCHA (when the site has one) and honeypot anti-spam.
|
||||
|
||||
- **Plugin id:** `contact` — install folder `external/plugins/contact/` · **version 2.1.0**
|
||||
- **Java package:** `mx.quest.contact` · **SPIs:** `ContentWidget` (`contact`) + `EndpointContributor`
|
||||
(`POST /contact/submit` anonymous; `POST /contact/install-page` and `POST /contact/smtp-test`, CSRF-checked)
|
||||
- **Links only the Runway SPI** (`requiresSpi: ">=1.0.0"`): `PluginSettings` (settings + the SMTP password secret),
|
||||
`PluginSiteFiles` (submissions), `Messages`, `AccessCheck`, `SitePages` (the starter page), `CaptchaService`.
|
||||
**Needs Runway 1.0.0 or later** (SPI `1.0.0`) — a kernel with an older SPI blocks this release at startup with
|
||||
a reason. See [`CHANGELOG.md`](CHANGELOG.md).
|
||||
- **No plugin dependency:** Jakarta Mail is part of the **core** Runway application (the kernel bundles it for
|
||||
its own platform mailer), so `contact` compiles it as `provided` and resolves the kernel's copy at runtime.
|
||||
|
||||
## Use it
|
||||
|
||||
1. Install `contact`, then restart the host.
|
||||
2. Enable the plugin, set your thank-you message, and fill in the **SMTP relay** (host, port, auth,
|
||||
username/password, STARTTLS/SSL, from/to) on the Contact settings page — the password is stored encrypted.
|
||||
3. Verify the relay with **Send a test email** on the settings page (operator-only).
|
||||
4. Put a form on a page: install the ready-made **Contact page** from the settings (it follows the site's
|
||||
publishing rules and says what happened), or add `<div id="contact" data-widget="contact/form"></div>` to any
|
||||
page.
|
||||
5. Read submissions on the Contact settings page (newest first) — a copy is kept even when email delivery fails.
|
||||
|
||||
> A site with a **blank** SMTP host/recipient simply stores messages (no email) — email is optional. A site sends
|
||||
> with its **own** relay only (tenant isolation).
|
||||
|
||||
> **Privacy.** The form POSTs, so a visitor's fields never appear in a URL, browser history or proxy log. The
|
||||
> stored submissions are declared **personal data** (`siteData.personal: [submissions.tsv]`): a site's **transfer
|
||||
> copy** leaves them out (and lists the omission in its manifest); a **full backup** keeps them. See
|
||||
> [`docs/CONTACT-PLUGIN.md`](docs/CONTACT-PLUGIN.md).
|
||||
|
||||
## Build and verify
|
||||
|
||||
```bash
|
||||
export JAVA_HOME=/path/to/jdk-25
|
||||
mvn verify # 75 tests (send seam mocked — no socket)
|
||||
mvn -DskipTests package # jar + target/contact/ + the .zip
|
||||
HOST_JAR=/path/to/runway-app-<ver>-exec.jar VERIFY_TMPDIR=/somewhere scripts/verify-against-host.sh
|
||||
```
|
||||
|
||||
The first build downloads its Maven dependencies, and needs the `runway-spi` jars installed in `~/.m2` as the
|
||||
[authoring guide §2](../docs/PLUGIN-AUTHORING-GUIDE.md#2-prerequisites) describes.
|
||||
|
||||
The verify boots the **packaged** host with this plugin (and, when built, the protection plugin from the host
|
||||
checkout), on four sites (Advisory, Enforced, Reviewed, and one with a CAPTCHA), and checks 59 things (54 without
|
||||
the protection plugin): zero
|
||||
host-linkage and surface warnings; an anonymous POST with no session stored and answered `303` with only an
|
||||
outcome flag; GET, honeypot, invalid, query-string and multipart submissions refused; the two operator actions
|
||||
CSRF-checked (a GET changes nothing, a POST without the console token is `403`); the starter page installed
|
||||
on every editorial level and never twice; the SMTP password stored `ENC(...)` and handed in clear to a local fake
|
||||
relay; a full backup with the submissions and a transfer copy without them; a POST without the CAPTCHA token
|
||||
refused.
|
||||
|
||||
## License
|
||||
|
||||
GNU Affero General Public License v3.0 with an additional permission for plugins (`LICENSE`, `LICENSE-EXCEPTION`),
|
||||
copyright Quest ICT SAS de CV. The permission means that a plugin which uses only the published SPI may carry any
|
||||
license.
|
||||
@@ -0,0 +1,256 @@
|
||||
# Runway Contact plugin — design & reference
|
||||
|
||||
> The reference for a plugin that **accepts input from anonymous visitors**, **stores per-tenant
|
||||
> personal data**, and **sends email** within the kernel's constraints (CSRF, servlet-free endpoints, tenant
|
||||
> isolation, encrypted secrets) — using **only the Runway SPI** (version 2.1.0, SPI 1.0.0). Grounded in the Runway
|
||||
> kernel as built.
|
||||
|
||||
## 1. What it does
|
||||
|
||||
- **Form widget** — a `ContentWidget` (`key = "contact"`) that renders the shared `ContactForm` inline wherever a
|
||||
page carries `<div id="…" data-widget="contact/…"></div>`. Honors the per-tenant `enabled` flag. The plugin owns
|
||||
**no visible page**: the form lives on a normal, editable site page. The widget is **query-aware** — the submit
|
||||
handler redirects back with `?contact=sent|invalid|captcha|queued`, and the widget re-renders that outcome
|
||||
(thank-you, or the form with an error) from the flag, so the page it sits on stays an ordinary, cacheable page.
|
||||
- **`POST /contact/submit`** — an `EndpointContributor` route declared **anonymous** (`Route.anonymousPost`, §2)
|
||||
that reads the fields from the url-encoded **body only**, runs the honeypot + (when configured) the CAPTCHA
|
||||
check, and for a valid message **stores it AND emails it** over the site's own SMTP relay, then answers
|
||||
**`303 See Other` back to the page the form lives on** (the same-origin `return` field, else the `Referer`) with
|
||||
only the outcome flag. It renders nothing itself. Any other method on this path is a 404.
|
||||
- **`POST /contact/install-page`** — an ordinary (CSRF-checked, §2a) route, operator-gated (`contact|settings`,
|
||||
checked with `AccessCheck`; fails **closed** with a 404 otherwise): installs a ready-made, editable tenant page carrying the form widget (slug
|
||||
`contact`, path `/contact`) through **`SitePages.install`**. The kernel never overwrites and follows the site's
|
||||
editorial level; the plain-text answer names the outcome (§1c). Once installed it is an ordinary site page
|
||||
(listed under Pages; restyle / move / rename it), so the operator, not the plugin, owns the URL and chrome.
|
||||
- **`POST /contact/smtp-test`** — an operator-only diagnostic (same CSRF check and gate) that sends a test message
|
||||
over the site's relay to verify the SMTP configuration — to the configured recipient, or to an optional `to` field
|
||||
of the form body (never the query string).
|
||||
- **Console** — a dashboard card (submission count) and an admin fragment with a **"Contact page"** card (install
|
||||
the ready-made page with a button, or see its live path when already installed — read fresh with
|
||||
`SitePages.pathOf`, so it follows a move and counts a draft or a page in review), the **SMTP readiness**
|
||||
("Configured / Not configured" badge + a "Send a test email" button) and a list of
|
||||
**recent submissions** (name, email, message excerpt, time), gated by the `settings` control point.
|
||||
|
||||
## 1a. Belt-and-suspenders: store AND send
|
||||
|
||||
A valid submission is **always stored first** (`ContactStore`, tenant TSV), **then** emailed (`ContactMailer`).
|
||||
The store is unconditional, so a message is **never lost** even if SMTP is down:
|
||||
|
||||
- **Send OK** → stored + emailed; the visitor sees the thank-you.
|
||||
- **Send FAILED** (a configured relay rejected/unreachable) → stored; the failure is logged and the visitor is
|
||||
redirected with `?contact=queued`, which the widget renders as the thank-you plus an unobtrusive "message
|
||||
received; email delivery is delayed" note. The relay internals
|
||||
are never exposed to the visitor.
|
||||
- **NOT_CONFIGURED** (blank host/recipient) → stored silently, no note — a site may legitimately choose to only
|
||||
store messages and read them in the console.
|
||||
- **PROVIDER_MISSING** (Jakarta Mail off the classloader) → stored; reported. The kernel bundles Jakarta Mail as
|
||||
a core capability, so this is effectively unreachable, but `ContactMailer` still guards the `LinkageError` at
|
||||
the send seam so the request can never crash.
|
||||
|
||||
## 1b. Email over the kernel's Jakarta Mail
|
||||
|
||||
The plugin compiles `jakarta.mail-api` as **`provided`** — the **kernel** bundles the Jakarta Mail + Angus stack
|
||||
as a core capability (for its own platform mailer), and the plugin classloader reaches it parent-first. This
|
||||
plugin **never bundles Jakarta Mail itself** (that would be a second, shadowing copy on the classloader). It
|
||||
therefore needs **no `requires:`** gate.
|
||||
|
||||
- The send seam is the `MailTransport` interface (`JakartaMailTransport` delegates to `jakarta.mail.Transport` in
|
||||
production; mocked in tests so no socket is opened).
|
||||
- `ContactMailer.build(...)` constructs a `MimeMessage` from `SmtpSettings`: From = the site's `fromAddress` (or
|
||||
the recipient when blank), To = the site's `toAddress`, Reply-To = the visitor's email (so a reply reaches
|
||||
them), a site-prefixed Subject, and a plain-text body. The `Session` always uses the `smtp` protocol
|
||||
(implicit TLS rides `mail.smtp.ssl.enable`, STARTTLS `mail.smtp.starttls.enable`) and a static `Authenticator`
|
||||
when `smtpAuth` is on.
|
||||
|
||||
### Per-site SMTP settings (tenant-owned, isolated)
|
||||
|
||||
All relay config is per-tenant `siteSettings` over `sites/<id>/plugins/contact.yml`, so **a site sends with its
|
||||
OWN relay only** — never another tenant's:
|
||||
|
||||
| key | type | notes |
|
||||
|---|---|---|
|
||||
| `smtpHost` | string | blank ⇒ not configured ⇒ mail skipped (stored only) |
|
||||
| `smtpPort` | int (1..65535, default 25) | |
|
||||
| `smtpAuth` | boolean (default false) | when on, uses username/password |
|
||||
| `smtpUsername` | string | |
|
||||
| `smtpPassword` | **secret** | stored `ENC(...)`-encrypted; the config file is `chmod 600`; **bound** to `smtpHost`, `smtpPort`, `smtpUsername`, `smtpStarttls`, `smtpSsl` (below) |
|
||||
| `smtpStarttls` | boolean (default false) | STARTTLS upgrade on a plain connection |
|
||||
| `smtpSsl` | boolean (default false) | implicit-TLS (SMTPS) |
|
||||
| `fromAddress` | string | envelope From; blank ⇒ falls back to the recipient |
|
||||
| `toAddress` | string | recipient; blank ⇒ not configured ⇒ mail skipped |
|
||||
|
||||
Every value is read from the `SettingsView` that `PluginSettings.site(siteId)` returns (the descriptor defaults
|
||||
overlaid by what the operator saved). The **secret** password is stored `ENC(...)` by the platform; the plugin
|
||||
reads it in clear with **`PluginSettings.secret(siteId, "smtpPassword")`** at send time — the kernel decrypts it
|
||||
(a hand-written plaintext value is returned as is) and answers empty when it is unset or cannot be decrypted (the
|
||||
relay then rejects the login and the submission is reported "delivery delayed", still stored). The password is
|
||||
never taken from the settings view (the kernel leaves secret keys out of it, and a test holds the plugin to that).
|
||||
The plaintext lives only in the transient `SmtpSettings` value handed to Jakarta Mail — never logged
|
||||
(`SmtpSettings.toString()` masks it) and never stored by this plugin.
|
||||
|
||||
**The password is bound to the relay login (`secretBoundTo`).** The descriptor declares
|
||||
`secretBoundTo: [smtpHost, smtpPort, smtpUsername, smtpStarttls, smtpSsl]` on `smtpPassword` (the TLS switches
|
||||
too: turning TLS off toward the same host would otherwise send the stored password in clear). A settings save that
|
||||
changes any of those five **without retyping the password** makes the kernel drop the stored password (the field is left blank, so the
|
||||
next send fails the login and the submission is stored as "delivery delayed" until the password is entered again).
|
||||
Why: the settings form never shows the stored password, but whoever may edit the settings could otherwise point the
|
||||
site's saved credentials at a server of their own — change the host, keep the password, press **Send a test
|
||||
email** — and read the password off the wire. Binding it means a stored password is only ever offered to the relay
|
||||
login it was typed for. Retyping the password in the same save keeps it (the new value is stored). Changing any
|
||||
other setting (`enabled`, the thank-you message, sender, recipient, `smtpAuth`) leaves it alone. The binding is
|
||||
enforced by the kernel, which also tells the operator on the settings page when a save dropped the password.
|
||||
|
||||
## 1c. The starter page and the site's editorial level
|
||||
|
||||
`SitePages.install` creates the page as a draft and then applies the site's level; the endpoint reports each
|
||||
`InstallResult` outcome in the operator's console language (`Messages.console`):
|
||||
|
||||
| Outcome | When | The answer (EN) |
|
||||
|---|---|---|
|
||||
| `PUBLISHED` | Advisory; Enforced or Reviewed with the checks passing (on Reviewed, for someone who may approve pages) | `Contact page installed at /contact` |
|
||||
| `PENDING_REVIEW` | Reviewed, and the operator may not approve pages | `The contact page was created and is waiting in the review queue: /contact` |
|
||||
| `DRAFT_BLOCKED` | the quality checks blocked publishing | `The contact page was created as a draft because the quality checks blocked publishing; fix it in the page editor: /contact` + one `- code: message` line per blocking finding |
|
||||
| `ALREADY_EXISTS` | a page with the slug `contact` exists, in any state | `A contact page already exists at <its current path>` |
|
||||
| a constant added in a later SPI | — | `The contact page install finished: <OUTCOME> <path>` |
|
||||
|
||||
A refused install (another page serves `/contact`, a write failure) answers `500` "Could not install the contact
|
||||
page." and leaves no draft behind (the kernel removes it).
|
||||
|
||||
## 2. POST on an anonymous route (the CSRF constraint, solved)
|
||||
|
||||
A public form on a cacheable page cannot carry the tenant chain's **session-based CSRF token**. The easy way
|
||||
around that — a form that submits by **GET** — would put a visitor's name, email and message in their browser
|
||||
history, in `Referer` headers and in proxy logs. The SPI has a contract for exactly this case, and the plugin uses
|
||||
it:
|
||||
|
||||
- The endpoint declares **`Route.anonymousPost("/contact/submit", posture)`**. The kernel exempts **exactly that
|
||||
method and path** from CSRF, on a site's host only, and in exchange takes away what a forged cross-site
|
||||
submission could use: the handler runs with **no principal** (`AccessCheck.may` is `false` even for a signed-in
|
||||
administrator), it is handed only `application/x-www-form-urlencoded` bodies (anything else is answered `415`),
|
||||
and every other route keeps its CSRF check.
|
||||
- The form (`ContactForm`) is `method="post"` with that encoding. The handler reads the fields **from the body
|
||||
only** (`RouteRequest.form()`), so a field put in a query string is ignored and personal data has no reason to
|
||||
travel in a URL; the `303` back to the page carries only `?contact=<outcome>`.
|
||||
- **The abuse guards stay in front of the store:** a hidden **honeypot** field (`website`; a submission that fills
|
||||
it is silently dropped — the bot sees a fake success, nothing is stored or sent), the site's **CAPTCHA** when one
|
||||
is configured (`CaptchaService.verify(site, token, req.clientIp())` — the client IP after the kernel's
|
||||
trusted-proxy gate; the token is read from the body too), and the platform's **per-address rate limit** (the
|
||||
protection plugin's edge guard, which sees every request before any endpoint).
|
||||
|
||||
## 2a. The operator actions are CSRF-checked POSTs
|
||||
|
||||
Installing the starter page creates a page, and the SMTP test sends an email. Were they `GET` links, a signed-in
|
||||
site manager who followed a link on another web site — or merely loaded a page with an
|
||||
`<img src="https://their-site/contact/install-page">` — would perform the action without meaning to (the browser
|
||||
sends the session cookie with the request; the permission check passes because it *is* the manager). The SMTP test
|
||||
would be worse: a `?to=` choosing the recipient would let such a link make the server email an arbitrary address.
|
||||
|
||||
Both are therefore **ordinary `POST` routes** — deliberately **not** `Route.anonymousPost`, which would switch the
|
||||
CSRF check off. The kernel's tenant chain demands the console session's CSRF token on them:
|
||||
|
||||
- the admin fragment renders each action as a `<form method="post">` with a hidden `_csrf` field bound to the
|
||||
request's token (`th:attr="name=${_csrf.parameterName},value=${_csrf.token}"`, the same pattern as the search
|
||||
plugin's "Clear list"); the answer opens in a new tab;
|
||||
- a `POST` without a valid token is refused `403` by the kernel (the "session expired" page) before the plugin runs;
|
||||
- a `GET` (a link, an `<img>`) matches no route, so the kernel answers `404` and nothing changes; the handler also
|
||||
refuses any non-`POST` method itself, as a second line;
|
||||
- the `contact|settings` permission check still runs after the token check (an anonymous visitor who holds a valid
|
||||
session token gets `404`).
|
||||
|
||||
**The body reaches the plugin whole.** The SMTP test's optional `to` override is read from the form body only,
|
||||
never the query string. The kernel keeps the url-encoded body for the route after its CSRF check, so `form()`
|
||||
carries every field whether the token travels as the `_csrf` form field — as a browser form sends it — or in the
|
||||
`X-CSRF-TOKEN` header. The console's SMTP-test button sends no `to`, so it always mails the configured recipient;
|
||||
the override is for a scripted call.
|
||||
|
||||
## 3. Storage (tenant-owned, backup-safe)
|
||||
|
||||
Submissions go through the kernel's **`PluginSiteFiles`** (this plugin's per-site folder, bound to the plugin by
|
||||
its jar; the kernel confines every path to `sites/<id>/plugins/contact/`, real path included) to
|
||||
`sites/<id>/plugins/contact/submissions.tsv` (an existing file is read and appended in place, so stored
|
||||
submissions survive an upgrade of the plugin):
|
||||
|
||||
- **Outside** the served `static/` tree — never publicly downloadable (the verify asserts a traversal attempt on
|
||||
it does not return 200).
|
||||
- **Inside** the tenant folder — so a **full backup** carries it automatically; no `BackupParticipant` needed.
|
||||
- **Declared personal data** in `plugin.yml` (`siteData: personal: [submissions.tsv]`): a **transfer copy** of the
|
||||
site (the console's "Download a transfer copy") leaves it out and lists `plugins/contact/submissions.tsv` under
|
||||
`omitted:` in the archive's `manifest.yml`. A restored transfer copy starts with no submissions, which the store
|
||||
reads as empty.
|
||||
- One **sanitized** TSV line per submission (`epochMillis \t name \t email \t message`; tabs/newlines stripped so
|
||||
the format is unambiguous, fields length-capped at 4,000 characters), bounded to the most recent
|
||||
`MAX_SUBMISSIONS` (500), which keeps the file far below the kernel's 16 MiB write cap. Each kernel write is
|
||||
atomic; the append (a read-modify-write) is serialized per site by the store. An append that cannot read the
|
||||
existing file fails rather than rewriting it from nothing; the console count and list then show nothing (logged).
|
||||
|
||||
Everywhere the plugin echoes a value (form re-render, thank-you, admin listing) it HTML-escapes it (`Html.escape`).
|
||||
|
||||
## 4. Inventory
|
||||
|
||||
| Piece | Type | File |
|
||||
|---|---|---|
|
||||
| `mainClass` `@Configuration` | `ContactConfig` | wires widget + endpoint + store + mailer + admin model from SPI services; every bean name starts with `contact` |
|
||||
| Form widget | `ContactWidget` (`ContentWidget` `contact`, query-aware) | inline form + outcome re-render |
|
||||
| Endpoint | `ContactEndpoint` (`EndpointContributor`: anonymous `POST /contact/submit`; CSRF-checked `POST /contact/install-page` and `POST /contact/smtp-test`) | submit+store+send+303, starter page via `SitePages`, gated test |
|
||||
| Shared form markup | `ContactForm` | the `<form>` the widget renders |
|
||||
| Storage | `ContactStore` + `ContactSubmission` | append/read tenant TSV |
|
||||
| Mail send | `ContactMailer` + `MailTransport`/`JakartaMailTransport` + `SmtpSettings` + `MailSendResult` | build MIME + send over the site relay |
|
||||
| Console model | `ContactAdminModel` (+ `SitePages.pathOf`) + `templates/` | contact-page install card + dashboard card + readiness + submissions table |
|
||||
| Front-end | `static/contact.css`, `static/contact-help.html` | self-contained |
|
||||
| i18n (EN/ES) | `i18n/` | form + console + SMTP labels/results |
|
||||
|
||||
## 5. What it links (SPI 1.0.0)
|
||||
|
||||
`pom.xml` depends on `runway-spi` only (`runway-spi-testkit` for tests); **`runway-app` is not a dependency in any
|
||||
scope**, so a host import does not compile, and `ContactConfigTest` scans the compiled classes' constant pools for
|
||||
any `mx.quest.runway` reference outside `mx.quest.runway.spi` — the kernel's own load-time scan finds nothing.
|
||||
|
||||
| Need | SPI service |
|
||||
|---|---|
|
||||
| the site's settings | `PluginSettings.site(site)` → `SettingsView` |
|
||||
| the SMTP password in clear, at send time | `PluginSettings.secret(site, "smtpPassword")` |
|
||||
| the stored submissions | `PluginSiteFiles` (`submissions.tsv`) |
|
||||
| visitor text / operator answers | `Messages.site` / `Messages.console` |
|
||||
| the operator gate | `AccessCheck` (the `authz` bean) |
|
||||
| the starter page | `SitePages.install` / `SitePages.pathOf` |
|
||||
| the site's CAPTCHA | `CaptchaService.verify(site, token, req.clientIp())` |
|
||||
| the submitted fields | `RouteRequest.form()` of an anonymous POST |
|
||||
|
||||
`requiresSpi: ">=1.0.0"`: a kernel with an older SPI blocks the plugin before wiring, with a reason.
|
||||
|
||||
## 6. Verify
|
||||
|
||||
`scripts/verify-against-host.sh` (honours `JAVA_HOME` (required), `MVN`, `HOST_TARGET`, `HOST_JAR`, `VERIFY_TMPDIR`,
|
||||
`VERIFY_LOG_DIR`, `PROTECTION_DIR`; never
|
||||
runs `mvn install`) boots the **packaged** host in ACTIVE mode with four sites — the wizard's default (Advisory)
|
||||
plus an Enforced, a Reviewed and a CAPTCHA site copied from it — and, when it is built, the protection plugin from
|
||||
the host checkout. It checks: the plugin loads with zero host-linkage and bean-name/surface warnings; an anonymous
|
||||
form POST with no session or token is stored and answered `303 ?contact=sent` with no submitted value in the
|
||||
`Location`; a GET submission is a 404, a honeypot fakes success, an invalid email, fields only in the query string
|
||||
and a multipart body are refused, and nothing of those is stored; the operator actions are CSRF-checked POSTs
|
||||
(a `GET` of either is a `404` and changes nothing even for the signed-in owner, a `POST` without or with a forged
|
||||
token is a `403` with no page created and no email sent, an anonymous `POST` holding a valid session token is a
|
||||
`404`, and the settings page renders both as `POST` forms carrying a non-empty token and links to neither); the
|
||||
starter page installs (`POST` with the settings page's token) on all three editorial levels and a second install
|
||||
changes nothing; the settings page shows the page's path and the count; the SMTP
|
||||
password saved through the settings form is stored `ENC(...)` and is offered in clear to a local fake relay (a
|
||||
small Python SMTP listener) for a submission and for the SMTP test (the console form to the configured
|
||||
recipient; a body `to` override with the token as a form field, as a browser form sends it, and again with it in
|
||||
the `X-CSRF-TOKEN` header; a `to` in the query string is ignored); a full backup carries `submissions.tsv` and a
|
||||
transfer copy does not, its manifest listing the omission; on the CAPTCHA site a POST without (or with a blank)
|
||||
token is answered `?contact=captcha` and nothing is stored; the static assets serve and the submissions are never
|
||||
served publicly.
|
||||
|
||||
Unit tests (75) cover the store over the testkit's `TempDirSiteFiles` (`ContactStoreTest`, incl. an existing file
|
||||
read in place and the unreadable-file rule), the widget rendering incl. the POST form, outcome flags + escaping
|
||||
(`ContactWidgetTest`), the endpoint incl. POST-only and body-only acceptance, the CAPTCHA with the gated client
|
||||
IP, store-then-send ordering, redirect outcomes, return-path safety, every install outcome, the gated SMTP test, POST-only operator actions (a GET installs and
|
||||
sends nothing even for a permitted operator; the SMTP recipient is read from the body only) (`ContactEndpointTest`),
|
||||
the admin fragment's POST forms carrying the CSRF token, no link to an action, unique ids
|
||||
(`ContactAdminTemplateTest`), the send path incl. the MIME build against a mock transport and the password taken only
|
||||
from the secret (`ContactMailerTest`), and the plugin's contract with the host (`ContactConfigTest`: wiring from
|
||||
SPI services, bean-name prefix, template bean references, the floor, version, personal-data and secret
|
||||
declarations, EN/ES key parity, the constant-pool scan).
|
||||
|
||||
> **Send tests open no socket.** The send seam (`MailTransport`) is mocked, so `ContactMailerTest` exercises the
|
||||
> full `MimeMessage` build and the store/send/report contract without touching the network.
|
||||
@@ -0,0 +1,69 @@
|
||||
# Runway Contact plugin — English strings. Console labels resolve automatically; public-facing strings
|
||||
# (contact.form.*, contact.success/error.*, contact.page.title) are looked up with Messages.site for the visitor's
|
||||
# locale, and the plain-text answers of the operator actions (contact.page.*, contact.test.*) with
|
||||
# Messages.console in the operator's console language.
|
||||
|
||||
# Grantable permission (permissions matrix label)
|
||||
contact.perm.settings=Configure contact form
|
||||
|
||||
# Per-tenant settings form labels
|
||||
contact.set.enabled=Enable contact form
|
||||
contact.set.success=Thank-you message
|
||||
contact.set.smtpHost=SMTP host
|
||||
contact.set.smtpPort=SMTP port
|
||||
contact.set.smtpAuth=SMTP authentication
|
||||
contact.set.smtpUsername=SMTP username
|
||||
contact.set.smtpPassword=SMTP password
|
||||
contact.set.smtpStarttls=Use STARTTLS
|
||||
contact.set.smtpSsl=Use SSL/TLS (SMTPS)
|
||||
contact.set.fromAddress=From address
|
||||
contact.set.toAddress=Send submissions to
|
||||
|
||||
# Dashboard card
|
||||
contact.card.title=Contact
|
||||
contact.card.submissions=submissions
|
||||
|
||||
# Admin status fragment
|
||||
contact.admin.title=Contact submissions
|
||||
contact.admin.empty=No submissions yet.
|
||||
contact.admin.when=When
|
||||
contact.admin.help=Contact help & reference
|
||||
contact.admin.smtp=SMTP relay
|
||||
contact.admin.smtp.ok=Configured
|
||||
contact.admin.smtp.missing=Not configured
|
||||
contact.admin.smtp.test=Send a test email
|
||||
contact.admin.smtp.test.tip=Send a test message over this site's SMTP relay to verify the configuration
|
||||
|
||||
# SMTP test result (public text response of /contact/smtp-test)
|
||||
contact.test.ok=Test message sent.
|
||||
contact.test.notConfigured=No SMTP relay is configured for this site.
|
||||
contact.test.providerMissing=Mail libraries are not available on the server, so email cannot be sent.
|
||||
contact.test.failed=Test message failed:
|
||||
|
||||
# Ready-made "Contact page" install card (admin fragment) + install-action result text
|
||||
contact.page.card.title=Contact page
|
||||
contact.page.card.desc=Install a ready-made contact page carrying the form. It becomes a normal site page — edit, restyle, move or rename it from Pages.
|
||||
contact.page.card.install=Install contact page
|
||||
contact.page.card.install.tip=Seed a ready-made, editable contact page (idempotent — it never overwrites an existing page)
|
||||
contact.page.card.badge=Installed
|
||||
contact.page.card.at=Installed at
|
||||
contact.page.card.edit=— edit it under Pages.
|
||||
# install-page action result (plain text)
|
||||
contact.page.title=Contact
|
||||
contact.page.installed=Contact page installed at
|
||||
contact.page.exists=A contact page already exists at
|
||||
contact.page.failed=Could not install the contact page.
|
||||
contact.page.pending=The contact page was created and is waiting in the review queue:
|
||||
contact.page.blocked=The contact page was created as a draft because the quality checks blocked publishing; fix it in the page editor:
|
||||
contact.page.other=The contact page install finished:
|
||||
|
||||
# Public-facing form + result
|
||||
contact.heading=Contact
|
||||
contact.form.name=Name
|
||||
contact.form.email=Email
|
||||
contact.form.message=Message
|
||||
contact.form.submit=Send
|
||||
contact.success=Thanks — your message has been sent.
|
||||
contact.note.stored=Your message was received; email delivery is delayed.
|
||||
contact.error.invalid=Please enter your email and a message.
|
||||
contact.error.captcha=Please complete the challenge and try again.
|
||||
@@ -0,0 +1,66 @@
|
||||
# Runway Contact plugin — cadenas en español.
|
||||
|
||||
# Permiso otorgable (etiqueta de la matriz de permisos)
|
||||
contact.perm.settings=Configurar formulario de contacto
|
||||
|
||||
# Etiquetas del formulario de configuración por sitio
|
||||
contact.set.enabled=Activar formulario de contacto
|
||||
contact.set.success=Mensaje de agradecimiento
|
||||
contact.set.smtpHost=Servidor SMTP
|
||||
contact.set.smtpPort=Puerto SMTP
|
||||
contact.set.smtpAuth=Autenticación SMTP
|
||||
contact.set.smtpUsername=Usuario SMTP
|
||||
contact.set.smtpPassword=Contraseña SMTP
|
||||
contact.set.smtpStarttls=Usar STARTTLS
|
||||
contact.set.smtpSsl=Usar SSL/TLS (SMTPS)
|
||||
contact.set.fromAddress=Dirección de remitente
|
||||
contact.set.toAddress=Enviar los mensajes a
|
||||
|
||||
# Tarjeta del panel
|
||||
contact.card.title=Contacto
|
||||
contact.card.submissions=mensajes
|
||||
|
||||
# Fragmento de estado (admin)
|
||||
contact.admin.title=Mensajes de contacto
|
||||
contact.admin.empty=Aún no hay mensajes.
|
||||
contact.admin.when=Fecha
|
||||
contact.admin.help=Ayuda y referencia de contacto
|
||||
contact.admin.smtp=Relé SMTP
|
||||
contact.admin.smtp.ok=Configurado
|
||||
contact.admin.smtp.missing=Sin configurar
|
||||
contact.admin.smtp.test=Enviar un correo de prueba
|
||||
contact.admin.smtp.test.tip=Envía un mensaje de prueba por el relé SMTP de este sitio para verificar la configuración
|
||||
|
||||
# Resultado de la prueba SMTP (respuesta de texto de /contact/smtp-test)
|
||||
contact.test.ok=Mensaje de prueba enviado.
|
||||
contact.test.notConfigured=No hay ningún relé SMTP configurado para este sitio.
|
||||
contact.test.providerMissing=Las bibliotecas de correo no están disponibles en el servidor, así que no se puede enviar correo.
|
||||
contact.test.failed=La prueba de envío falló:
|
||||
|
||||
# Tarjeta de instalación de la «Página de contacto» (fragmento admin) + texto del resultado de la acción
|
||||
contact.page.card.title=Página de contacto
|
||||
contact.page.card.desc=Instala una página de contacto lista para usar con el formulario. Se convierte en una página normal del sitio: edítala, cámbiale el estilo, muévela o renómbrala desde Páginas.
|
||||
contact.page.card.install=Instalar página de contacto
|
||||
contact.page.card.install.tip=Crea una página de contacto lista y editable (idempotente: nunca sobrescribe una página existente)
|
||||
contact.page.card.badge=Instalada
|
||||
contact.page.card.at=Instalada en
|
||||
contact.page.card.edit=— edítala desde Páginas.
|
||||
# Resultado de la acción de instalación (texto plano)
|
||||
contact.page.title=Contacto
|
||||
contact.page.installed=Página de contacto instalada en
|
||||
contact.page.exists=Ya existe una página de contacto en
|
||||
contact.page.failed=No se pudo instalar la página de contacto.
|
||||
contact.page.pending=Se creó la página de contacto y está esperando en la cola de revisión:
|
||||
contact.page.blocked=Se creó la página de contacto como borrador porque las comprobaciones de calidad bloquearon la publicación; corrígela en el editor de páginas:
|
||||
contact.page.other=La instalación de la página de contacto terminó:
|
||||
|
||||
# De cara al público (formulario + resultado)
|
||||
contact.heading=Contacto
|
||||
contact.form.name=Nombre
|
||||
contact.form.email=Correo electrónico
|
||||
contact.form.message=Mensaje
|
||||
contact.form.submit=Enviar
|
||||
contact.success=Gracias: tu mensaje ha sido enviado.
|
||||
contact.note.stored=Hemos recibido tu mensaje; el envío por correo se ha retrasado.
|
||||
contact.error.invalid=Introduce tu correo electrónico y un mensaje.
|
||||
contact.error.captcha=Completa el desafío e inténtalo de nuevo.
|
||||
@@ -0,0 +1,70 @@
|
||||
# =============================================================================
|
||||
# Runway Contact plugin — descriptor
|
||||
# A contact form delivered as a CONTENT WIDGET on a normal, editable site page
|
||||
# (no plugin-owned page): drop <div id=.. data-widget="contact/form"> on a page,
|
||||
# or install a ready-made contact page in one click from the settings — it then
|
||||
# behaves like any site page (listed under Pages; restyle/move/rename it). The
|
||||
# endpoint owns only the ANONYMOUS POST /contact/submit handler (CSRF-exempt by
|
||||
# the kernel for exactly that method and path; 303s back to the form's page with
|
||||
# a ?contact= outcome), the operator-gated, CSRF-checked POSTs /contact/install-page
|
||||
# and /contact/smtp-test. A submission is BOTH emailed to the site's recipient over
|
||||
# the site's own SMTP relay AND kept as a stored record (belt-and-suspenders —
|
||||
# never lost even if SMTP is down). CAPTCHA (when the site has one) + honeypot.
|
||||
# Links ONLY the Runway SPI (SPI 1.0.0).
|
||||
# The install folder name MUST equal this `id`: external/plugins/contact/.
|
||||
# =============================================================================
|
||||
id: contact
|
||||
name: Contact form
|
||||
version: 2.1.0
|
||||
|
||||
# The @Configuration registered before refresh. Package mx.quest.contact lives OUTSIDE mx.quest.runway.
|
||||
mainClass: mx.quest.contact.ContactConfig
|
||||
|
||||
# Built against the frozen SPI 1.0.0 contract (the service tier: PluginSettings, PluginSiteFiles, Messages,
|
||||
# AccessCheck, SitePages and anonymous POST routes). A kernel with an older SPI BLOCKS this plugin at startup
|
||||
# with a reason.
|
||||
requiresSpi: ">=1.0.0"
|
||||
|
||||
# --- Personal data (siteData) ------------------------------------------------------------------------------
|
||||
# submissions.tsv holds what visitors typed (names, emails, messages). A TRANSFER copy of a site (the one
|
||||
# meant for someone outside the organisation) leaves it out and lists it in the archive's manifest; a FULL
|
||||
# backup keeps it. Path relative to sites/<id>/plugins/contact/.
|
||||
siteData:
|
||||
personal:
|
||||
- submissions.tsv
|
||||
|
||||
# --- Dependencies ----------------------------------------------------------------------------------------
|
||||
# No plugin dependency: the Jakarta Mail stack is part of the CORE application (the kernel bundles it for
|
||||
# its own platform mailer). This plugin compiles Jakarta Mail as `provided` and resolves the kernel's copy at
|
||||
# runtime via the plugin classloader's parent-first delegation, so no `requires:` gate is needed.
|
||||
|
||||
# --- Grantable control-point permission (gates the settings editor, the submissions view + the SMTP test) --
|
||||
permissions:
|
||||
- { id: settings, realm: tenant, label: contact.perm.settings, defaultRoles: [] }
|
||||
|
||||
# --- Per-tenant settings (tenant-owned behaviour; over sites/<id>/plugins/contact.yml) -------------------
|
||||
# The SMTP relay is the TENANT's own mail transport — isolation: a site sends with its OWN settings only.
|
||||
# The password is a `secret` → stored ENC(...)-encrypted and the config file is chmod 600; the plugin reads it
|
||||
# in clear only through PluginSettings.secret(site, "smtpPassword"), at send time. A blank host
|
||||
# (or a blank recipient) simply means "don't send" — the submission is still stored.
|
||||
# secretBoundTo: the stored password belongs to ONE relay login. A save that changes the host, port, username or a TLS switch
|
||||
# without retyping the password makes the kernel DROP the stored password, so whoever may edit the settings
|
||||
# cannot point the site's saved credentials at a server of their choosing and read them off the wire.
|
||||
siteSettings:
|
||||
- { key: enabled, type: boolean, default: true, label: contact.set.enabled }
|
||||
- { key: successMessage, type: text, label: contact.set.success }
|
||||
# --- SMTP relay -------------------------------------------------------------------------------------
|
||||
- { key: smtpHost, type: string, label: contact.set.smtpHost }
|
||||
- { key: smtpPort, type: int, default: 25, range: "1..65535", label: contact.set.smtpPort }
|
||||
- { key: smtpAuth, type: boolean, default: false, label: contact.set.smtpAuth }
|
||||
- { key: smtpUsername, type: string, label: contact.set.smtpUsername }
|
||||
- { key: smtpPassword, type: secret, label: contact.set.smtpPassword,
|
||||
secretBoundTo: [smtpHost, smtpPort, smtpUsername, smtpStarttls, smtpSsl] }
|
||||
- { key: smtpStarttls, type: boolean, default: false, label: contact.set.smtpStarttls }
|
||||
- { key: smtpSsl, type: boolean, default: false, label: contact.set.smtpSsl }
|
||||
- { key: fromAddress, type: string, label: contact.set.fromAddress }
|
||||
- { key: toAddress, type: string, label: contact.set.toAddress }
|
||||
|
||||
# --- Tenant dashboard card (fragment resolves to __plugin__/contact/dashboard) ---------------------------
|
||||
dashboardCards:
|
||||
- { realm: tenant, order: 45, fragment: dashboard, permission: "contact|settings" }
|
||||
@@ -0,0 +1,144 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<!-- Inherit the SAME managed versions the kernel uses (Spring Boot 4.0.6). NOT a Boot app — no repackage;
|
||||
`mvn package` produces a THIN jar of only this plugin's classes. -->
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>4.0.6</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-plugin-contact</artifactId>
|
||||
<version>2.1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>Runway Contact Plugin</name>
|
||||
<licenses>
|
||||
<license>
|
||||
<name>GNU Affero General Public License v3.0, with the Runway additional permission for plugins</name>
|
||||
<url>https://www.gnu.org/licenses/agpl-3.0.txt</url>
|
||||
<distribution>repo</distribution>
|
||||
<comments>See LICENSE and LICENSE-EXCEPTION.</comments>
|
||||
</license>
|
||||
</licenses>
|
||||
<description>
|
||||
A contact form for Runway: an embeddable form content widget that POSTs to an anonymous /contact/submit
|
||||
route. A submission is BOTH emailed over the site's own SMTP relay (via Jakarta Mail, a core capability the
|
||||
kernel bundles) AND kept as a stored tenant-owned record (viewable in the console; declared personal data,
|
||||
so transfer copies leave it out), with CAPTCHA and honeypot anti-spam. Links only the Runway SPI.
|
||||
</description>
|
||||
|
||||
<properties>
|
||||
<java.version>25</java.version>
|
||||
<maven.compiler.release>25</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<!-- Reproducible builds: pins every archive entry's timestamp so two builds of the same source
|
||||
produce byte-identical artifacts. Without it a jar embeds the build time, so a rebuild can
|
||||
never match what was published. Bump at each release. -->
|
||||
<project.build.outputTimestamp>2026-10-21T18:56:00Z</project.build.outputTimestamp>
|
||||
<runway.version>1.0.0</runway.version>
|
||||
<!-- Kept in lock-step with the Jakarta Mail the KERNEL bundles (mail is a core capability).
|
||||
Compile-only here; the kernel supplies it at runtime. -->
|
||||
<jakarta.mail-api.version>2.1.5</jakarta.mail-api.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-spi</artifactId>
|
||||
<version>${runway.version}</version>
|
||||
</dependency>
|
||||
<!-- NO runway-app dependency, in any scope: the plugin links only the SPI, so a host
|
||||
import does not compile and the kernel's host-linkage scanner finds nothing to report. -->
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-spi-testkit</artifactId>
|
||||
<version>${runway.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Jakarta Mail API — PROVIDED at runtime by the KERNEL (which bundles the Jakarta Mail stack for its
|
||||
own platform mailer). Compile-only here: NEVER bundle it into this plugin's own lib/ (that would be a
|
||||
second Jakarta Mail copy on the classloader, shadowing the kernel's). The plugin classloader delegates
|
||||
parent-first, so the kernel's API + Angus SMTP implementation resolve at runtime via META-INF/services. -->
|
||||
<dependency>
|
||||
<groupId>jakarta.mail</groupId>
|
||||
<artifactId>jakarta.mail-api</artifactId>
|
||||
<version>${jakarta.mail-api.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Tests exercise the send path against a MOCK MailTransport (no socket) and the Angus implementation
|
||||
is needed to actually construct MimeMessage/Session in-process, so bring it in at test scope. -->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.angus</groupId>
|
||||
<artifactId>angus-mail</artifactId>
|
||||
<version>2.0.5</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>runway-plugin-contact</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-antrun-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>assemble-plugin-folder</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>run</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<target>
|
||||
<property name="stage" value="${project.build.directory}/contact"/>
|
||||
<delete dir="${stage}"/>
|
||||
<mkdir dir="${stage}"/>
|
||||
<copy file="${project.basedir}/plugin.yml" todir="${stage}"/>
|
||||
<copy file="${project.basedir}/LICENSE" todir="${stage}"/>
|
||||
<copy file="${project.basedir}/LICENSE-EXCEPTION" todir="${stage}"/>
|
||||
<copy file="${project.build.directory}/runway-plugin-contact.jar" todir="${stage}"/>
|
||||
<copy todir="${stage}/static">
|
||||
<fileset dir="${project.basedir}/static"/>
|
||||
</copy>
|
||||
<copy todir="${stage}/templates">
|
||||
<fileset dir="${project.basedir}/templates"/>
|
||||
</copy>
|
||||
<copy todir="${stage}/i18n">
|
||||
<fileset dir="${project.basedir}/i18n"/>
|
||||
</copy>
|
||||
<touch datetime="${project.build.outputTimestamp}"
|
||||
pattern="yyyy-MM-dd'T'HH:mm:ss'Z'">
|
||||
<fileset dir="${stage}"/>
|
||||
<dirset dir="${stage}"/>
|
||||
<dirset dir="${project.build.directory}" includes="contact"/>
|
||||
</touch>
|
||||
<zip destfile="${project.build.directory}/runway-plugin-contact-${project.version}.zip">
|
||||
<zipfileset dir="${project.build.directory}" includes="contact/**"/>
|
||||
</zip>
|
||||
<echo message="Staged install folder: ${stage}"/>
|
||||
<echo message="UI-uploadable archive: ${project.build.directory}/runway-plugin-contact-${project.version}.zip"/>
|
||||
</target>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
+383
@@ -0,0 +1,383 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build this plugin, drop it into a throwaway Runway deployment, boot the PACKAGED host in ACTIVE mode, and prove
|
||||
# the contact contract end to end (SPI 1.0.0):
|
||||
# - it loads with ZERO host-linkage and bean-name/surface warnings;
|
||||
# - an anonymous visitor's form POST (no session, no CSRF token) to the anonymous route is stored and 303s back
|
||||
# with only an outcome flag; GET submission is gone; honeypot / invalid / non-form bodies are refused;
|
||||
# - the two operator actions are CSRF-protected POSTs: a GET (a cross-site link or <img>) changes nothing even
|
||||
# for a signed-in owner, a POST without the console's CSRF token is refused 403, and an anonymous caller holding
|
||||
# a token is still refused by the permission check (404);
|
||||
# - signed in as the site owner, the starter page installs (POST + the token from the settings page) through
|
||||
# SitePages on an Advisory, an Enforced and a Reviewed site (each outcome reported), and a second install
|
||||
# changes nothing;
|
||||
# - the SMTP password saved through the settings form is stored ENC(...) and reaches a local fake relay in clear
|
||||
# (PluginSettings.secret), both for a submission and for the operator's SMTP test, whose body `to` override
|
||||
# arrives with the CSRF token as a form field or a header;
|
||||
# - a FULL backup carries submissions.tsv and a TRANSFER copy leaves it out and lists it in its manifest;
|
||||
# - with the protection plugin installed (from the host checkout, when built) and a CAPTCHA configured on one
|
||||
# site, a POST without the CAPTCHA token is refused and nothing is stored.
|
||||
# The deployment holds four sites copied from the wizard's default one before the ACTIVE boot: default (Advisory),
|
||||
# enforced, reviewed, captcha — addressed by Host name through curl --resolve. Verify ONLY against the packaged jar
|
||||
# — never spring-boot:run (its restart classloader loads ZERO plugins).
|
||||
#
|
||||
# Usage: scripts/verify-against-host.sh [--keep] [--port N]
|
||||
# JAVA_HOME=/path/to/jdk-25 required: the JDK that builds the plugin and runs the host
|
||||
# MVN=/path/to/mvn Maven (default: mvn on the PATH)
|
||||
# HOST_TARGET=/path/to/runway/runway-app/target the host build (default: the kernel this plugin sits in, else ../runway)
|
||||
# HOST_JAR=/path/to/runway-app-<ver>-exec.jar the kernel to verify against (default: the host checkout's
|
||||
# runway-app/target jar MATCHING its pom version)
|
||||
# PROTECTION_DIR=/dir the protection plugin's source folder (plugin.yml, i18n/, templates/,
|
||||
# target/runway-plugin-protection.jar); default: the host checkout's
|
||||
# runway-plugin-protection/.
|
||||
# Set it to "" to skip the CAPTCHA checks.
|
||||
# VERIFY_TMPDIR=/dir where the throwaway deployment goes (default: $TMPDIR or /tmp)
|
||||
# VERIFY_LOG_DIR=/dir keep copies of the host logs, the fake relay's log and the two
|
||||
# backup manifests there (evidence)
|
||||
# The script never runs `mvn install` (nothing is written to ~/.m2): it packages this plugin offline against
|
||||
# whatever runway-spi is already in the local repository.
|
||||
set -uo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
|
||||
# JAVA_HOME must name a JDK 25. MVN (default: `mvn` on the PATH), HOST_TARGET and PROTECTION_DIR (defaults: see
|
||||
# above) can be set in the environment.
|
||||
if [ -z "${JAVA_HOME:-}" ] || [ ! -x "$JAVA_HOME/bin/java" ]; then echo "set JAVA_HOME to a JDK 25"; exit 2; fi
|
||||
export JAVA_HOME
|
||||
JAVA="$JAVA_HOME/bin/java"
|
||||
MVN="${MVN:-mvn}"
|
||||
# Default host: the kernel at the root of the repository this plugin sits in (plugins/<name>/), else a kernel
|
||||
# checkout named `runway` beside the plugins checkout.
|
||||
if [ -z "${HOST_TARGET:-}" ]; then
|
||||
if [ -f "$HERE/../../runway-app/pom.xml" ]; then HOST_TARGET="$HERE/../../runway-app/target"
|
||||
else HOST_TARGET="$HERE/../../runway/runway-app/target"; fi
|
||||
fi
|
||||
PROTECTION_DIR="${PROTECTION_DIR-$HOST_TARGET/../../runway-plugin-protection}"
|
||||
|
||||
KEEP="no"; PORT=""
|
||||
while [ $# -gt 0 ]; do case "$1" in
|
||||
--keep) KEEP="yes"; shift ;;
|
||||
--port) PORT="${2:?}"; shift 2 ;;
|
||||
*) echo "unknown arg: $1"; exit 2 ;;
|
||||
esac; done
|
||||
|
||||
APP_USER=root; APP_PW=Contact-Admin-2026; SITE_USER=owner; SITE_PW=Contact-Site-2026
|
||||
SECRET_KEY=contact-verify-master-key-2026; RELAY_USER=relay-user; RELAY_PW='Relay-Secret-42'
|
||||
free_port() { python3 -I -c 'import socket;s=socket.socket();s.bind(("127.0.0.1",0));print(s.getsockname()[1]);s.close()'; }
|
||||
[ -n "$PORT" ] || PORT="$(free_port)"
|
||||
SMTP_PORT="$(free_port)"
|
||||
BASE="http://localhost:$PORT"
|
||||
|
||||
echo "[verify] building the plugin ..."
|
||||
( cd "$HERE" && "$MVN" -o -q -DskipTests package ) || { echo "plugin build failed"; exit 1; }
|
||||
|
||||
# The host jar MATCHING the host pom's version — never "the newest file": every reproducible jar carries the same
|
||||
# fixed timestamp, so `ls -t` cannot tell a leftover release jar from the SNAPSHOT under test.
|
||||
if [ -n "${HOST_JAR:-}" ]; then
|
||||
JAR="$HOST_JAR"
|
||||
else
|
||||
HOST_VERSION="$(sed -n 's:.*<version>\(.*\)</version>.*:\1:p' "$HOST_TARGET/../pom.xml" | head -1)"
|
||||
JAR="$HOST_TARGET/runway-app-$HOST_VERSION-exec.jar"
|
||||
fi
|
||||
[ -f "$JAR" ] || { echo "no host exec jar $JAR — build the host (mvn -pl runway-app package) or set HOST_JAR"; exit 1; }
|
||||
echo "[verify] host jar: $JAR"
|
||||
|
||||
SCRATCH="$(mktemp -d "${VERIFY_TMPDIR:-${TMPDIR:-/tmp}}/contact-verify.XXXXXX")"
|
||||
cleanup() {
|
||||
[ -z "${VERIFY_LOG_DIR:-}" ] || { mkdir -p "$VERIFY_LOG_DIR" \
|
||||
&& cp "$SCRATCH"/*.log "$SCRATCH"/*-manifest.yml "$VERIFY_LOG_DIR"/ 2>/dev/null; }
|
||||
kill "${SMTP_PID:-0}" 2>/dev/null
|
||||
# Wait for the host to exit before deleting: a JVM still shutting down rewrites files under external/ and
|
||||
# makes `rm -rf` leave the scratch folder behind.
|
||||
[ "$KEEP" = "yes" ] || { kill "${PID:-0}" 2>/dev/null; wait "${PID:-0}" 2>/dev/null; rm -rf "$SCRATCH"; }
|
||||
}
|
||||
trap cleanup EXIT
|
||||
EXT="$SCRATCH/external"
|
||||
mkdir -p "$EXT/plugins"
|
||||
cp -r "$HERE/target/contact" "$EXT/plugins/contact"
|
||||
|
||||
wait_for() { for _ in $(seq 1 "$3"); do grep -q "$2" "$1" 2>/dev/null && return 0; sleep 1; done; return 1; }
|
||||
PASS=0; FAIL=0; SKIP=0
|
||||
ck() { if eval "$2" >/dev/null 2>&1; then echo " PASS $1"; PASS=$((PASS+1)); else echo " FAIL $1"; FAIL=$((FAIL+1)); fi; }
|
||||
skip() { echo " SKIP $1"; SKIP=$((SKIP+1)); }
|
||||
boot() { ( cd "$SCRATCH" && exec "$JAVA" -jar "$JAR" --server.port="$PORT" --runway.storage.external="$EXT" \
|
||||
--runway.security.secret-key="$SECRET_KEY" ) >"$1" 2>&1 & PID=$!; }
|
||||
|
||||
echo "[verify] booting host (wizard) on :$PORT ..."
|
||||
boot "$SCRATCH/wizard.log"
|
||||
wait_for "$SCRATCH/wizard.log" "Started RunwayApplication" 90 || { echo "wizard did not start"; tail -20 "$SCRATCH/wizard.log"; exit 1; }
|
||||
curl -s -o /dev/null -X POST "$BASE/setup" --data-urlencode "username=$APP_USER" --data-urlencode "password=$APP_PW" \
|
||||
--data-urlencode "displayName=Root" --data-urlencode "siteAdminUsername=$SITE_USER" --data-urlencode "siteAdminPassword=$SITE_PW"
|
||||
for _ in $(seq 1 30); do kill -0 "$PID" 2>/dev/null || break; sleep 1; done
|
||||
|
||||
# --- Three more sites, copied from the seeded default one (same owner), before the ACTIVE boot reads them --------
|
||||
SITES="$EXT/sites"
|
||||
[ -f "$SITES/default/site.yml" ] || { echo "the wizard did not seed $SITES/default"; exit 1; }
|
||||
make_site() { # id editorial-level
|
||||
cp -r "$SITES/default" "$SITES/$1"
|
||||
sed -i -e "s/^id: .*/id: \"$1\"/" -e "s/^- \"localhost\"/- \"$1.test\"/" -e "s/^editorial: .*/editorial: \"$2\"/" \
|
||||
"$SITES/$1/site.yml"
|
||||
}
|
||||
make_site enforced enforced
|
||||
make_site reviewed reviewed
|
||||
make_site captcha advisory
|
||||
sed -i 's/^ - "default"$/ - "default"\n - "enforced"\n - "reviewed"/' "$EXT/site-users.yml"
|
||||
# A page carrying the widget anchor on the captcha site: its seeded About page, edited on disk.
|
||||
sed -i 's|<main id="content">|<main id="content"><div id="contact-form" data-widget="contact/form"></div>|' \
|
||||
"$SITES/captcha/templates/about.html"
|
||||
PROTECTION="no"
|
||||
if [ -n "$PROTECTION_DIR" ] && [ -f "$PROTECTION_DIR/target/runway-plugin-protection.jar" ]; then
|
||||
mkdir -p "$EXT/plugins/protection"
|
||||
cp "$PROTECTION_DIR/plugin.yml" "$PROTECTION_DIR/target/runway-plugin-protection.jar" "$EXT/plugins/protection/"
|
||||
cp -r "$PROTECTION_DIR/i18n" "$PROTECTION_DIR/templates" "$EXT/plugins/protection/"
|
||||
mkdir -p "$SITES/captcha/plugins"
|
||||
# A reCAPTCHA v2 configuration for the captcha site only (a hand-written plaintext secret is accepted). A POST
|
||||
# without a token is refused before any call to the provider, so no network is needed.
|
||||
cat > "$SITES/captcha/plugins/protection.yml" <<'YML'
|
||||
honeypotEnabled: true
|
||||
captcha:
|
||||
enabled: true
|
||||
provider: recaptcha-v2
|
||||
siteKey: verify-site-key
|
||||
secretKey: verify-secret-key
|
||||
YML
|
||||
PROTECTION="yes"
|
||||
fi
|
||||
|
||||
echo "[verify] booting host (ACTIVE) ..."
|
||||
boot "$SCRATCH/active.log"
|
||||
wait_for "$SCRATCH/active.log" "Started RunwayApplication" 90 || { echo "ACTIVE did not start"; tail -20 "$SCRATCH/active.log"; exit 1; }
|
||||
LOG="$SCRATCH/active.log"
|
||||
TSV="$SITES/default/plugins/contact/submissions.tsv"
|
||||
lines() { if [ -f "$1" ]; then grep -c . "$1"; else echo 0; fi; }
|
||||
|
||||
echo "== plugin load (SPI 1.0.0 contract) =="
|
||||
EXPECTED=1; [ "$PROTECTION" = "yes" ] && EXPECTED=2
|
||||
ck "plugins registered ($EXPECTED), 0 blocked" "grep -qE 'plugins: $EXPECTED registered, 0 blocked' '$LOG'"
|
||||
ck "not blocked / quarantined" "! grep -qE \"plugin 'contact' is blocked|plugin-quarantine\" '$LOG'"
|
||||
# Host linkage and the surface rules, in both kernels' words: SPI 0.6.0 WARNed ("uses host internals", "… allowed until
|
||||
# Runway 1.0"); from SPI 1.0.0 the kernel BLOCKS and logs "linkage scan: <reason>" / the surface reason — a grep for the
|
||||
# 0.6.0 wording alone can never fail on a 1.0 kernel.
|
||||
ck "ZERO host-linkage findings" "! grep -qE \"uses host internals|plugin 'contact' linkage scan\" '$LOG'"
|
||||
ck "ZERO bean-name/surface findings" "! grep -qE \"plugin 'contact'.*(allowed until Runway 1.0|bean name|may not contribute)\" '$LOG'"
|
||||
ck "no WARN/ERROR names the plugin" "! grep -E ' (WARN|ERROR) ' '$LOG' | grep -qi 'contact'"
|
||||
ck "no key collision / degraded" "! grep -qiE 'collision|duplicate key|degraded' '$LOG'"
|
||||
|
||||
echo "== static assets =="
|
||||
ck "contact.css served" "curl -s -o /dev/null -w '%{http_code}' '$BASE/__plugin/contact/static/contact.css' | grep -q 200"
|
||||
ck "help page served" "curl -s -o /dev/null -w '%{http_code}' '$BASE/__plugin/contact/static/contact-help.html' | grep -q 200"
|
||||
|
||||
echo "== anonymous POST /contact/submit (no session, no CSRF token) =="
|
||||
post() { curl -s -o /dev/null -w '%{http_code} %{redirect_url}' -X POST "$@"; }
|
||||
R="$(post "$BASE/contact/submit" --data-urlencode 'return=/' --data-urlencode 'name=Ann Visitor' \
|
||||
--data-urlencode 'email=ann@example.com' --data-urlencode 'message=Hello from a POST' --data-urlencode 'website=')"
|
||||
ck "valid POST -> 303 ?contact=sent" "[ \"\${R%% *}\" = 303 ] && echo '$R' | grep -q 'contact=sent'"
|
||||
ck "the redirect carries no submitted value" "! echo '$R' | grep -qiE 'ann|example|hello'"
|
||||
ck "the submission is stored (appended to submissions.tsv)" "grep -q $'\tAnn Visitor\tann@example.com\tHello from a POST' '$TSV'"
|
||||
ck "a GET submission is gone (404) and stores nothing" \
|
||||
"[ \"\$(curl -s -o /dev/null -w '%{http_code}' '$BASE/contact/submit?return=/&name=Get&email=get%40example.com&message=via%20GET&website=')\" = 404 ] && ! grep -q 'get@example.com' '$TSV'"
|
||||
ck "a filled honeypot fakes success and stores nothing" \
|
||||
"post '$BASE/contact/submit' -d 'return=/&name=Bot&email=bot%40example.com&message=spam&website=http://spam' | grep -q 'contact=sent' && ! grep -q 'bot@example.com' '$TSV'"
|
||||
ck "an invalid email -> ?contact=invalid, not stored" \
|
||||
"post '$BASE/contact/submit' -d 'return=/&name=Bad&email=nope&message=hi&website=' | grep -q 'contact=invalid' && ! grep -q $'\tBad\t' '$TSV'"
|
||||
ck "fields in the query string are ignored -> invalid" \
|
||||
"post '$BASE/contact/submit?name=Q&email=q%40example.com&message=query' -d 'return=/' | grep -q 'contact=invalid' && ! grep -q 'q@example.com' '$TSV'"
|
||||
ck "a multipart body is refused 415 by the kernel" \
|
||||
"[ \"\$(curl -s -o /dev/null -w '%{http_code}' -X POST '$BASE/contact/submit' -F 'name=M' -F 'email=m@example.com' -F 'message=multi')\" = 415 ]"
|
||||
ck "exactly one stored submission so far" "[ \"\$(lines '$TSV')\" = 1 ]"
|
||||
|
||||
ck "submissions.tsv is never served publicly" \
|
||||
"( for u in '/static/../plugins/contact/submissions.tsv' '/plugins/contact/submissions.tsv' '/__plugin/contact/static/../../submissions.tsv'; do curl -s --path-as-is '$BASE'\$u | grep -q 'ann@example.com' && exit 1; done; exit 0 )"
|
||||
|
||||
echo "== the starter page through SitePages (Advisory, Enforced, Reviewed) =="
|
||||
token() { grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//'; }
|
||||
# One cookie jar per site host; curl --resolve maps <site>.test to the local host so cookies scope correctly.
|
||||
site_url() { [ "$1" = default ] && echo "$BASE" || echo "http://$1.test:$PORT"; }
|
||||
sc() { # site curl-args...
|
||||
local site="$1"; shift
|
||||
curl -s -H 'Accept-Language: en' --resolve "$site.test:$PORT:127.0.0.1" \
|
||||
-c "$SCRATCH/cookies-$site.txt" -b "$SCRATCH/cookies-$site.txt" "$@"
|
||||
}
|
||||
login() {
|
||||
local u; u="$(site_url "$1")"
|
||||
sc "$1" -o /dev/null -X POST "$u/login" --data-urlencode "username=$SITE_USER" --data-urlencode "password=$SITE_PW" \
|
||||
--data-urlencode "_csrf=$(sc "$1" "$u/login" | token)"
|
||||
}
|
||||
code() { curl -s -o /dev/null -w '%{http_code}' "$@"; }
|
||||
SETTINGS="$BASE/__admin/plugins/contact/settings"
|
||||
no_page() { ! ls "$SITES/$1/templates"/contact.* >/dev/null 2>&1; }
|
||||
|
||||
echo "== the operator actions are CSRF-protected POSTs (a link or an <img> changes nothing) =="
|
||||
ck "anonymous GET of either action -> 404 (no GET route)" \
|
||||
"[ \"\$(code '$BASE/contact/install-page')\" = 404 ] && [ \"\$(code '$BASE/contact/smtp-test')\" = 404 ]"
|
||||
ck "anonymous POST without a CSRF token -> 403 (the tenant chain's CSRF check)" \
|
||||
"[ \"\$(code -X POST '$BASE/contact/install-page' -d x=1)\" = 403 ] && [ \"\$(code -X POST '$BASE/contact/smtp-test' -d x=1)\" = 403 ]"
|
||||
ANON_JAR="$SCRATCH/cookies-anon.txt"
|
||||
ANON_TOKEN="$(curl -s -c "$ANON_JAR" -b "$ANON_JAR" "$BASE/login" | token)"
|
||||
ck "anonymous POST WITH a valid session token -> 404 (the permission check still applies)" \
|
||||
"[ -n '$ANON_TOKEN' ] && [ \"\$(code -c '$ANON_JAR' -b '$ANON_JAR' -X POST '$BASE/contact/install-page' --data-urlencode '_csrf=$ANON_TOKEN')\" = 404 ]"
|
||||
ck "…and nothing was installed by any of that" "no_page default"
|
||||
for site in default enforced reviewed; do login "$site"; done
|
||||
ck "signed-in owner: GET /contact/install-page -> 404 and no page (a cross-site link installs nothing)" \
|
||||
"[ \"\$(sc default -o /dev/null -w '%{http_code}' '$BASE/contact/install-page')\" = 404 ] && no_page default"
|
||||
ck "signed-in owner: POST without the CSRF token -> 403 and no page" \
|
||||
"[ \"\$(sc default -o /dev/null -w '%{http_code}' -X POST '$BASE/contact/install-page' -d x=1)\" = 403 ] && no_page default"
|
||||
ck "signed-in owner: POST with a forged CSRF token -> 403 and no page" \
|
||||
"[ \"\$(sc default -o /dev/null -w '%{http_code}' -X POST '$BASE/contact/install-page' -d _csrf=forged-token)\" = 403 ] && no_page default"
|
||||
sc default "$SETTINGS" > "$SCRATCH/settings-0.html"
|
||||
ck "the settings page offers the install as a POST form carrying a non-empty CSRF token" \
|
||||
"grep -q 'id=\"cp-install-form\" method=\"post\" action=\"/contact/install-page\"' '$SCRATCH/settings-0.html' && grep -qE 'id=\"cp-csrf\" type=\"hidden\" name=\"_csrf\" value=\"[^\"]+\"' '$SCRATCH/settings-0.html'"
|
||||
ck "…and the SMTP test as a POST form carrying a non-empty CSRF token" \
|
||||
"grep -q 'id=\"cn-smtp-test-form\" method=\"post\" action=\"/contact/smtp-test\"' '$SCRATCH/settings-0.html' && grep -qE 'id=\"cn-csrf\" type=\"hidden\" name=\"_csrf\" value=\"[^\"]+\"' '$SCRATCH/settings-0.html'"
|
||||
ck "…and no link points at either action" "! grep -qE 'href=\"/contact/(install-page|smtp-test)' '$SCRATCH/settings-0.html'"
|
||||
install() { # site -> the install action's answer, POSTed with the token from that site's settings page
|
||||
local u; u="$(site_url "$1")"
|
||||
sc "$1" -X POST "$u/contact/install-page" --data-urlencode "_csrf=$(sc "$1" "$u/__admin/plugins/contact/settings" | token)"
|
||||
}
|
||||
install default > "$SCRATCH/install-default.txt"
|
||||
ck "Advisory: POST with the token installs and publishes at /contact" "grep -qx 'Contact page installed at /contact' '$SCRATCH/install-default.txt'"
|
||||
curl -s "$BASE/contact" > "$SCRATCH/contact-page.html"
|
||||
ck "…the public page renders the form as a POST to the anonymous route" \
|
||||
"grep -q 'method=\"post\" action=\"/contact/submit\"' '$SCRATCH/contact-page.html' && ! grep -q 'name=\"_csrf\"' '$SCRATCH/contact-page.html'"
|
||||
ck "…with the return path of the page" "grep -q 'name=\"return\" value=\"/contact\"' '$SCRATCH/contact-page.html'"
|
||||
install default > "$SCRATCH/install-again.txt"
|
||||
ck "a second install changes nothing and says where the page is" "grep -qx 'A contact page already exists at /contact' '$SCRATCH/install-again.txt'"
|
||||
for site in enforced reviewed; do
|
||||
install "$site" > "$SCRATCH/install-$site.txt"
|
||||
echo " $site says: $(head -c 300 "$SCRATCH/install-$site.txt" | tr '\n' ' ')"
|
||||
done
|
||||
# Enforced: published when the quality checks pass, else a draft with the blocking findings listed.
|
||||
ck "Enforced: a documented outcome, never an error" \
|
||||
"grep -qE '^(Contact page installed at /contact|The contact page was created as a draft because the quality checks blocked publishing; fix it in the page editor: /contact)' '$SCRATCH/install-enforced.txt'"
|
||||
# Reviewed: the owner holds APPROVE_PAGES, so the gated publish runs; without it the page would wait for review.
|
||||
ck "Reviewed (as the owner, who may approve): a documented outcome" \
|
||||
"grep -qE '^(Contact page installed at /contact|The contact page was created and is waiting in the review queue: /contact|The contact page was created as a draft)' '$SCRATCH/install-reviewed.txt'"
|
||||
ck "the installed pages exist on every site" \
|
||||
"( for s in default enforced reviewed; do ls \"$SITES/\$s/templates\"/contact.* >/dev/null || exit 1; done )"
|
||||
sc default "$SETTINGS" > "$SCRATCH/settings-1.html"
|
||||
ck "the settings page shows the installed page's live path" "grep -q 'id=\"cp-path\"[^>]*>/contact<' '$SCRATCH/settings-1.html'"
|
||||
ck "…and counts the stored submission" "grep -q 'id=\"cn-count\">1<' '$SCRATCH/settings-1.html'"
|
||||
|
||||
echo "== the SMTP password: saved ENC(...), handed to the relay in clear (PluginSettings.secret) =="
|
||||
# A minimal local SMTP relay that accepts AUTH LOGIN/PLAIN and records the credentials and the message.
|
||||
cat > "$SCRATCH/fake_smtp.py" <<'PY'
|
||||
import base64, socket, sys, threading
|
||||
port, log = int(sys.argv[1]), open(sys.argv[2], "a", buffering=1)
|
||||
def b64(s):
|
||||
return base64.b64decode(s.strip()).decode("utf-8", "replace")
|
||||
def serve(c):
|
||||
f = c.makefile("rwb", buffering=0)
|
||||
def say(line): f.write((line + "\r\n").encode())
|
||||
say("220 fake ESMTP")
|
||||
while True:
|
||||
raw = f.readline()
|
||||
if not raw: break
|
||||
line = raw.decode("utf-8", "replace").rstrip("\r\n"); up = line.upper()
|
||||
if up.startswith(("EHLO", "HELO")): say("250-fake"); say("250 AUTH LOGIN PLAIN")
|
||||
elif up.startswith("AUTH PLAIN"):
|
||||
arg = line[10:].strip()
|
||||
if not arg: say("334 "); arg = f.readline().decode()
|
||||
parts = b64(arg).split("\0"); log.write("AUTH user=%s pass=%s\n" % (parts[1], parts[2])); say("235 ok")
|
||||
elif up.startswith("AUTH LOGIN"):
|
||||
arg = line[10:].strip()
|
||||
if not arg: say("334 VXNlcm5hbWU6"); arg = f.readline().decode()
|
||||
user = b64(arg); say("334 UGFzc3dvcmQ6"); pw = b64(f.readline().decode())
|
||||
log.write("AUTH user=%s pass=%s\n" % (user, pw)); say("235 ok")
|
||||
elif up.startswith(("MAIL", "RCPT", "RSET", "NOOP")): log.write(line + "\n"); say("250 ok")
|
||||
elif up == "DATA":
|
||||
say("354 go")
|
||||
while True:
|
||||
d = f.readline().decode("utf-8", "replace")
|
||||
if d in (".\r\n", ".\n", ""): break
|
||||
log.write("DATA " + d.rstrip("\r\n") + "\n")
|
||||
say("250 queued")
|
||||
elif up == "QUIT": say("221 bye"); break
|
||||
else: say("250 ok")
|
||||
c.close()
|
||||
s = socket.socket(); s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1); s.bind(("127.0.0.1", port)); s.listen(5)
|
||||
while True:
|
||||
conn, _ = s.accept(); threading.Thread(target=serve, args=(conn,), daemon=True).start()
|
||||
PY
|
||||
python3 -I "$SCRATCH/fake_smtp.py" "$SMTP_PORT" "$SCRATCH/smtp.log" & SMTP_PID=$!
|
||||
sc default -o /dev/null -X POST "$SETTINGS" --data-urlencode "enabled=true" \
|
||||
--data-urlencode "smtpHost=127.0.0.1" --data-urlencode "smtpPort=$SMTP_PORT" --data-urlencode "smtpAuth=true" \
|
||||
--data-urlencode "smtpUsername=$RELAY_USER" --data-urlencode "smtpPassword=$RELAY_PW" \
|
||||
--data-urlencode "fromAddress=site@example.test" --data-urlencode "toAddress=owner@example.test" \
|
||||
--data-urlencode "_csrf=$(token < "$SCRATCH/settings-1.html")"
|
||||
CFG="$SITES/default/plugins/contact.yml"
|
||||
ck "the password is stored ENC(...), never in clear" "grep -q 'smtpPassword: .*ENC(' '$CFG' && ! grep -q '$RELAY_PW' '$CFG'"
|
||||
R="$(post "$BASE/contact/submit" --data-urlencode 'return=/contact' --data-urlencode 'name=Bea Mailer' \
|
||||
--data-urlencode 'email=bea@example.com' --data-urlencode 'message=Please call me back' --data-urlencode 'website=')"
|
||||
ck "a submission over the configured relay -> ?contact=sent (not queued)" "echo '$R' | grep -q '/contact?contact=sent'"
|
||||
ck "…the relay was offered the secret in clear" "grep -qx 'AUTH user=$RELAY_USER pass=$RELAY_PW' '$SCRATCH/smtp.log'"
|
||||
ck "…and received the visitor's message" "grep -q 'DATA Please call me back' '$SCRATCH/smtp.log'"
|
||||
ck "…which is stored as well" "grep -q 'bea@example.com' '$TSV'"
|
||||
ck "signed-in owner: GET /contact/smtp-test?to=… -> 404 and no email (a cross-site link sends nothing)" \
|
||||
"[ \"\$(sc default -o /dev/null -w '%{http_code}' '$BASE/contact/smtp-test?to=link@example.test')\" = 404 ] && ! grep -q 'link@example.test' '$SCRATCH/smtp.log'"
|
||||
ck "signed-in owner: POST /contact/smtp-test without the CSRF token -> 403 and no email" \
|
||||
"[ \"\$(sc default -o /dev/null -w '%{http_code}' -X POST '$BASE/contact/smtp-test' --data-urlencode 'to=forged@example.test')\" = 403 ] && ! grep -q 'forged@example.test' '$SCRATCH/smtp.log'"
|
||||
# The console's button: a form POST carrying only the token -> the test goes to the configured recipient.
|
||||
sc default -X POST "$BASE/contact/smtp-test" --data-urlencode "_csrf=$(sc default "$SETTINGS" | token)" \
|
||||
> "$SCRATCH/smtp-test.txt"
|
||||
ck "the operator's SMTP test (the console form: POST + token) sends over the same relay to the configured recipient" \
|
||||
"grep -qx 'Test message sent.' '$SCRATCH/smtp-test.txt' && [ \"\$(grep -c 'RCPT TO:<owner@example.test>' '$SCRATCH/smtp.log')\" = 2 ]"
|
||||
# The optional `to` override is read from the form BODY, never the query string. A browser form sends the CSRF
|
||||
# token as the `_csrf` FIELD next to it, so that is the case that must work: the kernel keeps the url-encoded body
|
||||
# for the route after its CSRF check, so form() carries the field whether the token came as the field or in the
|
||||
# X-CSRF-TOKEN header. Both ways are checked.
|
||||
sc default -X POST "$BASE/contact/smtp-test" --data-urlencode "_csrf=$(sc default "$SETTINGS" | token)" \
|
||||
--data-urlencode "to=field@example.test" > "$SCRATCH/smtp-test-to-field.txt"
|
||||
ck "…and honours a 'to' override in the body with the token as a form field (as a browser form sends it)" \
|
||||
"grep -qx 'Test message sent.' '$SCRATCH/smtp-test-to-field.txt' && grep -q 'RCPT TO:<field@example.test>' '$SCRATCH/smtp.log'"
|
||||
sc default -X POST "$BASE/contact/smtp-test" -H "X-CSRF-TOKEN: $(sc default "$SETTINGS" | token)" \
|
||||
--data-urlencode "to=header@example.test" > "$SCRATCH/smtp-test-to-header.txt"
|
||||
ck "…and with the token in the X-CSRF-TOKEN header" \
|
||||
"grep -qx 'Test message sent.' '$SCRATCH/smtp-test-to-header.txt' && grep -q 'RCPT TO:<header@example.test>' '$SCRATCH/smtp.log'"
|
||||
sc default -X POST "$BASE/contact/smtp-test?to=query@example.test" \
|
||||
--data-urlencode "_csrf=$(sc default "$SETTINGS" | token)" > "$SCRATCH/smtp-test-to-query.txt"
|
||||
ck "…but ignores a 'to' in the query string (the test goes to the configured recipient)" \
|
||||
"grep -qx 'Test message sent.' '$SCRATCH/smtp-test-to-query.txt' && ! grep -q 'query@example.test' '$SCRATCH/smtp.log' && [ \"\$(grep -c 'RCPT TO:<owner@example.test>' '$SCRATCH/smtp.log')\" = 3 ]"
|
||||
|
||||
echo "== backups: a full backup keeps submissions.tsv, a transfer copy leaves it out =="
|
||||
sc default -o "$SCRATCH/full.zip" "$BASE/__admin/backups/download"
|
||||
sc default -o "$SCRATCH/transfer.zip" "$BASE/__admin/backups/download-transfer"
|
||||
zipq() { # zip mode -> prints what was asked
|
||||
python3 -I - "$@" <<'PY'
|
||||
import sys, zipfile
|
||||
z = zipfile.ZipFile(sys.argv[1]); mode = sys.argv[2]
|
||||
names = z.namelist()
|
||||
if mode == "has":
|
||||
sys.exit(0 if any(n.endswith(sys.argv[3]) for n in names) else 1)
|
||||
if mode == "read":
|
||||
n = next(n for n in names if n.endswith(sys.argv[3])); sys.stdout.write(z.read(n).decode("utf-8"))
|
||||
PY
|
||||
}
|
||||
zipq "$SCRATCH/full.zip" read manifest.yml > "$SCRATCH/full-manifest.yml" 2>/dev/null
|
||||
zipq "$SCRATCH/transfer.zip" read manifest.yml > "$SCRATCH/transfer-manifest.yml" 2>/dev/null
|
||||
ck "the full backup carries plugins/contact/submissions.tsv" "zipq '$SCRATCH/full.zip' has plugins/contact/submissions.tsv"
|
||||
ck "…with the submissions in it" "zipq '$SCRATCH/full.zip' read plugins/contact/submissions.tsv | grep -q 'ann@example.com'"
|
||||
ck "the transfer copy has NO plugins/contact/submissions.tsv" "! zipq '$SCRATCH/transfer.zip' has plugins/contact/submissions.tsv"
|
||||
ck "…and its manifest lists the omission" "grep -q 'plugins/contact/submissions.tsv' '$SCRATCH/transfer-manifest.yml'"
|
||||
ck "…while the settings file travels (secret blanked)" \
|
||||
"zipq '$SCRATCH/transfer.zip' has plugins/contact.yml && ! zipq '$SCRATCH/transfer.zip' read plugins/contact.yml | grep -q 'ENC('"
|
||||
ck "the full backup's manifest omits nothing of contact" "! grep -q 'plugins/contact/submissions.tsv' '$SCRATCH/full-manifest.yml'"
|
||||
|
||||
echo "== CAPTCHA still enforced on the anonymous POST (protection plugin, one site) =="
|
||||
if [ "$PROTECTION" = "yes" ]; then
|
||||
CTSV="$SITES/captcha/plugins/contact/submissions.tsv"
|
||||
CURL_C="http://captcha.test:$PORT"
|
||||
curl -s --resolve "captcha.test:$PORT:127.0.0.1" "$CURL_C/about" > "$SCRATCH/captcha-about.html"
|
||||
ck "the form carries the site's CAPTCHA challenge" \
|
||||
"grep -q 'data-sitekey=\"verify-site-key\"' '$SCRATCH/captcha-about.html' && grep -q 'method=\"post\" action=\"/contact/submit\"' '$SCRATCH/captcha-about.html'"
|
||||
ck "a POST without the CAPTCHA token -> ?contact=captcha" \
|
||||
"post --resolve 'captcha.test:$PORT:127.0.0.1' '$CURL_C/contact/submit' -d 'return=/about&name=Cy&email=cy%40example.com&message=no%20token&website=' | grep -q '/about?contact=captcha'"
|
||||
ck "a POST with a blank CAPTCHA token -> ?contact=captcha" \
|
||||
"post --resolve 'captcha.test:$PORT:127.0.0.1' '$CURL_C/contact/submit' -d 'return=/about&name=Cy&email=cy%40example.com&message=blank&website=&g-recaptcha-response=' | grep -q 'contact=captcha'"
|
||||
ck "a filled honeypot on that site still fakes success" \
|
||||
"post --resolve 'captcha.test:$PORT:127.0.0.1' '$CURL_C/contact/submit' -d 'return=/about&name=Bot&email=b%40example.com&message=x&website=http://spam' | grep -q 'contact=sent'"
|
||||
ck "nothing was stored for the CAPTCHA site" "[ \"\$(lines '$CTSV')\" = 0 ]"
|
||||
else
|
||||
skip "CAPTCHA checks (no built protection plugin at '$PROTECTION_DIR')"
|
||||
fi
|
||||
|
||||
echo; echo "RESULT: $PASS passed, $FAIL failed, $SKIP skipped"
|
||||
if [ "$KEEP" = "yes" ]; then echo "[verify] kept at $BASE (scratch $SCRATCH; kill $PID to stop)"; wait "$PID"; fi
|
||||
exit "$FAIL"
|
||||
@@ -0,0 +1,69 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import java.util.List;
|
||||
import mx.quest.runway.spi.service.SitePages;
|
||||
|
||||
/**
|
||||
* Read-only status model for the console surfaces (dashboard card + admin fragment), read by template bean name,
|
||||
* e.g. {@code ${@contactAdminModel.count(tenantSiteId)}} and iterated for the recent-submissions table. Also
|
||||
* exposes the SMTP <b>readiness</b> ({@link #smtpConfigured(String)}) and the test-action URL so the admin
|
||||
* fragment can show "Configured / Not configured" and offer the operator-only SMTP self-test, plus the
|
||||
* ready-made-page <b>install status</b> ({@link #pageInstalled(String)} / {@link #pagePath(String)}) — read
|
||||
* fresh from the kernel's {@link SitePages#pathOf} so a moved/renamed page reports its current path. Gated in the console
|
||||
* by the plugin's {@code settings} control point.
|
||||
*/
|
||||
public class ContactAdminModel {
|
||||
|
||||
private static final int RECENT = 20;
|
||||
|
||||
private final ContactStore store;
|
||||
private final ContactMailer mailer;
|
||||
private final SitePages pages;
|
||||
|
||||
public ContactAdminModel(ContactStore store, ContactMailer mailer, SitePages pages) {
|
||||
this.store = store;
|
||||
this.mailer = mailer;
|
||||
this.pages = pages;
|
||||
}
|
||||
|
||||
/** Total stored submissions for the site. */
|
||||
public int count(String siteId) {
|
||||
return store.count(siteId);
|
||||
}
|
||||
|
||||
/** The most recent submissions (newest first) for the admin listing. */
|
||||
public List<ContactSubmission> recent(String siteId) {
|
||||
return store.recent(siteId, RECENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this site has a usable SMTP relay (a non-blank host AND recipient). When false, submissions are
|
||||
* stored only — the readiness badge shows "Not configured" and no email is sent.
|
||||
*/
|
||||
public boolean smtpConfigured(String siteId) {
|
||||
return mailer.settingsFor(siteId).isConfigured();
|
||||
}
|
||||
|
||||
/** The recipient address configured for this site (for display), or an empty string when none is set. */
|
||||
public String recipient(String siteId) {
|
||||
return mailer.settingsFor(siteId).to();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this site already has the ready-made contact page (the one {@code /contact/install-page} seeds).
|
||||
* Read fresh through {@link SitePages#pathOf} by the installer's stable slug, in any state (a draft or a page
|
||||
* waiting for review counts), so it stays true even after the operator moves or renames the page (the slug is
|
||||
* the page's identity; only its path changes).
|
||||
*/
|
||||
public boolean pageInstalled(String siteId) {
|
||||
return pages.pathOf(siteId, ContactEndpoint.INSTALLED_PAGE_SLUG).isPresent();
|
||||
}
|
||||
|
||||
/**
|
||||
* The current URL path of the installed contact page (e.g. {@code /contact}, or wherever the operator moved
|
||||
* it), or an empty string when it is not installed. Read live so the console always shows the real location.
|
||||
*/
|
||||
public String pagePath(String siteId) {
|
||||
return pages.pathOf(siteId, ContactEndpoint.INSTALLED_PAGE_SLUG).orElse("");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import mx.quest.runway.spi.CaptchaService;
|
||||
import mx.quest.runway.spi.ContentWidget;
|
||||
import mx.quest.runway.spi.EndpointContributor;
|
||||
import mx.quest.runway.spi.service.AccessCheck;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.PluginSiteFiles;
|
||||
import mx.quest.runway.spi.service.SitePages;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* The plugin's {@code mainClass} — the single {@code @Configuration} registered into the host context before
|
||||
* refresh. Beans are wired EXPLICITLY (no {@code @ComponentScan}). The package {@code mx.quest.contact} lives
|
||||
* OUTSIDE {@code mx.quest.runway} so the host never double-scans it.
|
||||
*
|
||||
* <p><b>SPI only.</b> Everything this plugin needs from the kernel arrives as an SPI service (SPI 1.0.0):
|
||||
* {@link PluginSettings} (this plugin's per-site settings, and the SMTP password secret in clear) and
|
||||
* {@link PluginSiteFiles} (this plugin's per-site folder, where submissions are kept) are bound to this plugin by
|
||||
* the jar this class was loaded from; {@link Messages}, {@link AccessCheck}, {@link SitePages} and the
|
||||
* {@link CaptchaService} are kernel singletons. Nothing outside {@code mx.quest.runway.spi} is linked.
|
||||
*
|
||||
* <p>The {@link ContactWidget} ({@code ContentWidget}) and {@link ContactEndpoint} ({@code EndpointContributor})
|
||||
* are list-collected SPIs — plain {@code @Bean}s, NEVER {@code @Primary}. Every bean name starts with the plugin
|
||||
* id ({@code contact…}), the kernel's rule for a bean namespace plugins share. The email seam is
|
||||
* {@link MailTransport} ({@link JakartaMailTransport} in production, using the Jakarta Mail stack the KERNEL
|
||||
* bundles as a core capability).
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class ContactConfig {
|
||||
|
||||
@Bean
|
||||
public ContactStore contactStore(PluginSiteFiles files) {
|
||||
return new ContactStore(files);
|
||||
}
|
||||
|
||||
/** The production send seam — delegates to {@code jakarta.mail.Transport} (the kernel bundles Jakarta Mail). */
|
||||
@Bean
|
||||
public MailTransport contactMailTransport() {
|
||||
return new JakartaMailTransport();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ContactMailer contactMailer(PluginSettings settings, MailTransport transport) {
|
||||
return new ContactMailer(settings, transport);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ContentWidget contactWidget(PluginSettings settings, Messages messages, CaptchaService captcha) {
|
||||
return new ContactWidget(settings, messages, captcha);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public EndpointContributor contactEndpoint(ContactStore store, ContactMailer mailer, PluginSettings settings,
|
||||
Messages messages, AccessCheck access, CaptchaService captcha,
|
||||
SitePages pages) {
|
||||
return new ContactEndpoint(store, mailer, settings, messages, access, captcha, pages);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ContactAdminModel contactAdminModel(ContactStore store, ContactMailer mailer, SitePages pages) {
|
||||
return new ContactAdminModel(store, mailer, pages);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.CaptchaService;
|
||||
import mx.quest.runway.spi.EndpointContributor;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.CaptchaWidget;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.InstallResult;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.spi.model.Route;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.StarterPage;
|
||||
import mx.quest.runway.spi.model.SurfacePosture;
|
||||
import mx.quest.runway.spi.service.AccessCheck;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.SitePages;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* The contact plugin's tiny request-handling surface — it owns <b>no visible page</b>. The contact form lives on a
|
||||
* normal, editable site page (via the {@link ContactWidget} anchor; the operator installs the ready-made one from
|
||||
* the plugin settings). This endpoint only:
|
||||
* <ul>
|
||||
* <li><b>{@code POST /contact/submit}</b> — an <b>anonymous</b> route ({@code Route.anonymousPost}): the kernel
|
||||
* exempts exactly this method and path from CSRF (a public form on a cacheable page has no session token),
|
||||
* hands it only {@code application/x-www-form-urlencoded} bodies and runs it with no principal. The fields
|
||||
* are read from the <b>form body only</b> — a field put in the query string is ignored, so a visitor's
|
||||
* personal data never has to travel in a URL. It stores + emails the submission, then answers {@code 303}
|
||||
* back to the page the form lives on (the {@code return} field, or the {@code Referer}) with a
|
||||
* {@code ?contact=sent|invalid|captcha|queued} flag the widget re-renders the outcome from. The abuse guards
|
||||
* stay in front of the store: a filled honeypot fakes success (stores/sends nothing), an invalid submission
|
||||
* or an unsolved CAPTCHA (verified with the kernel-gated {@code clientIp}) redirects with an error flag, and
|
||||
* the platform's per-address rate limit (the protection plugin's edge guard) applies to this path like any
|
||||
* other. A valid submission is <b>stored first</b> ({@link ContactStore}) and then <b>emailed</b> over the
|
||||
* site's own relay, so a send failure never loses the message. Any other method on this path is a 404.</li>
|
||||
* <li><b>{@code POST /contact/install-page}</b> — operator-gated ({@code contact|settings}): installs a real,
|
||||
* editable page carrying the contact-form widget through {@link SitePages#install}, which respects the
|
||||
* site's editorial level and never overwrites; the operator is told which of the outcomes happened.</li>
|
||||
* <li><b>{@code POST /contact/smtp-test}</b> — operator-gated SMTP self-test; an optional {@code to} field of the
|
||||
* form body overrides the recipient.</li>
|
||||
* </ul>
|
||||
* The two operator actions change something (a page is created, an email is sent), so they are <b>ordinary,
|
||||
* non-anonymous {@code POST} routes</b>: the kernel's tenant chain demands the console session's CSRF token on them
|
||||
* (the admin fragment's forms carry it), which is what stops another web site from triggering them through a
|
||||
* signed-in operator's browser with a link or an {@code <img>}. A {@code GET} on either path matches no route and
|
||||
* changes nothing (the kernel answers 404); {@link #handle} refuses any other method too, as a second line.
|
||||
* Neither action reads the query string.
|
||||
* Honors the per-site {@code enabled} setting (disabled ⇒ a submission is a no-op 404). All redirect targets are
|
||||
* validated as same-origin local paths.
|
||||
*/
|
||||
public class ContactEndpoint implements EndpointContributor {
|
||||
|
||||
/** The anonymous form-submission route; the {@link ContactForm} posts here. */
|
||||
static final String SUBMIT_PATH = "/contact/submit";
|
||||
static final String INSTALL_PATH = "/contact/install-page";
|
||||
static final String SMTP_TEST_PATH = "/contact/smtp-test";
|
||||
/** The slug/path the ready-made contact page is installed at (then owned + movable by the operator). */
|
||||
static final String INSTALLED_PAGE_SLUG = "contact";
|
||||
static final String SETTINGS_PERMISSION = "contact|settings";
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ContactEndpoint.class);
|
||||
|
||||
private final ContactStore store;
|
||||
private final ContactMailer mailer;
|
||||
private final PluginSettings settings;
|
||||
private final Messages messages;
|
||||
private final AccessCheck access;
|
||||
private final CaptchaService captcha;
|
||||
private final SitePages pages;
|
||||
|
||||
public ContactEndpoint(ContactStore store, ContactMailer mailer, PluginSettings settings, Messages messages,
|
||||
AccessCheck access, CaptchaService captcha, SitePages pages) {
|
||||
this.store = store;
|
||||
this.mailer = mailer;
|
||||
this.settings = settings;
|
||||
this.messages = messages;
|
||||
this.access = access;
|
||||
this.captcha = captcha;
|
||||
this.pages = pages;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "contact/form";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Route> routes() {
|
||||
// No public /contact PAGE — the form lives on a normal editable page. These are the submit handler + the
|
||||
// two operator actions; all safeDefault (noindex/no-store), never advertised or crawled. The operator
|
||||
// actions are POST and NOT anonymous: they change state, so the kernel's CSRF check must apply to them.
|
||||
return List.of(
|
||||
Route.anonymousPost(SUBMIT_PATH, SurfacePosture.safeDefault()),
|
||||
new Route("POST", INSTALL_PATH, Realm.TENANT, SurfacePosture.safeDefault()),
|
||||
new Route("POST", SMTP_TEST_PATH, Realm.TENANT, SurfacePosture.safeDefault()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public RouteResponse handle(RouteRequest req) {
|
||||
// Every route here is POST-only; the kernel dispatches by method + path, and this check is the second line.
|
||||
if (!"POST".equalsIgnoreCase(req.method())) {
|
||||
return RouteResponse.notFound();
|
||||
}
|
||||
return switch (req.path()) {
|
||||
case SUBMIT_PATH -> handleSubmit(req);
|
||||
case INSTALL_PATH -> handleInstallPage(req);
|
||||
case SMTP_TEST_PATH -> handleSmtpTest(req);
|
||||
default -> RouteResponse.notFound();
|
||||
};
|
||||
}
|
||||
|
||||
/** Stores + emails a submission, then redirects back to the form's page with an outcome flag. */
|
||||
private RouteResponse handleSubmit(RouteRequest req) {
|
||||
String siteId = req.site().id();
|
||||
if (!settings.site(siteId).bool("enabled", true)) {
|
||||
return RouteResponse.notFound();
|
||||
}
|
||||
String back = resolveReturn(req);
|
||||
String name = formField(req, "name");
|
||||
String email = formField(req, "email");
|
||||
String message = formField(req, "message");
|
||||
String honeypot = formField(req, "website");
|
||||
|
||||
if (!honeypot.isBlank()) {
|
||||
return redirect(back, "sent"); // a bot filled the trap — fake success, store/send nothing
|
||||
}
|
||||
if (message.isBlank() || !isEmail(email)) {
|
||||
return redirect(back, "invalid");
|
||||
}
|
||||
CaptchaWidget widget = captcha.widgetForSite(siteId);
|
||||
if (widget.active() && !captcha.verify(siteId, formField(req, widget.tokenField()), req.clientIp())) {
|
||||
return redirect(back, "captcha");
|
||||
}
|
||||
// Belt-and-suspenders: STORE first (never lose a message), THEN email over the site's relay.
|
||||
store.add(siteId, name, email, message, System.currentTimeMillis());
|
||||
MailSendResult sent = mailer.send(siteId, req.site().displayName(), name, email, message);
|
||||
// "queued" ⇒ stored but the configured relay failed (an unobtrusive "delivery delayed" note); NOT_CONFIGURED
|
||||
// is silent (the site simply stores messages) — so only a real relay failure downgrades to "queued".
|
||||
boolean delayed = sent != null && !sent.wasSent()
|
||||
&& sent.status() != MailSendResult.Status.NOT_CONFIGURED;
|
||||
return redirect(back, delayed ? "queued" : "sent");
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs the ready-made, editable contact page (idempotent). {@code POST} only, CSRF-checked by the kernel;
|
||||
* operator-gated, failing closed with a 404.
|
||||
*/
|
||||
private RouteResponse handleInstallPage(RouteRequest req) {
|
||||
if (!access.may(SETTINGS_PERMISSION)) {
|
||||
return RouteResponse.notFound();
|
||||
}
|
||||
String siteId = req.site().id();
|
||||
Locale siteDefault = req.site().defaultLocale();
|
||||
String title = messages.site(siteId, siteDefault, "contact.page.title", "Contact");
|
||||
StarterPage page = new StarterPage(INSTALLED_PAGE_SLUG, "/" + INSTALLED_PAGE_SLUG,
|
||||
Map.of(siteDefault.getLanguage(), title), installedPageHtml(title), installedPageLogic(), false);
|
||||
InstallResult result;
|
||||
try {
|
||||
result = pages.install(siteId, page);
|
||||
} catch (RuntimeException e) {
|
||||
// IllegalStateException: a path another page serves, an unknown site, a failed write (no stray draft
|
||||
// is left behind). Anything else is equally "not installed" to the operator.
|
||||
log.warn("contact page install failed for site {}: {}", siteId, e.toString());
|
||||
return RouteResponse.text(500, console("contact.page.failed", "Could not install the contact page."));
|
||||
}
|
||||
return RouteResponse.text(200, describe(result));
|
||||
}
|
||||
|
||||
/** The operator's words for each install outcome; an outcome added in a later SPI MINOR gets a neutral line. */
|
||||
private String describe(InstallResult result) {
|
||||
String path = result.path();
|
||||
return switch (result.outcome()) {
|
||||
case PUBLISHED -> console("contact.page.installed", "Contact page installed at") + " " + path;
|
||||
case PENDING_REVIEW -> console("contact.page.pending",
|
||||
"The contact page was created and is waiting in the review queue:") + " " + path;
|
||||
case DRAFT_BLOCKED -> {
|
||||
StringBuilder text = new StringBuilder(console("contact.page.blocked",
|
||||
"The contact page was created as a draft because the quality checks blocked publishing; "
|
||||
+ "fix it in the page editor:")).append(' ').append(path);
|
||||
for (Finding finding : result.blocking()) {
|
||||
text.append("\n- ").append(finding.code()).append(": ").append(finding.message());
|
||||
}
|
||||
yield text.toString();
|
||||
}
|
||||
case ALREADY_EXISTS -> console("contact.page.exists", "A contact page already exists at") + " " + path;
|
||||
default -> console("contact.page.other", "The contact page install finished:") + " "
|
||||
+ result.outcome() + " " + path;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The operator-only SMTP self-test ({@code POST}, CSRF-checked by the kernel) — fails closed unless the caller
|
||||
* holds {@code contact|settings}.
|
||||
*/
|
||||
private RouteResponse handleSmtpTest(RouteRequest req) {
|
||||
if (!access.may(SETTINGS_PERMISSION)) {
|
||||
return RouteResponse.notFound();
|
||||
}
|
||||
// The override recipient comes from the form body only — never the query string.
|
||||
MailSendResult result = mailer.sendTest(req.site().id(), req.site().displayName(), formField(req, "to"));
|
||||
String text = switch (result.status()) {
|
||||
case SENT -> console("contact.test.ok", "Test message sent.");
|
||||
case NOT_CONFIGURED -> console("contact.test.notConfigured", "No SMTP relay is configured for this site.");
|
||||
case PROVIDER_MISSING -> console("contact.test.providerMissing",
|
||||
"Mail libraries are not available on the server.");
|
||||
case FAILED -> console("contact.test.failed", "Test message failed:") + " " + result.detail();
|
||||
};
|
||||
return RouteResponse.text(result.wasSent() ? 200 : 502, text);
|
||||
}
|
||||
|
||||
/** The page the form lives on: the same-origin {@code return} field, else the {@code Referer} path, else "/". */
|
||||
private static String resolveReturn(RouteRequest req) {
|
||||
String fromField = safeLocalPath(formField(req, "return"));
|
||||
if (fromField != null) {
|
||||
return fromField;
|
||||
}
|
||||
String fromReferer = safeLocalPath(refererPath(req.headers().get("referer")));
|
||||
return fromReferer != null ? fromReferer : "/";
|
||||
}
|
||||
|
||||
/** The path (with query stripped) of a Referer, or {@code null} when absent. */
|
||||
private static String refererPath(String referer) {
|
||||
if (referer == null || referer.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
int scheme = referer.indexOf("://");
|
||||
String path = referer;
|
||||
if (scheme >= 0) {
|
||||
int slash = referer.indexOf('/', scheme + 3);
|
||||
path = slash < 0 ? "/" : referer.substring(slash);
|
||||
}
|
||||
int q = path.indexOf('?');
|
||||
return q < 0 ? path : path.substring(0, q);
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@code 303 See Other} back to {@code path} carrying only the outcome flag (never a submitted value); the
|
||||
* browser follows it with a GET and the widget on that page re-renders from the flag (post/redirect/get, so a
|
||||
* reload never resubmits).
|
||||
*/
|
||||
private static RouteResponse redirect(String path, String outcome) {
|
||||
String location = path + (path.contains("?") ? "&" : "?") + "contact=" + outcome;
|
||||
return new RouteResponse(303, Map.of("Location", location), new byte[0]);
|
||||
}
|
||||
|
||||
/** Reduces a candidate to a safe same-origin path (a single leading "/", no scheme/backslash/space/control). */
|
||||
private static String safeLocalPath(String p) {
|
||||
if (p == null || p.isBlank() || !p.startsWith("/") || p.startsWith("//") || p.contains("://")) {
|
||||
return null;
|
||||
}
|
||||
for (int i = 0; i < p.length(); i++) {
|
||||
char c = p.charAt(i);
|
||||
if (c < 0x20 || c == '\\' || c == ' ') {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
/**
|
||||
* The body of the installed page: chrome seams ({@code head}/{@code #site-header}/{@code #site-footer}, filled
|
||||
* from the master by {@link #installedPageLogic()}) and a {@code #content} carrying the contact-form widget
|
||||
* anchor. The anchor bears both an {@code id} and {@code data-widget="contact/form"} on one element (the
|
||||
* widget-binding contract), so the host renders the form in place.
|
||||
*/
|
||||
private static String installedPageHtml(String title) {
|
||||
String t = Html.escape(title);
|
||||
return "<!DOCTYPE html>\n<html>\n<head><title>" + t + "</title></head>\n<body>\n"
|
||||
+ "<header id=\"site-header\"></header>\n<main id=\"content\">\n"
|
||||
+ " <h1 id=\"contact-page-title\">" + t + "</h1>\n"
|
||||
+ " <div id=\"contact-form\" data-widget=\"contact/form\"></div>\n"
|
||||
+ "</main>\n<footer id=\"site-footer\"></footer>\n</body>\n</html>\n";
|
||||
}
|
||||
|
||||
/** The decoupled logic of the installed page: pulls the master chrome via {@code ${master}} (never a literal). */
|
||||
private static String installedPageLogic() {
|
||||
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<thlogic>\n"
|
||||
+ " <attr sel=\"head\" th:replace=\"~{${master} :: head}\"/>\n"
|
||||
+ " <attr sel=\"#site-header\" th:replace=\"~{${master} :: #site-header}\"/>\n"
|
||||
+ " <attr sel=\"#site-footer\" th:replace=\"~{${master} :: #site-footer}\"/>\n"
|
||||
+ " <attr sel=\"#contact-page-title\" th:text=\"${pageTitle}\"/>\n"
|
||||
+ "</thlogic>\n";
|
||||
}
|
||||
|
||||
private static boolean isEmail(String value) {
|
||||
int at = value.indexOf('@');
|
||||
return at > 0 && at < value.length() - 1 && value.indexOf('.', at) > at;
|
||||
}
|
||||
|
||||
/** A field of the form BODY (never the query string), stripped; "" when absent. */
|
||||
private static String formField(RouteRequest req, String name) {
|
||||
List<String> values = req.form().get(name);
|
||||
return (values == null || values.isEmpty()) ? "" : values.get(0).strip();
|
||||
}
|
||||
|
||||
private String console(String code, String fallback) {
|
||||
return messages.console(code, fallback);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("endpoint.tenant", "contact.form");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import java.util.Locale;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
|
||||
/**
|
||||
* Builds the contact-form markup the {@link ContactWidget} renders inline on a page. The form <b>POSTs</b> an
|
||||
* {@code application/x-www-form-urlencoded} body to {@value ContactEndpoint#SUBMIT_PATH}, a route the
|
||||
* {@link ContactEndpoint} declares <b>anonymous</b> ({@code Route.anonymousPost}): the kernel exempts exactly that
|
||||
* method and path from CSRF, because a public form on a cacheable page cannot carry a per-session token. So the
|
||||
* visitor's name, email and message travel in the request body — never in a URL, browser history, a
|
||||
* {@code Referer} or a proxy log. A hidden honeypot field ({@code website}) catches naive bots; {@code captchaHtml}
|
||||
* (when non-empty) adds the site's CAPTCHA challenge from the platform's {@code CaptchaService} — trusted,
|
||||
* pre-rendered markup. Every label is looked up with {@link Messages#site} for the visitor's locale; every value
|
||||
* that came from a request or a setting is HTML-escaped.
|
||||
*/
|
||||
final class ContactForm {
|
||||
|
||||
private ContactForm() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the contact form. It submits to the anonymous {@code POST} handler, which stores + emails the message
|
||||
* and answers {@code 303} back to {@code returnPath} with a {@code ?contact=sent|invalid|captcha|queued} flag —
|
||||
* so the visible page stays a normal, editable site page (the widget re-renders the outcome from that flag).
|
||||
*/
|
||||
static String render(Messages messages, String siteId, Locale locale, String error, String captchaHtml,
|
||||
String returnPath) {
|
||||
String nameLbl = messages.site(siteId, locale, "contact.form.name", "Name");
|
||||
String emailLbl = messages.site(siteId, locale, "contact.form.email", "Email");
|
||||
String messageLbl = messages.site(siteId, locale, "contact.form.message", "Message");
|
||||
String submitLbl = messages.site(siteId, locale, "contact.form.submit", "Send");
|
||||
|
||||
StringBuilder b = new StringBuilder(768);
|
||||
b.append("<link rel=\"stylesheet\" href=\"/__plugin/contact/static/contact.css\">")
|
||||
.append("<form class=\"rw-contact\" method=\"post\" action=\"").append(ContactEndpoint.SUBMIT_PATH)
|
||||
.append("\" enctype=\"application/x-www-form-urlencoded\">")
|
||||
// Where the submit handler redirects back to (this page); validated server-side as a local path.
|
||||
.append("<input type=\"hidden\" name=\"return\" value=\"").append(Html.escape(returnPath)).append("\">");
|
||||
if (error != null && !error.isBlank()) {
|
||||
b.append("<p class=\"rw-contact-error\">").append(Html.escape(error)).append("</p>");
|
||||
}
|
||||
b.append(field("text", "name", nameLbl))
|
||||
.append(field("email", "email", emailLbl))
|
||||
.append("<label class=\"rw-contact-label\">").append(Html.escape(messageLbl))
|
||||
.append("<textarea class=\"rw-contact-input\" name=\"message\" rows=\"5\" required></textarea></label>")
|
||||
// Honeypot: hidden from humans, left blank; a bot that fills it is dropped as spam.
|
||||
.append("<div class=\"rw-contact-hp\" aria-hidden=\"true\">")
|
||||
.append("<label>Website<input type=\"text\" name=\"website\" tabindex=\"-1\" autocomplete=\"off\"></label></div>");
|
||||
// Real CAPTCHA challenge (only when the site configured one — trusted markup from the platform seam).
|
||||
if (captchaHtml != null && !captchaHtml.isBlank()) {
|
||||
b.append("<div class=\"rw-contact-captcha\">").append(captchaHtml).append("</div>");
|
||||
}
|
||||
b.append("<button class=\"rw-contact-submit\" type=\"submit\">").append(Html.escape(submitLbl))
|
||||
.append("</button></form>");
|
||||
return b.toString();
|
||||
}
|
||||
|
||||
private static String field(String type, String fieldName, String label) {
|
||||
return "<label class=\"rw-contact-label\">" + Html.escape(label)
|
||||
+ "<input class=\"rw-contact-input\" type=\"" + type + "\" name=\"" + fieldName + "\" required></label>";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import jakarta.mail.Authenticator;
|
||||
import jakarta.mail.Message;
|
||||
import jakarta.mail.MessagingException;
|
||||
import jakarta.mail.PasswordAuthentication;
|
||||
import jakarta.mail.Session;
|
||||
import jakarta.mail.internet.InternetAddress;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Properties;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Builds and sends the notification email for a contact submission over the <b>site's own</b> SMTP relay, then
|
||||
* reports the outcome as a {@link MailSendResult}. It NEVER stores anything and NEVER throws for an operational
|
||||
* failure — the {@link ContactEndpoint} always stores the submission first, so a relay problem degrades to a
|
||||
* reported (not lost) message.
|
||||
*
|
||||
* <p><b>Isolation.</b> The relay coordinates come only from {@link SmtpSettings#from} over this site's settings
|
||||
* ({@link PluginSettings}, bound by the kernel to this plugin), so a site sends exclusively through the relay it
|
||||
* configured (a tenant can never send through another's). The password is the site's {@code smtpPassword} secret,
|
||||
* read in clear with {@link PluginSettings#secret} at send time and never kept.
|
||||
*
|
||||
* <p><b>Degrade-don't-crash.</b> Three non-fatal outcomes are reported rather than thrown:
|
||||
* <ul>
|
||||
* <li>{@link MailSendResult#notConfigured()} — no host/recipient set (nothing to send to);</li>
|
||||
* <li>{@link MailSendResult#providerMissing()} — the Jakarta Mail classes are not on the classloader (a
|
||||
* {@link NoClassDefFoundError}/{@link LinkageError} at the seam). The kernel now bundles Jakarta Mail as a
|
||||
* core capability, so this is effectively unreachable; the guard is kept purely so a broken deployment can
|
||||
* never crash the request;</li>
|
||||
* <li>{@link MailSendResult#failed(String)} — a configured relay rejected the message or was unreachable.</li>
|
||||
* </ul>
|
||||
* The build/send seam is {@link MailTransport}, injected so tests exercise the full MIME build against a mock
|
||||
* with no socket opened.
|
||||
*/
|
||||
public class ContactMailer {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ContactMailer.class);
|
||||
private static final int MAX_SUBJECT_SOURCE = 120;
|
||||
/** The declared {@code type: secret} key of the SMTP password (plugin.yml). */
|
||||
static final String PASSWORD_KEY = "smtpPassword";
|
||||
|
||||
private final PluginSettings settings;
|
||||
private final MailTransport transport;
|
||||
|
||||
public ContactMailer(PluginSettings settings, MailTransport transport) {
|
||||
this.settings = settings;
|
||||
this.transport = transport;
|
||||
}
|
||||
|
||||
/** This site's current SMTP settings (the secret password in clear). Used by the send and the readiness badge. */
|
||||
public SmtpSettings settingsFor(String siteId) {
|
||||
return SmtpSettings.from(settings.site(siteId), settings.secret(siteId, PASSWORD_KEY));
|
||||
}
|
||||
|
||||
/**
|
||||
* Emails a stored submission's contents to the site's recipient. Never throws for an operational failure —
|
||||
* the outcome is always a {@link MailSendResult}.
|
||||
*
|
||||
* @param siteId the bound site (its own relay is used)
|
||||
* @param displayName the site's display name (for the subject / body context)
|
||||
* @param name the submitter's name
|
||||
* @param email the submitter's email (used as Reply-To so a reply reaches the visitor)
|
||||
* @param message the message body
|
||||
*/
|
||||
public MailSendResult send(String siteId, String displayName, String name, String email, String message) {
|
||||
SmtpSettings smtp = settingsFor(siteId);
|
||||
if (!smtp.isConfigured()) {
|
||||
return MailSendResult.notConfigured();
|
||||
}
|
||||
String subject = "[" + displayName + "] " + subjectExcerpt(name, message);
|
||||
String body = "New contact submission on " + displayName + "\n\n"
|
||||
+ "Name: " + orDash(name) + "\n"
|
||||
+ "Email: " + orDash(email) + "\n\n"
|
||||
+ message;
|
||||
return dispatch(smtp, smtp.effectiveFrom(), smtp.to(), subject, body, blankToNull(email));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a diagnostic test message to {@code testTo} over the site's relay, to verify the SMTP configuration
|
||||
* from the console. Same degrade contract as {@link #send} — the outcome is reported, never thrown.
|
||||
*/
|
||||
public MailSendResult sendTest(String siteId, String displayName, String testTo) {
|
||||
SmtpSettings smtp = settingsFor(siteId);
|
||||
// A test still needs a usable relay (host + a configured recipient) even though we override the To.
|
||||
if (!smtp.isConfigured()) {
|
||||
return MailSendResult.notConfigured();
|
||||
}
|
||||
String to = (testTo == null || testTo.isBlank()) ? smtp.to() : testTo.strip();
|
||||
String body = "This is a test message from the Runway contact plugin for site '" + displayName + "'.\n"
|
||||
+ "If you received it, the site's SMTP relay is configured correctly.";
|
||||
return dispatch(smtp, smtp.effectiveFrom(), to, "[" + displayName + "] SMTP test", body, null);
|
||||
}
|
||||
|
||||
private MailSendResult dispatch(SmtpSettings smtp, String from, String to, String subject, String body,
|
||||
String replyTo) {
|
||||
try {
|
||||
MimeMessage msg = build(smtp, from, to, subject, body, replyTo);
|
||||
transport.send(msg);
|
||||
return MailSendResult.sent();
|
||||
} catch (MessagingException e) {
|
||||
log.warn("contact mail send failed for relay {}: {}", smtp, e.toString());
|
||||
return MailSendResult.failed(rootMessage(e));
|
||||
} catch (LinkageError e) {
|
||||
// Jakarta Mail not on the classpath. The kernel bundles it as a core capability, so this is
|
||||
// effectively unreachable; guard it anyway so a broken deployment never crashes the request.
|
||||
log.warn("contact mail send skipped: Jakarta Mail unavailable on the classloader: {}", e.toString());
|
||||
return MailSendResult.providerMissing();
|
||||
}
|
||||
}
|
||||
|
||||
/** Builds the MIME message from the site's relay settings. Package-visible for direct MIME-shape testing. */
|
||||
MimeMessage build(SmtpSettings smtp, String from, String to, String subject, String body, String replyTo)
|
||||
throws MessagingException {
|
||||
Session session = session(smtp);
|
||||
MimeMessage msg = new MimeMessage(session);
|
||||
msg.setFrom(new InternetAddress(from));
|
||||
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
|
||||
if (replyTo != null) {
|
||||
try {
|
||||
msg.setReplyTo(InternetAddress.parse(replyTo, false));
|
||||
} catch (MessagingException badReplyTo) {
|
||||
// A visitor-supplied email that isn't a valid address must not block the notification.
|
||||
log.debug("ignoring invalid Reply-To '{}': {}", replyTo, badReplyTo.toString());
|
||||
}
|
||||
}
|
||||
msg.setSubject(subject, StandardCharsets.UTF_8.name());
|
||||
msg.setText(body, StandardCharsets.UTF_8.name());
|
||||
return msg;
|
||||
}
|
||||
|
||||
/**
|
||||
* A Jakarta Mail {@link Session} from the relay settings (host/port, TLS mode + auth).
|
||||
*
|
||||
* <p><b>The protocol is always {@code smtp}, even for implicit TLS.</b> We send with the static
|
||||
* {@link jakarta.mail.Transport#send(jakarta.mail.Message)}, which resolves an {@code rfc822} recipient to
|
||||
* the {@code smtp} transport via Jakarta Mail's address map — that lookup <b>ignores</b>
|
||||
* {@code mail.transport.protocol}. Selecting {@code smtps} therefore leaves {@code mail.smtp.host} unset, so
|
||||
* the send silently dials {@code localhost:25} and fails with "Connection refused". Implicit TLS (SMTPS, e.g.
|
||||
* port 465) must instead ride {@code mail.smtp.ssl.enable}; explicit TLS (e.g. 587) rides
|
||||
* {@code mail.smtp.starttls.enable}. Package-visible so a test can assert the resolved properties.
|
||||
*/
|
||||
static Session session(SmtpSettings smtp) {
|
||||
boolean ssl = smtp.ssl();
|
||||
Properties props = new Properties();
|
||||
props.put("mail.transport.protocol", "smtp");
|
||||
props.put("mail.smtp.host", smtp.host());
|
||||
props.put("mail.smtp.port", String.valueOf(smtp.port()));
|
||||
props.put("mail.smtp.auth", String.valueOf(smtp.auth()));
|
||||
if (ssl) {
|
||||
props.put("mail.smtp.ssl.enable", "true"); // implicit TLS on connect (SMTPS, e.g. 465)
|
||||
} else {
|
||||
props.put("mail.smtp.starttls.enable", String.valueOf(smtp.starttls())); // opportunistic STARTTLS (e.g. 587)
|
||||
}
|
||||
if (smtp.auth()) {
|
||||
Authenticator auth = new Authenticator() {
|
||||
@Override
|
||||
protected PasswordAuthentication getPasswordAuthentication() {
|
||||
return new PasswordAuthentication(smtp.username(), smtp.password());
|
||||
}
|
||||
};
|
||||
return Session.getInstance(props, auth);
|
||||
}
|
||||
return Session.getInstance(props);
|
||||
}
|
||||
|
||||
private static String subjectExcerpt(String name, String message) {
|
||||
String source = (name != null && !name.isBlank()) ? name : message;
|
||||
String s = source == null ? "message" : source.strip().replaceAll("\\s+", " ");
|
||||
if (s.isEmpty()) {
|
||||
s = "message";
|
||||
}
|
||||
return s.length() <= MAX_SUBJECT_SOURCE ? s : s.substring(0, MAX_SUBJECT_SOURCE).stripTrailing() + "…";
|
||||
}
|
||||
|
||||
private static String rootMessage(Throwable t) {
|
||||
Throwable cur = t;
|
||||
while (cur.getCause() != null && cur.getCause() != cur) {
|
||||
cur = cur.getCause();
|
||||
}
|
||||
String m = cur.getMessage();
|
||||
return (m == null || m.isBlank()) ? cur.getClass().getSimpleName() : m;
|
||||
}
|
||||
|
||||
private static String orDash(String value) {
|
||||
return (value == null || value.isBlank()) ? "—" : value.strip();
|
||||
}
|
||||
|
||||
private static String blankToNull(String value) {
|
||||
return (value == null || value.isBlank()) ? null : value.strip();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import mx.quest.runway.spi.service.PluginSiteFiles;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Persists contact-form submissions as tenant-owned data in this plugin's per-site folder, through the kernel's
|
||||
* {@link PluginSiteFiles}: {@value #FILE} under {@code sites/<id>/plugins/contact/}; an existing file is read and
|
||||
* appended in place. The folder is <b>outside</b> the served {@code static/} tree (never publicly downloadable) and
|
||||
* inside the site folder, so full backups carry it. The file holds what visitors typed, so {@code plugin.yml}
|
||||
* declares it <b>personal data</b> ({@code siteData.personal}) and a transfer copy of the site leaves it out.
|
||||
*
|
||||
* <p>One tab-separated line per submission ({@code epochMillis \t name \t email \t message}); fields are
|
||||
* sanitized to strip tabs/newlines so the format stays unambiguous, and each field is capped at
|
||||
* {@value #MAX_FIELD} characters. The file is bounded to the most recent {@link #MAX_SUBMISSIONS}, so it stays
|
||||
* a few MiB — well under the kernel's per-write cap.
|
||||
*
|
||||
* <p><b>Concurrency.</b> Each kernel write is atomic, but appending is a read-modify-write, which the service
|
||||
* leaves to the plugin: it is serialized here per site (contact volume is low). <b>Failure.</b> A read failure
|
||||
* during {@link #add} aborts the append rather than rewriting the file from nothing (which would lose every
|
||||
* stored submission); the console reads ({@link #count}, {@link #recent}) degrade to empty with a warning so an
|
||||
* unreadable file never takes the settings screen down.
|
||||
*/
|
||||
public class ContactStore {
|
||||
|
||||
static final int MAX_SUBMISSIONS = 500;
|
||||
static final String FILE = "submissions.tsv";
|
||||
static final int MAX_FIELD = 4000;
|
||||
private static final Logger log = LoggerFactory.getLogger(ContactStore.class);
|
||||
|
||||
private final PluginSiteFiles files;
|
||||
private final ConcurrentMap<String, Object> locks = new ConcurrentHashMap<>();
|
||||
|
||||
public ContactStore(PluginSiteFiles files) {
|
||||
this.files = files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a submission (stamped {@code epochMillis}), keeping only the most recent {@link #MAX_SUBMISSIONS}.
|
||||
*
|
||||
* @throws UncheckedIOException when the file cannot be read or written (nothing is lost: an unreadable file is
|
||||
* left untouched)
|
||||
*/
|
||||
public void add(String siteId, String name, String email, String message, long epochMillis) {
|
||||
String line = epochMillis + "\t" + sanitize(name) + "\t" + sanitize(email) + "\t" + sanitize(message);
|
||||
synchronized (locks.computeIfAbsent(siteId, k -> new Object())) {
|
||||
try {
|
||||
List<String> lines = new ArrayList<>(rawLines(siteId));
|
||||
lines.add(line);
|
||||
if (lines.size() > MAX_SUBMISSIONS) {
|
||||
lines = lines.subList(lines.size() - MAX_SUBMISSIONS, lines.size());
|
||||
}
|
||||
files.writeText(siteId, FILE, String.join("\n", lines) + "\n");
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("storing a contact submission for site " + siteId, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The most recent submissions, newest first, at most {@code limit}; empty when the file cannot be read. */
|
||||
public List<ContactSubmission> recent(String siteId, int limit) {
|
||||
List<String> lines = new ArrayList<>(readableLines(siteId));
|
||||
Collections.reverse(lines);
|
||||
List<ContactSubmission> out = new ArrayList<>();
|
||||
for (String line : lines) {
|
||||
if (out.size() >= limit) {
|
||||
break;
|
||||
}
|
||||
ContactSubmission s = parse(line);
|
||||
if (s != null) {
|
||||
out.add(s);
|
||||
}
|
||||
}
|
||||
return List.copyOf(out);
|
||||
}
|
||||
|
||||
/** The total number of stored submissions; 0 when the file cannot be read. */
|
||||
public int count(String siteId) {
|
||||
return readableLines(siteId).size();
|
||||
}
|
||||
|
||||
private List<String> readableLines(String siteId) {
|
||||
try {
|
||||
return rawLines(siteId);
|
||||
} catch (IOException e) {
|
||||
log.warn("contact submissions of site {} could not be read: {}", siteId, e.toString());
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> rawLines(String siteId) throws IOException {
|
||||
return files.readText(siteId, FILE)
|
||||
.map(text -> List.of(text.split("\n")).stream().filter(l -> !l.isBlank()).toList())
|
||||
.orElse(List.of());
|
||||
}
|
||||
|
||||
private static ContactSubmission parse(String line) {
|
||||
String[] p = line.split("\t", 4);
|
||||
if (p.length < 4) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return new ContactSubmission(Long.parseLong(p[0].trim()), p[1], p[2], p[3]);
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String sanitize(String value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
String s = value.replace('\t', ' ').replace('\r', ' ').replace('\n', ' ').strip();
|
||||
return s.length() > MAX_FIELD ? s.substring(0, MAX_FIELD) : s;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
/**
|
||||
* One stored contact-form submission. Immutable; fields are already sanitized (no tabs/newlines) by
|
||||
* {@link ContactStore} so the on-disk TSV format stays unambiguous.
|
||||
*
|
||||
* @param epochMillis when it was received
|
||||
* @param name the submitter's name
|
||||
* @param email the submitter's email
|
||||
* @param message the message (newlines collapsed to spaces on storage)
|
||||
*/
|
||||
public record ContactSubmission(long epochMillis, String name, String email, String message) {
|
||||
|
||||
private static final DateTimeFormatter WHEN =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(ZoneId.systemDefault());
|
||||
|
||||
/** A {@code yyyy-MM-dd HH:mm} timestamp for display. */
|
||||
public String time() {
|
||||
return WHEN.format(Instant.ofEpochMilli(epochMillis));
|
||||
}
|
||||
|
||||
/** A short excerpt of the message for a listing cell. */
|
||||
public String excerpt() {
|
||||
String m = message == null ? "" : message.strip();
|
||||
return m.length() <= 80 ? m : m.substring(0, 80).stripTrailing() + "…";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import java.util.Locale;
|
||||
import mx.quest.runway.spi.CaptchaService;
|
||||
import mx.quest.runway.spi.ContentWidget;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.RenderFragment;
|
||||
import mx.quest.runway.spi.model.SettingsView;
|
||||
import mx.quest.runway.spi.model.WidgetView;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* The {@code contact} content widget: a site manager drops
|
||||
* {@code <div id="contact" data-widget="contact/form"></div>} on a page and the host renders the contact form
|
||||
* inline (it POSTs to the {@link ContactEndpoint}). Honors the per-site {@code enabled} setting (disabled ⇒
|
||||
* {@link RenderFragment#empty()}). The markup is the shared {@link ContactForm}; public text comes from
|
||||
* {@link Messages#site} in the visitor's locale.
|
||||
*/
|
||||
public class ContactWidget implements ContentWidget {
|
||||
|
||||
private final PluginSettings settings;
|
||||
private final Messages messages;
|
||||
private final CaptchaService captcha;
|
||||
|
||||
public ContactWidget(PluginSettings settings, Messages messages, CaptchaService captcha) {
|
||||
this.settings = settings;
|
||||
this.messages = messages;
|
||||
this.captcha = captcha;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "contact";
|
||||
}
|
||||
|
||||
@Override
|
||||
public RenderFragment render(WidgetView view) {
|
||||
String siteId = view.site().id();
|
||||
SettingsView config = settings.site(siteId);
|
||||
if (!config.bool("enabled", true)) {
|
||||
return RenderFragment.empty();
|
||||
}
|
||||
Locale locale = view.locale();
|
||||
// The submit handler redirects back here with ?contact=sent|invalid|captcha; the widget re-renders the
|
||||
// outcome from that flag. A pure read of the request — the store/send side effects live in the endpoint.
|
||||
String outcome = view.query().get("contact");
|
||||
if ("sent".equals(outcome) || "queued".equals(outcome)) {
|
||||
String success = config.string("successMessage",
|
||||
messages.site(siteId, locale, "contact.success", "Thanks — your message has been sent."));
|
||||
String html = "<p class=\"rw-contact-success\">" + Html.escape(success.strip()) + "</p>";
|
||||
if ("queued".equals(outcome)) {
|
||||
// Stored, but the site's relay failed: say so quietly, so the visitor does not send it again.
|
||||
html += "<p class=\"rw-contact-note\">" + Html.escape(messages.site(siteId, locale,
|
||||
"contact.note.stored", "Your message was received; email delivery is delayed.")) + "</p>";
|
||||
}
|
||||
return RenderFragment.of(html);
|
||||
}
|
||||
String error = null;
|
||||
if ("invalid".equals(outcome)) {
|
||||
error = messages.site(siteId, locale, "contact.error.invalid", "Please enter your email and a message.");
|
||||
} else if ("captcha".equals(outcome)) {
|
||||
error = messages.site(siteId, locale, "contact.error.captcha",
|
||||
"Please complete the challenge and try again.");
|
||||
}
|
||||
String captchaHtml = captcha.widgetForSite(siteId).html();
|
||||
// Land the visitor back on THIS page after submit: the request path as served (locale prefix and all),
|
||||
// from the view — NEVER built from the slug, which for a content source's page (a blog entry rendering
|
||||
// this widget in the master chrome) is a composite identity like "blog:my-post", not a path. The slug
|
||||
// form remains only as the legacy fallback for a host that predates WidgetView.path.
|
||||
String returnPath = view.path().isEmpty() ? "/" + view.page().slug() : view.path();
|
||||
return RenderFragment.of(ContactForm.render(messages, siteId, locale, error, captchaHtml, returnPath));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("widget.contact");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
/**
|
||||
* Minimal HTML escaping for the values the contact plugin interpolates into its form and its stored/echoed
|
||||
* submissions. The plugin owns escaping of its own output so a crafted name/email/message can never inject
|
||||
* markup into the form page, the thank-you page, or the admin listing.
|
||||
*/
|
||||
final class Html {
|
||||
|
||||
private Html() {
|
||||
}
|
||||
|
||||
static String escape(String value) {
|
||||
if (value == null || value.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
return value.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
.replace("\"", """).replace("'", "'");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import jakarta.mail.MessagingException;
|
||||
import jakarta.mail.Transport;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
|
||||
/**
|
||||
* The production {@link MailTransport}: hands the message to {@code jakarta.mail.Transport}, which resolves the
|
||||
* {@code smtp}/{@code smtps} provider from the message's {@link jakarta.mail.Session} (the Angus reference
|
||||
* implementation, discovered at runtime via {@code META-INF/services/jakarta.mail.Provider} — now supplied by
|
||||
* the KERNEL, which bundles the Jakarta Mail stack as a core capability and is reached parent-first from the
|
||||
* plugin classloader).
|
||||
*
|
||||
* <p>Authentication is carried on the {@code Session} the {@link ContactMailer} built (with {@code mail.smtp.auth}
|
||||
* and a static {@link jakarta.mail.Authenticator} when the relay requires it), so {@link Transport#send(jakarta.mail.Message)}
|
||||
* with the message alone is sufficient — no separate connect/credentials call. Stateless and thread-safe.
|
||||
*/
|
||||
public class JakartaMailTransport implements MailTransport {
|
||||
|
||||
@Override
|
||||
public void send(MimeMessage message) throws MessagingException {
|
||||
Transport.send(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
/**
|
||||
* The reported outcome of trying to email a contact submission. A submission is <b>always</b> stored first
|
||||
* (belt-and-suspenders), so this result is <em>advisory</em> — it never means the message was lost, only whether
|
||||
* the email went out. The {@link ContactEndpoint} uses it to decide what the visitor sees; the plugin logs a
|
||||
* failure but keeps the stored copy.
|
||||
*/
|
||||
public record MailSendResult(Status status, String detail) {
|
||||
|
||||
/** Which way the send went. */
|
||||
public enum Status {
|
||||
/** The message was handed to the site's SMTP relay successfully. */
|
||||
SENT,
|
||||
/** No relay is configured for this site (blank host or recipient) — nothing was sent, only stored. */
|
||||
NOT_CONFIGURED,
|
||||
/** Jakarta Mail is not on the classpath (a broken deployment; the kernel bundles it) — stored only. */
|
||||
PROVIDER_MISSING,
|
||||
/** A relay is configured but the send failed (rejected / unreachable / auth) — {@link #detail} says why. */
|
||||
FAILED
|
||||
}
|
||||
|
||||
/** The email was sent. */
|
||||
public static MailSendResult sent() {
|
||||
return new MailSendResult(Status.SENT, null);
|
||||
}
|
||||
|
||||
/** No SMTP relay configured for this site (stored only). */
|
||||
public static MailSendResult notConfigured() {
|
||||
return new MailSendResult(Status.NOT_CONFIGURED, null);
|
||||
}
|
||||
|
||||
/** Jakarta Mail is unavailable on the classloader (a broken deployment; stored only). */
|
||||
public static MailSendResult providerMissing() {
|
||||
return new MailSendResult(Status.PROVIDER_MISSING, null);
|
||||
}
|
||||
|
||||
/** The send failed for the given reason (stored only). */
|
||||
public static MailSendResult failed(String detail) {
|
||||
return new MailSendResult(Status.FAILED, detail);
|
||||
}
|
||||
|
||||
/** Whether the email actually went out (as opposed to being stored only). */
|
||||
public boolean wasSent() {
|
||||
return status == Status.SENT;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import jakarta.mail.MessagingException;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
|
||||
/**
|
||||
* The send seam: the single point where a built {@link MimeMessage} actually leaves the JVM over SMTP. Factored
|
||||
* out as an interface so the {@link ContactMailer}'s build-and-send logic can be unit-tested against a mock
|
||||
* transport with <b>no socket opened</b> (the production {@link JakartaMailTransport} delegates to
|
||||
* {@code jakarta.mail.Transport}).
|
||||
*
|
||||
* <p>Implementations MUST NOT swallow a failure — a broken relay has to be reported so the {@link ContactMailer}
|
||||
* can surface it (the stored copy of the submission still lands regardless). A {@link MessagingException} means
|
||||
* the send failed; returning normally means it was handed to the relay.
|
||||
*/
|
||||
public interface MailTransport {
|
||||
|
||||
/**
|
||||
* Sends an already-built, already-addressed message.
|
||||
*
|
||||
* @param message the MIME message to transmit (From/To/Subject/body all set by the caller)
|
||||
* @throws MessagingException if the relay rejected the message or could not be reached
|
||||
*/
|
||||
void send(MimeMessage message) throws MessagingException;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import mx.quest.runway.spi.model.SettingsView;
|
||||
|
||||
/**
|
||||
* The per-site SMTP relay configuration, materialized from a site's {@code contact} plugin settings (the
|
||||
* {@code smtp*} + {@code fromAddress}/{@code toAddress} {@code siteSettings}). Immutable; a pure value.
|
||||
*
|
||||
* <p><b>Isolation.</b> Every field comes from <em>this</em> site's own {@code sites/<id>/plugins/contact.yml};
|
||||
* a site can therefore only ever send through the relay <em>it</em> configured — never another tenant's.
|
||||
*
|
||||
* <p><b>Secret handling.</b> The password is a {@code secret} setting, stored {@code ENC(...)}-encrypted by the
|
||||
* platform. It never appears in the {@link SettingsView} (the kernel leaves secret keys out of it); the caller
|
||||
* hands it over separately, already in clear, from {@code PluginSettings.secret(siteId, "smtpPassword")}. The
|
||||
* plaintext lives only in this transient value and is handed straight to Jakarta Mail, never logged (see
|
||||
* {@link #toString()}) and never stored by this plugin.
|
||||
*
|
||||
* @param host the SMTP server host; blank ⇒ {@link #isConfigured()} is false (mail is skipped)
|
||||
* @param port the SMTP server port (1..65535; default 25)
|
||||
* @param auth whether to authenticate (SMTP AUTH) with {@code username}/{@code password}
|
||||
* @param username the SMTP username (used only when {@code auth})
|
||||
* @param password the SMTP password in PLAINTEXT (already decrypted; used only when {@code auth})
|
||||
* @param starttls whether to upgrade a plain connection with STARTTLS
|
||||
* @param ssl whether to open an implicit-TLS (SMTPS) connection
|
||||
* @param from the envelope/From address; blank ⇒ falls back to {@code to}
|
||||
* @param to the recipient address; blank ⇒ {@link #isConfigured()} is false (mail is skipped)
|
||||
*/
|
||||
public record SmtpSettings(String host, int port, boolean auth, String username, String password,
|
||||
boolean starttls, boolean ssl, String from, String to) {
|
||||
|
||||
/**
|
||||
* Reads the SMTP relay from a site's contact settings.
|
||||
*
|
||||
* @param view the site's effective contact settings ({@code PluginSettings.site}) — declared defaults
|
||||
* overlaid by what the operator saved; secret keys are absent from it by contract
|
||||
* @param password the {@code smtpPassword} secret in clear ({@code PluginSettings.secret}); empty when unset
|
||||
* or undecryptable — the relay then authenticates with a blank password and reports the failure
|
||||
* @return the materialized, immutable settings (never {@code null}); {@link #isConfigured()} reports usability
|
||||
*/
|
||||
public static SmtpSettings from(SettingsView view, Optional<String> password) {
|
||||
Objects.requireNonNull(view, "view");
|
||||
String host = text(view, "smtpHost");
|
||||
int port = (int) view.integer("smtpPort", 25L, 1, 65535);
|
||||
boolean auth = view.bool("smtpAuth", false);
|
||||
String username = text(view, "smtpUsername");
|
||||
String clear = password == null ? "" : password.orElse("");
|
||||
boolean starttls = view.bool("smtpStarttls", false);
|
||||
boolean ssl = view.bool("smtpSsl", false);
|
||||
String from = text(view, "fromAddress");
|
||||
String to = text(view, "toAddress");
|
||||
return new SmtpSettings(host, port, auth, username, clear, starttls, ssl, from, to);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether enough is set to attempt a send: a non-blank host AND a non-blank recipient. When false the
|
||||
* {@link ContactMailer} reports {@code NOT_CONFIGURED} and the submission is stored only (never lost).
|
||||
*/
|
||||
public boolean isConfigured() {
|
||||
return host != null && !host.isBlank() && to != null && !to.isBlank();
|
||||
}
|
||||
|
||||
/** The effective From address: the configured one, or the recipient when From is blank (a sane default). */
|
||||
public String effectiveFrom() {
|
||||
return (from == null || from.isBlank()) ? to : from;
|
||||
}
|
||||
|
||||
private static String text(SettingsView view, String key) {
|
||||
return view.string(key, "").strip();
|
||||
}
|
||||
|
||||
/** Never leak the password in logs / diagnostics. */
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SmtpSettings[host=" + host + ", port=" + port + ", auth=" + auth + ", username=" + username
|
||||
+ ", starttls=" + starttls + ", ssl=" + ssl + ", from=" + from + ", to=" + to
|
||||
+ ", password=" + (password == null || password.isBlank() ? "<none>" : "<set>") + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import mx.quest.runway.spi.model.Route;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The console side of the CSRF fix: every operator action the endpoint declares (a non-anonymous {@code POST}) is
|
||||
* reached from the admin fragment by a {@code <form method="post">} that carries the console session's CSRF token,
|
||||
* and no link points at it any more (a link is a {@code GET}, and a {@code GET} on those paths changes nothing).
|
||||
* The markup is read from {@code templates/} as shipped; the token binding from the sibling {@code .th.xml}.
|
||||
*/
|
||||
class ContactAdminTemplateTest {
|
||||
|
||||
private static final Pattern FORM = Pattern.compile("(?s)<form\\b([^>]*)>(.*?)</form>");
|
||||
private static final Pattern CSRF_INPUT =
|
||||
Pattern.compile("<input\\b[^>]*\\bid=\"([^\"]+)\"[^>]*\\bname=\"_csrf\"[^>]*>");
|
||||
private static final String TOKEN_BINDING =
|
||||
"th:attr=\"name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}\"";
|
||||
|
||||
private static String read(String file) throws IOException {
|
||||
return Files.readString(Path.of("templates", file), StandardCharsets.UTF_8).replaceAll("(?s)<!--.*?-->", "");
|
||||
}
|
||||
|
||||
private static List<String> operatorActions() {
|
||||
ContactEndpoint endpoint = new ContactEndpoint(null, null, new FakePluginSettings(), new FakeSiteServices(),
|
||||
new FakeSiteServices(), null, new FakeSiteServices());
|
||||
List<String> paths = new ArrayList<>();
|
||||
for (Route r : endpoint.routes()) {
|
||||
if (!r.anonymous()) {
|
||||
paths.add(r.pathPattern());
|
||||
}
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOperatorActionsAreTheInstallAndTheSmtpTest() {
|
||||
assertEquals(List.of("/contact/install-page", "/contact/smtp-test"), operatorActions());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyOperatorActionIsAPostFormCarryingTheCsrfToken() throws IOException {
|
||||
String html = read("admin.html");
|
||||
String logic = read("admin.th.xml");
|
||||
for (String action : operatorActions()) {
|
||||
Matcher form = FORM.matcher(html);
|
||||
boolean found = false;
|
||||
while (form.find()) {
|
||||
String attrs = form.group(1);
|
||||
if (!attrs.contains("action=\"" + action + "\"")) {
|
||||
continue;
|
||||
}
|
||||
found = true;
|
||||
assertTrue(attrs.contains("method=\"post\""), action + " must be submitted by POST: " + attrs);
|
||||
Matcher csrf = CSRF_INPUT.matcher(form.group(2));
|
||||
assertTrue(csrf.find(), action + "'s form carries a hidden _csrf field");
|
||||
String id = csrf.group(1);
|
||||
assertTrue(logic.contains("<attr sel=\"#" + id + "\"\n " + TOKEN_BINDING + "/>"),
|
||||
"#" + id + " is bound to the console session's CSRF token in admin.th.xml");
|
||||
}
|
||||
assertTrue(found, "the admin fragment has a form for " + action);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void noLinkPointsAtAnOperatorAction() throws IOException {
|
||||
String html = read("admin.html");
|
||||
for (String action : operatorActions()) {
|
||||
assertFalse(html.contains("href=\"" + action), "a link is a GET and would not carry the token: " + action);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAdminFragmentsIdsAreUnique() throws IOException {
|
||||
// A duplicate id in a decoupled template is a hard Thymeleaf error that would 500 the settings page.
|
||||
Matcher ids = Pattern.compile("\\bid=\"([^\"]+)\"").matcher(read("admin.html"));
|
||||
Set<String> seen = new HashSet<>();
|
||||
while (ids.find()) {
|
||||
assertTrue(seen.add(ids.group(1)), "duplicate id " + ids.group(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import mx.quest.runway.spi.CaptchaService;
|
||||
import mx.quest.runway.spi.ContentWidget;
|
||||
import mx.quest.runway.spi.EndpointContributor;
|
||||
import mx.quest.runway.spi.model.CaptchaWidget;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.PluginSiteFiles;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
|
||||
/**
|
||||
* The plugin's contract with the host, checked at build time: the wiring over SPI services only, the bean-name
|
||||
* rule, the bean names the templates reference, the descriptor (SPI floor, release version, the personal-data
|
||||
* declaration matching the file the store writes), the i18n bundles, and that the compiled classes link nothing of
|
||||
* the host but the SPI — the same things the kernel's load-time checks warn about (and refuse from Runway 1.0).
|
||||
*/
|
||||
class ContactConfigTest {
|
||||
|
||||
private static final String PREFIX = "contact";
|
||||
|
||||
private static Set<String> beanMethodNames() {
|
||||
return Arrays.stream(ContactConfig.class.getDeclaredMethods())
|
||||
.filter(m -> m.isAnnotationPresent(Bean.class))
|
||||
.map(Method::getName)
|
||||
.collect(Collectors.toCollection(TreeSet::new));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> descriptor() throws IOException {
|
||||
try (Reader in = Files.newBufferedReader(Path.of("plugin.yml"), StandardCharsets.UTF_8)) {
|
||||
return (Map<String, Object>) new Yaml().load(in);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void wiresEverythingFromSpiServicesUnderPrefixedNames(@TempDir Path sites) throws IOException {
|
||||
Files.createDirectories(sites.resolve("acme"));
|
||||
FakeSiteServices kernel = new FakeSiteServices()
|
||||
.site(new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null))
|
||||
.page("acme", "contact", "/kontakt");
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
|
||||
ctx.registerBean(PluginSettings.class, () -> new FakePluginSettings()
|
||||
.site("acme", Map.of("smtpHost", "mail.example.com", "toAddress", "owner@example.com")));
|
||||
ctx.registerBean(PluginSiteFiles.class, () -> new TempDirSiteFiles(sites, "contact"));
|
||||
ctx.registerBean(FakeSiteServices.class, () -> kernel);
|
||||
ctx.registerBean(CaptchaService.class, () -> new CaptchaService() {
|
||||
@Override
|
||||
public CaptchaWidget widgetForSite(String siteId) {
|
||||
return CaptchaWidget.inactive();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(String siteId, String token, String clientIp) {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
ctx.register(ContactConfig.class);
|
||||
ctx.refresh();
|
||||
|
||||
assertInstanceOf(ContactWidget.class, ctx.getBean("contactWidget", ContentWidget.class));
|
||||
assertInstanceOf(ContactEndpoint.class, ctx.getBean("contactEndpoint", EndpointContributor.class));
|
||||
ctx.getBean("contactStore", ContactStore.class).add("acme", "Ann", "a@example.com", "hi", 1L);
|
||||
ContactAdminModel model = ctx.getBean("contactAdminModel", ContactAdminModel.class);
|
||||
assertEquals(1, model.count("acme"), "the admin model reads the store over the injected site files");
|
||||
assertTrue(model.smtpConfigured("acme"), "…and the relay over the injected settings");
|
||||
assertEquals("/kontakt", model.pagePath("acme"), "…and the page through SitePages");
|
||||
assertTrue(model.pageInstalled("acme"));
|
||||
assertFalse(model.pageInstalled("other"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyBeanNameStartsWithThePluginIdInLowerCamelCase() {
|
||||
Set<String> names = beanMethodNames();
|
||||
assertEquals(Set.of("contactStore", "contactMailTransport", "contactMailer", "contactWidget",
|
||||
"contactEndpoint", "contactAdminModel"), names);
|
||||
for (Method m : ContactConfig.class.getDeclaredMethods()) {
|
||||
Bean bean = m.getAnnotation(Bean.class);
|
||||
if (bean != null) {
|
||||
for (String alias : bean.name()) {
|
||||
assertTrue(alias.startsWith(PREFIX), "an explicit bean name must start with " + PREFIX + ": " + alias);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyBeanTheTemplatesReferenceIsOneOfOurs() throws IOException {
|
||||
Set<String> referenced = new TreeSet<>();
|
||||
try (Stream<Path> files = Files.list(Path.of("templates"))) {
|
||||
for (Path file : files.filter(p -> p.toString().endsWith(".th.xml")).toList()) {
|
||||
// XML comments explain the ${@bean} rules in prose; only the live attributes count.
|
||||
String live = Files.readString(file, StandardCharsets.UTF_8).replaceAll("(?s)<!--.*?-->", "");
|
||||
Matcher m = Pattern.compile("\\$\\{\\s*!?\\s*@(\\w+)").matcher(live);
|
||||
while (m.find()) {
|
||||
referenced.add(m.group(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals(Set.of("contactAdminModel"), referenced, "the console templates read the admin model only");
|
||||
assertTrue(beanMethodNames().containsAll(referenced), "templates reference unknown beans: " + referenced);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDescriptorDeclaresTheSpiFloorAndTheReleaseVersion() throws IOException {
|
||||
Map<String, Object> yml = descriptor();
|
||||
assertEquals(">=1.0.0", yml.get("requiresSpi"), "built for the frozen SPI 1.0.0 contract");
|
||||
String pom = Files.readString(Path.of("pom.xml"), StandardCharsets.UTF_8);
|
||||
Matcher version = Pattern.compile("<artifactId>runway-plugin-contact</artifactId>\\s*<version>([^<]+)")
|
||||
.matcher(pom);
|
||||
assertTrue(version.find());
|
||||
assertEquals(version.group(1), String.valueOf(yml.get("version")), "plugin.yml and pom.xml agree on the version");
|
||||
assertFalse(pom.contains("<artifactId>runway-app</artifactId>"), "no runway-app dependency in any scope");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void theSubmissionsFileIsDeclaredPersonalDataSoTransferCopiesLeaveItOut() throws IOException {
|
||||
Map<String, Object> siteData = (Map<String, Object>) descriptor().get("siteData");
|
||||
assertTrue(siteData != null, "plugin.yml declares siteData");
|
||||
List<String> personal = (List<String>) siteData.get("personal");
|
||||
assertEquals(List.of(ContactStore.FILE), personal,
|
||||
"exactly the file the store writes (visitor names, emails, messages) is personal data");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSmtpPasswordIsDeclaredASecret() throws IOException {
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, Object>> schema = (List<Map<String, Object>>) descriptor().get("siteSettings");
|
||||
Map<String, Object> password = schema.stream()
|
||||
.filter(s -> ContactMailer.PASSWORD_KEY.equals(s.get("key"))).findFirst().orElseThrow();
|
||||
assertEquals("secret", password.get("type"),
|
||||
"PluginSettings.secret hands out only keys declared type: secret (and site() leaves them out)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSmtpPasswordIsBoundToTheRelayLogin() throws IOException {
|
||||
// secretBoundTo: a save that changes the relay's host, port or username without retyping the password makes
|
||||
// the kernel drop the stored password, so a settings editor cannot repoint the saved credentials at a server
|
||||
// of their choosing. Every bound key must be a declared setting, or the binding silently binds nothing.
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, Object>> schema = (List<Map<String, Object>>) descriptor().get("siteSettings");
|
||||
Map<String, Object> password = schema.stream()
|
||||
.filter(s -> ContactMailer.PASSWORD_KEY.equals(s.get("key"))).findFirst().orElseThrow();
|
||||
assertEquals(List.of("smtpHost", "smtpPort", "smtpUsername", "smtpStarttls", "smtpSsl"), password.get("secretBoundTo"),
|
||||
"the stored SMTP password is bound to the host, port and username it was typed for");
|
||||
List<Object> declared = schema.stream().map(s -> s.get("key")).toList();
|
||||
for (Object bound : (List<?>) password.get("secretBoundTo")) {
|
||||
assertTrue(declared.contains(bound), "secretBoundTo names a declared setting: " + bound);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEnglishAndSpanishBundlesDefineTheSameKeys() throws IOException {
|
||||
assertEquals(keys("i18n/messages.properties"), keys("i18n/messages_es.properties"));
|
||||
Set<String> en = keys("i18n/messages.properties");
|
||||
for (String key : List.of("contact.page.installed", "contact.page.pending", "contact.page.blocked",
|
||||
"contact.page.exists", "contact.page.failed", "contact.page.other")) {
|
||||
assertTrue(en.contains(key), "every install outcome has words: " + key);
|
||||
}
|
||||
}
|
||||
|
||||
private static Set<String> keys(String file) throws IOException {
|
||||
Properties p = new Properties();
|
||||
try (Reader in = Files.newBufferedReader(Path.of(file), StandardCharsets.UTF_8)) {
|
||||
p.load(in);
|
||||
}
|
||||
return new TreeSet<>(p.stringPropertyNames());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCompiledClassesLinkNoHostInternals() throws IOException {
|
||||
Path classes = Path.of("target", "classes");
|
||||
Pattern host = Pattern.compile("mx[/.]quest[/.]runway[/.](?!spi[/.])[\\w/.$]*");
|
||||
List<String> problems = new ArrayList<>();
|
||||
int scanned = 0;
|
||||
try (Stream<Path> files = Files.walk(classes)) {
|
||||
for (Path file : files.filter(p -> p.toString().endsWith(".class")).toList()) {
|
||||
scanned++;
|
||||
String rel = classes.relativize(file).toString().replace('\\', '/');
|
||||
if (rel.startsWith("mx/quest/runway/")) {
|
||||
problems.add(rel + " lives under mx.quest.runway");
|
||||
}
|
||||
// The constant pool holds class names and descriptors as (modified) UTF-8; Latin-1 keeps every
|
||||
// byte as one char, so an ASCII pattern finds them without parsing the class file.
|
||||
Matcher m = host.matcher(new String(Files.readAllBytes(file), StandardCharsets.ISO_8859_1));
|
||||
while (m.find()) {
|
||||
problems.add(rel + " → " + m.group());
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(scanned >= 12, "the compiled classes were found (" + scanned + ")");
|
||||
assertTrue(problems.isEmpty(), "host linkage: " + problems);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.CaptchaService;
|
||||
import mx.quest.runway.spi.model.CaptchaWidget;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.InstallResult;
|
||||
import mx.quest.runway.spi.model.Route;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.Severity;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.model.StarterPage;
|
||||
import mx.quest.runway.spi.service.SitePages;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The contact plugin's request surface — it owns <b>no visible page</b>. Covered here: the anonymous
|
||||
* {@code POST /contact/submit} handler (303 back to the form's page with a {@code ?contact=…} outcome; POST only,
|
||||
* fields from the body only; store-then-send ordering; honeypot, invalid and CAPTCHA gating with the gated client
|
||||
* IP; return-path safety), the operator-gated {@code POST /contact/install-page} with each {@code SitePages}
|
||||
* outcome, and the operator-gated {@code POST /contact/smtp-test}. Both operator actions change state, so they are
|
||||
* non-anonymous POST routes (the kernel's CSRF check applies) and a GET changes nothing. The form's HTML is covered
|
||||
* in {@link ContactWidgetTest}; the console forms that carry the CSRF token in {@link ContactAdminTemplateTest}.
|
||||
*/
|
||||
class ContactEndpointTest {
|
||||
|
||||
private static final SiteView ACME = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null);
|
||||
private static final String CLIENT_IP = "203.0.113.7";
|
||||
|
||||
private ContactStore store;
|
||||
private ContactMailer mailer;
|
||||
private FakePluginSettings settings;
|
||||
private FakeSiteServices kernel;
|
||||
private CaptchaService captcha;
|
||||
private ContactEndpoint endpoint;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
store = mock(ContactStore.class);
|
||||
mailer = mock(ContactMailer.class);
|
||||
when(mailer.send(anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(MailSendResult.sent());
|
||||
settings = new FakePluginSettings().defaults(Map.of("enabled", true));
|
||||
kernel = new FakeSiteServices().site(ACME).current("acme");
|
||||
captcha = mock(CaptchaService.class);
|
||||
// Default: no challenge configured (submissions flow through the non-CAPTCHA path).
|
||||
when(captcha.widgetForSite(any())).thenReturn(CaptchaWidget.inactive());
|
||||
endpoint = new ContactEndpoint(store, mailer, settings, kernel, kernel, captcha, kernel);
|
||||
}
|
||||
|
||||
private static RouteRequest request(String method, String path, Map<String, List<String>> query,
|
||||
Map<String, List<String>> form, Map<String, String> headers) {
|
||||
return new RouteRequest(ACME, Locale.ENGLISH, method, path, query, headers, new byte[0], form, CLIENT_IP,
|
||||
"https://acme.test");
|
||||
}
|
||||
|
||||
/** A POST /contact/submit with the given BODY fields; carries a {@code return} of /home. */
|
||||
private RouteResponse submit(Map<String, List<String>> fields) {
|
||||
Map<String, List<String>> form = new HashMap<>(fields);
|
||||
form.putIfAbsent("return", List.of("/home"));
|
||||
return endpoint.handle(request("POST", "/contact/submit", Map.of(), form, Map.of()));
|
||||
}
|
||||
|
||||
private static Map<String, List<String>> valid() {
|
||||
return Map.of("name", List.of("Ann"), "email", List.of("ann@example.com"),
|
||||
"message", List.of("Hello there"), "website", List.of(""));
|
||||
}
|
||||
|
||||
private static Map<String, List<String>> with(Map<String, List<String>> base, String key, String value) {
|
||||
Map<String, List<String>> copy = new HashMap<>(base);
|
||||
copy.put(key, List.of(value));
|
||||
return copy;
|
||||
}
|
||||
|
||||
private static String location(RouteResponse res) {
|
||||
return res.headers().get("Location");
|
||||
}
|
||||
|
||||
private static String text(RouteResponse res) {
|
||||
return new String(res.body(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private void verifyNothingStoredOrSent() {
|
||||
verify(store, never()).add(anyString(), anyString(), anyString(), anyString(), anyLong());
|
||||
verify(mailer, never()).send(anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
// ---- routes ----------------------------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void theSubmitRouteIsAnAnonymousPostAndTheOperatorActionsAreNot() {
|
||||
List<Route> routes = endpoint.routes();
|
||||
Route submit = routes.stream().filter(r -> r.pathPattern().equals("/contact/submit")).findFirst().orElseThrow();
|
||||
assertEquals("POST", submit.method());
|
||||
assertTrue(submit.anonymous(), "declared anonymous: the kernel exempts exactly this POST from CSRF");
|
||||
assertEquals(1, routes.stream().filter(r -> r.pathPattern().equals("/contact/submit")).count(),
|
||||
"no GET submit route remains");
|
||||
for (Route r : routes) {
|
||||
if (!r.pathPattern().equals("/contact/submit")) {
|
||||
assertFalse(r.anonymous(), "the operator actions keep the principal (and the CSRF rule): " + r);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyRouteIsAPostSoNoLinkOrImageCanChangeState() {
|
||||
List<Route> routes = endpoint.routes();
|
||||
assertEquals(List.of("/contact/submit", "/contact/install-page", "/contact/smtp-test"),
|
||||
routes.stream().map(Route::pathPattern).toList());
|
||||
for (Route r : routes) {
|
||||
assertEquals("POST", r.method(), "a GET route would let a cross-site link trigger it: " + r);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- POST /contact/submit --------------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void aValidPostRedirects303SentAndStoresAndEmails() {
|
||||
RouteResponse res = submit(valid());
|
||||
assertEquals(303, res.status(), "post/redirect/get");
|
||||
assertEquals("/home?contact=sent", location(res), "it lands back on the form's page with a success flag");
|
||||
verify(store).add(eq("acme"), eq("Ann"), eq("ann@example.com"), eq("Hello there"), anyLong());
|
||||
verify(mailer).send(eq("acme"), eq("Acme"), eq("Ann"), eq("ann@example.com"), eq("Hello there"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRedirectCarriesTheOutcomeOnlyNeverASubmittedValue() {
|
||||
String where = location(submit(valid()));
|
||||
for (String personal : List.of("Ann", "ann", "example.com", "Hello")) {
|
||||
assertFalse(where.contains(personal), "no personal data in the Location: " + where);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGetSubmissionIsNotAcceptedAndStoresNothing() {
|
||||
Map<String, List<String>> query = with(valid(), "return", "/home");
|
||||
RouteResponse res = endpoint.handle(request("GET", "/contact/submit", query, Map.of(), Map.of()));
|
||||
assertEquals(404, res.status(), "1.x's GET submission is gone: only the anonymous POST is handled");
|
||||
verifyNothingStoredOrSent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void fieldsInTheQueryStringAreIgnoredOnAPost() {
|
||||
Map<String, List<String>> query = valid();
|
||||
RouteResponse res = endpoint.handle(request("POST", "/contact/submit", query,
|
||||
Map.of("return", List.of("/home")), Map.of()));
|
||||
assertEquals("/home?contact=invalid", location(res), "personal data is read from the body only");
|
||||
verifyNothingStoredOrSent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFilledHoneypotFakesSuccessWithoutStoringOrEmailing() {
|
||||
RouteResponse res = submit(with(valid(), "website", "http://spam.example"));
|
||||
assertEquals("/home?contact=sent", location(res), "the bot sees a fake success");
|
||||
verifyNothingStoredOrSent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInvalidEmailRedirectsWithTheInvalidFlag() {
|
||||
assertEquals("/home?contact=invalid", location(submit(with(valid(), "email", "not-an-email"))));
|
||||
verifyNothingStoredOrSent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlankMessageRedirectsWithTheInvalidFlag() {
|
||||
assertEquals("/home?contact=invalid", location(submit(with(valid(), "message", " "))));
|
||||
verifyNothingStoredOrSent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActiveCaptchaWithoutATokenRefusesThePost() {
|
||||
when(captcha.widgetForSite(any())).thenReturn(new CaptchaWidget(
|
||||
true, "g-recaptcha-response", "<div class=\"g-recaptcha\"></div>"));
|
||||
when(captcha.verify(any(), any(), any())).thenReturn(false);
|
||||
RouteResponse res = submit(valid());
|
||||
assertEquals("/home?contact=captcha", location(res));
|
||||
verify(captcha).verify("acme", "", CLIENT_IP);
|
||||
verifyNothingStoredOrSent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActiveCaptchaIsVerifiedWithTheBodyTokenAndTheGatedClientIp() {
|
||||
when(captcha.widgetForSite(any())).thenReturn(new CaptchaWidget(
|
||||
true, "g-recaptcha-response", "<div class=\"g-recaptcha\"></div>"));
|
||||
when(captcha.verify(eq("acme"), eq("good-token"), eq(CLIENT_IP))).thenReturn(true);
|
||||
RouteResponse res = submit(with(valid(), "g-recaptcha-response", "good-token"));
|
||||
assertEquals("/home?contact=sent", location(res));
|
||||
verify(store).add(eq("acme"), eq("Ann"), eq("ann@example.com"), eq("Hello there"), anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCaptchaTokenOnlyInTheQueryStringDoesNotCount() {
|
||||
when(captcha.widgetForSite(any())).thenReturn(new CaptchaWidget(
|
||||
true, "g-recaptcha-response", "<div class=\"g-recaptcha\"></div>"));
|
||||
when(captcha.verify(eq("acme"), eq("good-token"), any())).thenReturn(true);
|
||||
Map<String, List<String>> form = with(valid(), "return", "/home");
|
||||
RouteResponse res = endpoint.handle(request("POST", "/contact/submit",
|
||||
Map.of("g-recaptcha-response", List.of("good-token")), form, Map.of()));
|
||||
assertEquals("/home?contact=captcha", location(res));
|
||||
verifyNothingStoredOrSent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActiveCaptchaThatFailsRedirectsWithTheCaptchaFlag() {
|
||||
when(captcha.widgetForSite(any())).thenReturn(new CaptchaWidget(
|
||||
true, "g-recaptcha-response", "<div class=\"g-recaptcha\"></div>"));
|
||||
when(captcha.verify(any(), any(), any())).thenReturn(false);
|
||||
assertEquals("/home?contact=captcha", location(submit(with(valid(), "g-recaptcha-response", "bad"))));
|
||||
verifyNothingStoredOrSent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledContactReturns404() {
|
||||
settings.site("acme", Map.of("enabled", false));
|
||||
assertEquals(404, submit(valid()).status());
|
||||
verifyNothingStoredOrSent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedSendRedirectsQueuedButStillStores() {
|
||||
when(mailer.send(anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(MailSendResult.failed("relay refused"));
|
||||
assertEquals("/home?contact=queued", location(submit(valid())), "a real relay failure is a delayed note");
|
||||
verify(store).add(eq("acme"), eq("Ann"), eq("ann@example.com"), eq("Hello there"), anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnconfiguredRelayRedirectsSentSilentlyAndStores() {
|
||||
when(mailer.send(anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(MailSendResult.notConfigured());
|
||||
assertEquals("/home?contact=sent", location(submit(valid())), "a store-only site never shows a delivery note");
|
||||
verify(store).add(eq("acme"), eq("Ann"), eq("ann@example.com"), eq("Hello there"), anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRefererIsUsedWhenNoReturnFieldIsGiven() {
|
||||
RouteResponse res = endpoint.handle(request("POST", "/contact/submit", Map.of(), valid(),
|
||||
Map.of("Referer", "https://acme.test/contact-us?x=1")));
|
||||
assertEquals("/contact-us?contact=sent", location(res), "it lands back on the Referer page (query stripped)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aForeignReturnFieldIsRejectedAndFallsBackToRoot() {
|
||||
RouteResponse res = submit(with(valid(), "return", "https://evil.example/steal"));
|
||||
assertEquals("/?contact=sent", location(res), "an off-origin return target is ignored (no open redirect)");
|
||||
assertEquals("/?contact=sent", location(submit(with(valid(), "return", "//evil.example/x"))));
|
||||
}
|
||||
|
||||
// ---- /contact/install-page (operator-gated) ---------------------------------------------------------------
|
||||
|
||||
private RouteResponse install() {
|
||||
return endpoint.handle(request("POST", "/contact/install-page", Map.of(), Map.of(), Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theInstallPageIsHiddenFromCallersWithoutThePermission() {
|
||||
RouteResponse res = install();
|
||||
assertEquals(404, res.status(), "fail closed: the action is not revealed to the unauthorized");
|
||||
assertTrue(kernel.installs().isEmpty(), "nothing was installed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGetOnTheInstallPathInstallsNothingEvenForAnAuthorizedOperator() {
|
||||
kernel.grant("contact|settings");
|
||||
for (String method : List.of("GET", "HEAD", "PUT", "DELETE")) {
|
||||
RouteResponse res = endpoint.handle(request(method, "/contact/install-page", Map.of(), Map.of(), Map.of()));
|
||||
assertEquals(404, res.status(), method + " is not the install action");
|
||||
}
|
||||
assertTrue(kernel.installs().isEmpty(), "following a link (or loading an <img>) must not install the page");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theInstallMethodIsMatchedCaseInsensitively() {
|
||||
kernel.grant("contact|settings");
|
||||
RouteResponse res = endpoint.handle(request("post", "/contact/install-page", Map.of(), Map.of(), Map.of()));
|
||||
assertEquals(200, res.status());
|
||||
assertEquals(1, kernel.installs().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInstallThatPublishesSaysWhereThePageIs() {
|
||||
kernel.grant("contact|settings").message("acme", "contact.page.title", "Contact us");
|
||||
RouteResponse res = install();
|
||||
assertEquals(200, res.status());
|
||||
assertEquals("Contact page installed at /contact", text(res));
|
||||
StarterPage page = kernel.installs().get(0);
|
||||
assertEquals("contact", page.slug(), "installed at the stable slug");
|
||||
assertEquals("/contact", page.path());
|
||||
assertEquals(Map.of("en", "Contact us"), page.titles(), "titled in the site's default language");
|
||||
assertFalse(page.noindex(), "a contact page is meant to be found");
|
||||
assertTrue(page.html().contains("data-widget=\"contact/form\""), "the page carries the widget anchor");
|
||||
assertTrue(page.html().contains("<title>Contact us</title>"));
|
||||
assertTrue(page.logic().contains("${master}"), "the chrome comes from the master");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInstallOnAReviewedSiteSaysItIsWaitingForReview() {
|
||||
kernel.grant("contact|settings").nextInstall(InstallResult.Outcome.PENDING_REVIEW);
|
||||
RouteResponse res = install();
|
||||
assertEquals(200, res.status());
|
||||
assertTrue(text(res).contains("waiting in the review queue"), text(res));
|
||||
assertTrue(text(res).endsWith("/contact"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInstallBlockedByTheQualityChecksSaysItIsADraftAndWhy() {
|
||||
kernel.grant("contact|settings").nextInstall(InstallResult.Outcome.DRAFT_BLOCKED,
|
||||
new Finding(Severity.ERROR, "content.thin", "The page has almost no text."));
|
||||
RouteResponse res = install();
|
||||
assertEquals(200, res.status());
|
||||
assertTrue(text(res).contains("as a draft"), text(res));
|
||||
assertTrue(text(res).contains("- content.thin: The page has almost no text."), "the blocking finding: " + text(res));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSecondInstallChangesNothingAndSaysWhereTheExistingPageIs() {
|
||||
kernel.grant("contact|settings").page("acme", "contact", "/hola");
|
||||
RouteResponse res = install();
|
||||
assertEquals(200, res.status(), "an existing page is not an error — the action is idempotent");
|
||||
assertEquals("A contact page already exists at /hola", text(res), "the page's current path, wherever it moved");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedInstallIsA500WithTheOperatorsMessage() {
|
||||
SitePages failing = mock(SitePages.class);
|
||||
when(failing.install(any(), any())).thenThrow(new IllegalStateException("/contact is served by another page"));
|
||||
kernel.grant("contact|settings");
|
||||
ContactEndpoint withFailingPages = new ContactEndpoint(store, mailer, settings, kernel, kernel, captcha, failing);
|
||||
RouteResponse res = withFailingPages.handle(request("POST", "/contact/install-page", Map.of(), Map.of(), Map.of()));
|
||||
assertEquals(500, res.status());
|
||||
assertEquals("Could not install the contact page.", text(res));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOperatorAnswersAreConsoleMessages() {
|
||||
kernel.grant("contact|settings").message(null, "contact.page.installed", "Página de contacto instalada en");
|
||||
assertEquals("Página de contacto instalada en /contact", text(install()),
|
||||
"in the operator's console language (Messages.console), not the visitor's");
|
||||
}
|
||||
|
||||
// ---- /contact/smtp-test (operator-gated) ------------------------------------------------------------------
|
||||
|
||||
private RouteResponse smtpTest(Map<String, List<String>> form) {
|
||||
return endpoint.handle(request("POST", "/contact/smtp-test", Map.of(), form, Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSmtpTestIsHiddenFromCallersWithoutThePermission() {
|
||||
assertEquals(404, smtpTest(Map.of()).status(), "fail closed: the surface is not revealed to the unauthorized");
|
||||
verifyNoInteractions(mailer);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSmtpTestSendsForAnAuthorizedCaller() {
|
||||
kernel.grant("contact|settings");
|
||||
when(mailer.sendTest(eq("acme"), eq("Acme"), eq("me@example.com"))).thenReturn(MailSendResult.sent());
|
||||
RouteResponse res = smtpTest(Map.of("to", List.of(" me@example.com ")));
|
||||
assertEquals(200, res.status());
|
||||
assertEquals("Test message sent.", text(res));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSmtpTestWithoutARecipientUsesTheConfiguredOne() {
|
||||
kernel.grant("contact|settings");
|
||||
when(mailer.sendTest(eq("acme"), eq("Acme"), eq(""))).thenReturn(MailSendResult.sent());
|
||||
assertEquals(200, smtpTest(Map.of()).status());
|
||||
verify(mailer).sendTest("acme", "Acme", "");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGetOnTheSmtpTestPathSendsNothingEvenForAnAuthorizedOperator() {
|
||||
kernel.grant("contact|settings");
|
||||
RouteResponse res = endpoint.handle(request("GET", "/contact/smtp-test",
|
||||
Map.of("to", List.of("victim@example.com")), Map.of(), Map.of()));
|
||||
assertEquals(404, res.status(), "a cross-site link must not make the server send an email");
|
||||
verifyNoInteractions(mailer);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSmtpTestRecipientIsReadFromTheBodyNeverTheQueryString() {
|
||||
kernel.grant("contact|settings");
|
||||
when(mailer.sendTest(anyString(), anyString(), any())).thenReturn(MailSendResult.sent());
|
||||
endpoint.handle(request("POST", "/contact/smtp-test", Map.of("to", List.of("victim@example.com")),
|
||||
Map.of(), Map.of()));
|
||||
verify(mailer).sendTest("acme", "Acme", "");
|
||||
verify(mailer, never()).sendTest(anyString(), anyString(), eq("victim@example.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedSmtpTestReportsA502() {
|
||||
kernel.grant("contact|settings");
|
||||
when(mailer.sendTest(anyString(), anyString(), any())).thenReturn(MailSendResult.failed("timeout"));
|
||||
RouteResponse res = smtpTest(Map.of());
|
||||
assertEquals(502, res.status(), "a failed test reports a bad-gateway status");
|
||||
assertTrue(text(res).contains("timeout"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import jakarta.mail.Message;
|
||||
import jakarta.mail.MessagingException;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
import jakarta.mail.PasswordAuthentication;
|
||||
import jakarta.mail.Session;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
/**
|
||||
* The send path: {@link ContactMailer} builds the expected MIME message and hands it to a MOCK
|
||||
* {@link MailTransport} (no socket), reports a send failure without throwing, reports "not configured" when no
|
||||
* relay is set, and takes the SMTP password ONLY from {@code PluginSettings.secret(site, "smtpPassword")} — the
|
||||
* kernel decrypts the {@code ENC(...)} value; the plugin never sees ciphertext, never reads a password out of the
|
||||
* settings view, and never prints it.
|
||||
*/
|
||||
class ContactMailerTest {
|
||||
|
||||
private static final Map<String, Object> RELAY = Map.of(
|
||||
"smtpHost", "mail.example.com",
|
||||
"smtpPort", 587L,
|
||||
"smtpAuth", true,
|
||||
"smtpUsername", "postmaster",
|
||||
"smtpStarttls", true,
|
||||
"fromAddress", "site@example.com",
|
||||
"toAddress", "owner@example.com");
|
||||
|
||||
/** The plugin's per-site settings as the kernel hands them over: RELAY for acme, the password a secret. */
|
||||
private static FakePluginSettings settings(Map<String, Object> acme) {
|
||||
return new FakePluginSettings().site("acme", acme).secret("acme", "smtpPassword", "s3cret");
|
||||
}
|
||||
|
||||
/** The password the built session's authenticator would answer the relay with. */
|
||||
private static PasswordAuthentication credentials(Session session) {
|
||||
return session.requestPasswordAuthentication(null, 587, "smtp", null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSubmissionBuildsTheExpectedMimeMessageAndCallsTheTransport() throws Exception {
|
||||
MailTransport transport = mock(MailTransport.class);
|
||||
ContactMailer mailer = new ContactMailer(settings(RELAY), transport);
|
||||
|
||||
MailSendResult result = mailer.send("acme", "Acme", "Ann", "ann@example.com", "Hello there");
|
||||
|
||||
assertEquals(MailSendResult.Status.SENT, result.status());
|
||||
ArgumentCaptor<MimeMessage> captor = ArgumentCaptor.forClass(MimeMessage.class);
|
||||
verify(transport).send(captor.capture());
|
||||
MimeMessage msg = captor.getValue();
|
||||
assertEquals("site@example.com", ((jakarta.mail.internet.InternetAddress) msg.getFrom()[0]).getAddress());
|
||||
assertEquals("owner@example.com",
|
||||
((jakarta.mail.internet.InternetAddress) msg.getRecipients(Message.RecipientType.TO)[0]).getAddress());
|
||||
// Reply-To is the visitor so the site can reply straight to them.
|
||||
assertEquals("ann@example.com",
|
||||
((jakarta.mail.internet.InternetAddress) msg.getReplyTo()[0]).getAddress());
|
||||
assertTrue(msg.getSubject().startsWith("[Acme] "), "subject is site-prefixed: " + msg.getSubject());
|
||||
String body = (String) msg.getContent();
|
||||
assertTrue(body.contains("ann@example.com"), "the body carries the submitter email");
|
||||
assertTrue(body.contains("Hello there"), "the body carries the message");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTransportFailureIsReportedNotThrown() throws Exception {
|
||||
MailTransport transport = mock(MailTransport.class);
|
||||
doThrow(new MessagingException("relay refused")).when(transport).send(any());
|
||||
ContactMailer mailer = new ContactMailer(settings(RELAY), transport);
|
||||
|
||||
MailSendResult result = mailer.send("acme", "Acme", "Ann", "ann@example.com", "Hi");
|
||||
|
||||
assertEquals(MailSendResult.Status.FAILED, result.status());
|
||||
assertNotNull(result.detail());
|
||||
assertTrue(result.detail().contains("relay refused"), "the reason is surfaced: " + result.detail());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnconfiguredRelayReportsNotConfiguredAndNeverTouchesTheTransport() throws Exception {
|
||||
MailTransport transport = mock(MailTransport.class);
|
||||
// Blank host + recipient ⇒ not configured.
|
||||
ContactMailer mailer = new ContactMailer(settings(Map.of()), transport);
|
||||
|
||||
MailSendResult result = mailer.send("acme", "Acme", "Ann", "ann@example.com", "Hi");
|
||||
|
||||
assertEquals(MailSendResult.Status.NOT_CONFIGURED, result.status());
|
||||
verify(transport, never()).send(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSmtpTestSendsToTheGivenAddress() throws Exception {
|
||||
MailTransport transport = mock(MailTransport.class);
|
||||
ContactMailer mailer = new ContactMailer(settings(RELAY), transport);
|
||||
|
||||
MailSendResult result = mailer.sendTest("acme", "Acme", "check@example.com");
|
||||
|
||||
assertEquals(MailSendResult.Status.SENT, result.status());
|
||||
ArgumentCaptor<MimeMessage> captor = ArgumentCaptor.forClass(MimeMessage.class);
|
||||
verify(transport).send(captor.capture());
|
||||
assertEquals("check@example.com", ((jakarta.mail.internet.InternetAddress)
|
||||
captor.getValue().getRecipients(Message.RecipientType.TO)[0]).getAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePasswordIsTheSitesSecretInClearAndReachesTheRelayCredentials() throws Exception {
|
||||
MailTransport transport = mock(MailTransport.class);
|
||||
ContactMailer mailer = new ContactMailer(settings(RELAY), transport);
|
||||
|
||||
SmtpSettings smtp = mailer.settingsFor("acme");
|
||||
assertEquals("s3cret", smtp.password(), "PluginSettings.secret supplies the password, already in clear");
|
||||
mailer.send("acme", "Acme", "Ann", "ann@example.com", "Hi");
|
||||
ArgumentCaptor<MimeMessage> captor = ArgumentCaptor.forClass(MimeMessage.class);
|
||||
verify(transport).send(captor.capture());
|
||||
PasswordAuthentication auth = credentials(captor.getValue().getSession());
|
||||
assertEquals("postmaster", auth.getUserName());
|
||||
assertEquals("s3cret", auth.getPassword(), "the relay is offered the secret's clear value");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPasswordFoundInTheSettingsViewIsNeverUsed() {
|
||||
// The kernel leaves secret keys out of the view; a value there anyway (a hand-built view, a future change)
|
||||
// must not become the password: only the declared secret, read through secret(), is trusted.
|
||||
Map<String, Object> withLeak = new HashMap<>(RELAY);
|
||||
withLeak.put("smtpPassword", "ENC(ciphertext-not-a-password)");
|
||||
ContactMailer viewOnly = new ContactMailer(new FakePluginSettings().site("acme", withLeak),
|
||||
mock(MailTransport.class));
|
||||
assertEquals("", viewOnly.settingsFor("acme").password(), "no secret ⇒ no password, whatever the view holds");
|
||||
|
||||
ContactMailer both = new ContactMailer(settings(withLeak), mock(MailTransport.class));
|
||||
assertEquals("s3cret", both.settingsFor("acme").password(), "the secret wins over anything in the view");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSecretIsReadForTheSendingSiteOnly() {
|
||||
FakePluginSettings settings = settings(RELAY).site("other", RELAY).secret("other", "smtpPassword", "other-pw");
|
||||
ContactMailer mailer = new ContactMailer(settings, mock(MailTransport.class));
|
||||
assertEquals("s3cret", mailer.settingsFor("acme").password());
|
||||
assertEquals("other-pw", mailer.settingsFor("other").password(), "each site authenticates with its own secret");
|
||||
assertEquals("", mailer.settingsFor("nobody").password(), "a site with no secret has no password");
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePasswordNeverAppearsInTheSettingsText() {
|
||||
String text = new ContactMailer(settings(RELAY), mock(MailTransport.class)).settingsFor("acme").toString();
|
||||
assertFalse(text.contains("s3cret"), "masked in logs: " + text);
|
||||
assertTrue(text.contains("password=<set>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void settingsAreReadTypedWithTheDescriptorDefaultsAndAClampedPort() {
|
||||
Map<String, Object> odd = new HashMap<>(RELAY);
|
||||
odd.put("smtpPort", 99999L);
|
||||
odd.put("smtpHost", " mail.example.com ");
|
||||
SmtpSettings smtp = new ContactMailer(settings(odd), mock(MailTransport.class)).settingsFor("acme");
|
||||
assertEquals(65535, smtp.port(), "the port is clamped to 1..65535");
|
||||
assertEquals("mail.example.com", smtp.host(), "values are stripped");
|
||||
SmtpSettings bare = new ContactMailer(new FakePluginSettings(), mock(MailTransport.class)).settingsFor("acme");
|
||||
assertEquals(25, bare.port(), "port 25 when unset");
|
||||
assertFalse(bare.auth());
|
||||
assertFalse(bare.isConfigured(), "no host and no recipient");
|
||||
}
|
||||
|
||||
@Test
|
||||
void implicitTlsRidesSslEnableOnTheSmtpProtocol() {
|
||||
// Regression: implicit TLS (SMTPS, e.g. 465) must ride mail.smtp.ssl.enable on the smtp protocol. Switching
|
||||
// to "smtps" left mail.smtp.host unset, so the static Transport.send() (which maps rfc822 -> smtp, ignoring
|
||||
// mail.transport.protocol) dialed localhost:25 and failed with "Connection refused".
|
||||
jakarta.mail.Session s = ContactMailer.session(new SmtpSettings(
|
||||
"mail.example.com", 465, true, "postmaster", "pw", false, true, "site@example.com", "owner@example.com"));
|
||||
|
||||
assertEquals("smtp", s.getProperty("mail.transport.protocol"), "protocol stays smtp (address map ignores smtps)");
|
||||
assertEquals("mail.example.com", s.getProperty("mail.smtp.host"), "host on mail.smtp.* (what the send reads)");
|
||||
assertEquals("465", s.getProperty("mail.smtp.port"));
|
||||
assertEquals("true", s.getProperty("mail.smtp.ssl.enable"), "implicit TLS on connect");
|
||||
assertNull(s.getProperty("mail.smtps.host"), "no smtps-scoped host the static send would silently ignore");
|
||||
assertNull(s.getProperty("mail.smtp.starttls.enable"), "implicit TLS and STARTTLS are mutually exclusive");
|
||||
}
|
||||
|
||||
@Test
|
||||
void starttlsRidesStarttlsEnableOnTheSmtpProtocol() {
|
||||
jakarta.mail.Session s = ContactMailer.session(new SmtpSettings(
|
||||
"mail.example.com", 587, false, null, null, true, false, "site@example.com", "owner@example.com"));
|
||||
|
||||
assertEquals("smtp", s.getProperty("mail.transport.protocol"));
|
||||
assertEquals("587", s.getProperty("mail.smtp.port"));
|
||||
assertEquals("true", s.getProperty("mail.smtp.starttls.enable"), "opportunistic STARTTLS");
|
||||
assertNull(s.getProperty("mail.smtp.ssl.enable"), "STARTTLS mode must not also enable implicit TLS");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* The submission store over {@code PluginSiteFiles} (the testkit's {@link TempDirSiteFiles}, which applies the
|
||||
* kernel's confinement rules): append + newest-first read, field sanitization, the bound, per-site isolation, the
|
||||
* on-disk location shared with 1.x, and that an unreadable file is never overwritten.
|
||||
*/
|
||||
class ContactStoreTest {
|
||||
|
||||
@TempDir
|
||||
Path sites;
|
||||
private TempDirSiteFiles files;
|
||||
private ContactStore store;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
Files.createDirectories(sites.resolve("acme"));
|
||||
Files.createDirectories(sites.resolve("other"));
|
||||
files = new TempDirSiteFiles(sites, "contact");
|
||||
store = new ContactStore(files);
|
||||
}
|
||||
|
||||
@Test
|
||||
void appendsAndReadsNewestFirst() {
|
||||
store.add("acme", "Ann", "ann@example.com", "First message", 1000L);
|
||||
store.add("acme", "Bob", "bob@example.com", "Second message", 2000L);
|
||||
|
||||
assertEquals(2, store.count("acme"));
|
||||
List<ContactSubmission> recent = store.recent("acme", 10);
|
||||
assertEquals("Bob", recent.get(0).name(), "newest first");
|
||||
assertEquals("Ann", recent.get(1).name());
|
||||
assertEquals("ann@example.com", recent.get(1).email());
|
||||
assertEquals(1, store.recent("acme", 1).size(), "the limit is honoured");
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesTheSameFileAs1xSoExistingSubmissionsCarryOver() throws IOException {
|
||||
Path file = sites.resolve("acme/plugins/contact/submissions.tsv");
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, "500\tOld\told@example.com\tfrom contact 1.1.2\n", StandardCharsets.UTF_8);
|
||||
|
||||
store.add("acme", "New", "new@example.com", "after the upgrade", 900L);
|
||||
|
||||
assertEquals(2, store.count("acme"), "the 1.x submission is read from the same file");
|
||||
List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
|
||||
assertEquals(List.of("500\tOld\told@example.com\tfrom contact 1.1.2", "900\tNew\tnew@example.com\tafter the upgrade"),
|
||||
lines, "appended in place, one TSV line each");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tabsAndNewlinesAreSanitizedSoTheTsvFormatHolds() {
|
||||
store.add("acme", "Eve\tEvil", "e@example.com", "line one\nline two\tindented", 1000L);
|
||||
ContactSubmission s = store.recent("acme", 10).get(0);
|
||||
assertEquals("Eve Evil", s.name(), "tabs stripped from the field");
|
||||
assertEquals("line one line two indented", s.message(), "newlines/tabs collapsed to spaces");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFieldIsCappedAndTheFileKeepsOnlyTheMostRecentSubmissions() {
|
||||
store.add("acme", "Long", "l@example.com", "x".repeat(ContactStore.MAX_FIELD + 50), 1L);
|
||||
assertEquals(ContactStore.MAX_FIELD, store.recent("acme", 1).get(0).message().length());
|
||||
for (int i = 2; i <= ContactStore.MAX_SUBMISSIONS + 1; i++) {
|
||||
store.add("acme", "N" + i, "n@example.com", "m", i);
|
||||
}
|
||||
assertEquals(ContactStore.MAX_SUBMISSIONS, store.count("acme"), "bounded to the most recent");
|
||||
assertEquals("N" + (ContactStore.MAX_SUBMISSIONS + 1), store.recent("acme", 1).get(0).name());
|
||||
assertTrue(store.recent("acme", ContactStore.MAX_SUBMISSIONS).stream().noneMatch(s -> s.name().equals("Long")),
|
||||
"the oldest one was dropped");
|
||||
}
|
||||
|
||||
@Test
|
||||
void submissionsAreIsolatedPerSite() {
|
||||
store.add("acme", "Ann", "a@example.com", "for acme", 1000L);
|
||||
assertEquals(1, store.count("acme"));
|
||||
assertEquals(0, store.count("other"), "another site sees none of acme's submissions");
|
||||
assertTrue(store.recent("other", 10).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnreadableFileIsNeverOverwrittenAndTheConsoleReadsDegradeToEmpty() throws IOException {
|
||||
// A file over the read cap cannot be read: an append must fail rather than rewrite it from nothing.
|
||||
ContactStore small = new ContactStore(new TempDirSiteFiles(sites, "contact", 64));
|
||||
Path file = sites.resolve("acme/plugins/contact/submissions.tsv");
|
||||
Files.createDirectories(file.getParent());
|
||||
String big = "1\tA\ta@example.com\t" + "y".repeat(200) + "\n";
|
||||
Files.writeString(file, big, StandardCharsets.UTF_8);
|
||||
|
||||
assertThrows(UncheckedIOException.class, () -> small.add("acme", "B", "b@example.com", "hi", 2L));
|
||||
assertEquals(big, Files.readString(file, StandardCharsets.UTF_8), "the stored submissions are untouched");
|
||||
assertEquals(0, small.count("acme"), "the console count degrades to 0 instead of failing the screen");
|
||||
assertTrue(small.recent("acme", 10).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSiteWithoutAFolderIsAnErrorNotASilentCreate() {
|
||||
assertThrows(UncheckedIOException.class, () -> store.add("ghost", "A", "a@example.com", "hi", 1L),
|
||||
"the kernel refuses to create a deleted site's folder; the store reports it");
|
||||
assertTrue(Files.notExists(sites.resolve("ghost")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import mx.quest.runway.spi.CaptchaService;
|
||||
import mx.quest.runway.spi.model.CaptchaWidget;
|
||||
import mx.quest.runway.spi.model.PageMeta;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.model.WidgetView;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The {@code contact} content widget renders the form inline on a normal page and re-renders the submit outcome
|
||||
* from the {@code ?contact=…} query the endpoint redirects back with. All rendering (form, thank-you, error
|
||||
* re-render, CAPTCHA, escaping) lives here — the endpoint only stores/sends/redirects. Settings and messages come
|
||||
* from the SPI services (testkit fakes).
|
||||
*/
|
||||
class ContactWidgetTest {
|
||||
|
||||
private static final SiteView ACME = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null);
|
||||
|
||||
private FakePluginSettings settings;
|
||||
private FakeSiteServices kernel;
|
||||
private final AtomicReference<CaptchaWidget> challenge = new AtomicReference<>(CaptchaWidget.inactive());
|
||||
private ContactWidget widget;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
settings = new FakePluginSettings().defaults(Map.of("enabled", true));
|
||||
kernel = new FakeSiteServices().site(ACME);
|
||||
CaptchaService captcha = new CaptchaService() {
|
||||
@Override
|
||||
public CaptchaWidget widgetForSite(String siteId) {
|
||||
return challenge.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(String siteId, String token, String clientIp) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
widget = new ContactWidget(settings, kernel, captcha);
|
||||
}
|
||||
|
||||
private String render(Map<String, String> query) {
|
||||
PageMeta page = new PageMeta("home", "Home", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
|
||||
return widget.render(new WidgetView(ACME, page, Locale.ENGLISH, "contact", false, Map.of(), query)).html();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theFormPostsAUrlEncodedBodyToTheAnonymousSubmitRoute() {
|
||||
String html = render(Map.of());
|
||||
assertTrue(html.contains("method=\"post\""), "the form POSTs — its fields never ride a URL: " + html);
|
||||
assertFalse(html.contains("method=\"get\""));
|
||||
assertTrue(html.contains("action=\"/contact/submit\""), "to the anonymous submit route");
|
||||
assertTrue(html.contains("enctype=\"application/x-www-form-urlencoded\""),
|
||||
"the only body an anonymous route accepts");
|
||||
assertFalse(html.contains("_csrf"), "no session token: the route is CSRF-exempt by declaration");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBareRenderShowsTheFormWithTheHoneypotAndTheReturnPath() {
|
||||
String html = render(Map.of());
|
||||
assertTrue(html.contains("name=\"message\""), "the message field is present");
|
||||
assertTrue(html.contains("name=\"website\""), "the honeypot field is present");
|
||||
// Lands the visitor back on this page (its slug path) after submit; a moved page is caught server-side by Referer.
|
||||
assertTrue(html.contains("name=\"return\" value=\"/home\""), "the return path is the page the widget lives on");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theReturnPathIsTheRequestPathWhenTheHostProvidesIt() {
|
||||
// A blog entry (a content source's page) renders this widget from the master chrome: its PageMeta slug
|
||||
// is a composite identity ("blog:my-post"), NOT a path — the request path from the view must win.
|
||||
PageMeta entry = new PageMeta("blog:my-post", "My post", "", List.of(Locale.ENGLISH), Locale.ENGLISH,
|
||||
true, false, "blog");
|
||||
String html = widget.render(new WidgetView(ACME, entry, Locale.ENGLISH, "contact", true, Map.of(),
|
||||
Map.of(), "/es/blog/mi-entrada")).html();
|
||||
assertTrue(html.contains("name=\"return\" value=\"/es/blog/mi-entrada\""),
|
||||
"the return path is the URL as served — never built from the composite slug");
|
||||
assertFalse(html.contains("/blog:my-post"), "the composite identity never leaks into a path");
|
||||
}
|
||||
|
||||
@Test
|
||||
void labelsComeFromTheSitesMessagesAndAreEscaped() {
|
||||
kernel.message("acme", "contact.form.submit", "Envoyer <maintenant>");
|
||||
String html = render(Map.of());
|
||||
assertTrue(html.contains(">Envoyer <maintenant></button>"), "Messages.site for the label: " + html);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSentOutcomeShowsAThankYouNotTheForm() {
|
||||
String html = render(Map.of("contact", "sent"));
|
||||
assertTrue(html.contains("rw-contact-success"), "a thank-you is shown");
|
||||
assertTrue(html.contains("Thanks — your message has been sent."), "the default thank-you text");
|
||||
assertFalse(html.contains("name=\"message\""), "the form is replaced by the confirmation");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theQueuedOutcomeThanksAndNotesTheDelayedDeliveryInsteadOfShowingTheFormAgain() {
|
||||
String html = render(Map.of("contact", "queued"));
|
||||
assertTrue(html.contains("rw-contact-success"), "the message was stored: thank the visitor");
|
||||
assertTrue(html.contains("email delivery is delayed"), "and say the email is late: " + html);
|
||||
assertFalse(html.contains("name=\"message\""), "no empty form inviting a duplicate submission");
|
||||
assertFalse(render(Map.of("contact", "sent")).contains("delayed"), "a plain success carries no note");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theConfiguredThankYouWinsAndIsEscaped() {
|
||||
settings.site("acme", Map.of("successMessage", "<b>x</b>"));
|
||||
String html = render(Map.of("contact", "sent"));
|
||||
assertFalse(html.contains("<b>x</b>"), "the configured thank-you is HTML-escaped");
|
||||
assertTrue(html.contains("<b>x</b>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInvalidOutcomeReRendersTheFormWithAnError() {
|
||||
String html = render(Map.of("contact", "invalid"));
|
||||
assertTrue(html.contains("rw-contact-error"), "the validation error is surfaced");
|
||||
assertTrue(html.contains("name=\"message\""), "the form re-renders so the visitor can retry");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCaptchaOutcomeReRendersTheFormWithAnError() {
|
||||
String html = render(Map.of("contact", "captcha"));
|
||||
assertTrue(html.contains("Please complete the challenge"), "the challenge error is surfaced");
|
||||
assertTrue(html.contains("name=\"message\""), "the form re-renders so the visitor can retry");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConfiguredChallengeRendersOnTheForm() {
|
||||
challenge.set(new CaptchaWidget(true, "g-recaptcha-response", "<div class=\"g-recaptcha\" data-sitekey=\"KEY\"></div>"));
|
||||
String html = render(Map.of());
|
||||
assertTrue(html.contains("data-sitekey=\"KEY\""), "the site's CAPTCHA renders inline");
|
||||
assertTrue(html.indexOf("data-sitekey") < html.indexOf("</form>"), "inside the form, so its token is posted");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDisabledContactRendersNothing() {
|
||||
settings.site("acme", Map.of("enabled", false));
|
||||
assertTrue(render(Map.of()).isEmpty(), "a disabled contact widget renders an empty fragment");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex">
|
||||
<title>Contact plugin — help & reference</title>
|
||||
<style>
|
||||
body { max-width: 46rem; margin: 2rem auto; padding: 0 1rem;
|
||||
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; color: #1a1a1a; line-height: 1.5; }
|
||||
h1 { font-size: 1.6rem; } h2 { font-size: 1.2rem; margin-top: 1.75rem; }
|
||||
code { background: #f3f3f3; padding: .1rem .3rem; border-radius: .25rem; }
|
||||
pre { background: #f6f8fa; padding: .75rem 1rem; border-radius: .375rem; overflow: auto; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Contact — help & reference</h1>
|
||||
<p>The Contact plugin adds a contact form to your site and stores each submission (and can email it), which you
|
||||
read here in the console. The form is a <strong>content widget</strong>: it lives on a normal, editable site
|
||||
page. You can add it to any page yourself, or install a ready-made contact page in one click from the settings.</p>
|
||||
|
||||
<h2>Install a ready-made contact page</h2>
|
||||
<p>On the Contact settings page, the <strong>Contact page</strong> card installs a ready-made page carrying the
|
||||
form (at <code>/contact</code>). It then becomes an <strong>ordinary site page</strong> — it appears under
|
||||
<em>Pages</em>, and you can edit its template, restyle it, move it or give it a different URL. Installing is
|
||||
idempotent: it never overwrites an existing page. It also follows your site's publishing rules: on a site that
|
||||
requires review it waits in the review queue (unless you may approve pages), and when the site's quality checks
|
||||
block publishing it is kept as a draft and the answer lists what to fix. The answer always says which happened.</p>
|
||||
|
||||
<h2>Or put the form on any page</h2>
|
||||
<pre><div id="contact" data-widget="contact/form"></div></pre>
|
||||
<p>The <code>id</code> and <code>data-widget</code> must be on the same element. On submit the form posts to
|
||||
<code>/contact/submit</code>, which stores (and emails) the message and sends the visitor back to the page the
|
||||
form lives on, where they see your thank-you message. If the message was stored but your mail server could not
|
||||
be reached, the thank-you adds a short note that email delivery is delayed.</p>
|
||||
|
||||
<h2>Read submissions</h2>
|
||||
<p>Every submission is stored inside your site's own folder and listed on the Contact settings page — newest
|
||||
first, with the name, email, message and time — and, when an SMTP relay is set, also emailed to you. A
|
||||
<strong>full backup</strong> of the site keeps the submissions. A <strong>transfer copy</strong> (the download
|
||||
meant for someone outside your organisation) leaves them out, because they are your visitors' personal data;
|
||||
its manifest lists what was left out.</p>
|
||||
|
||||
<h2>Settings</h2>
|
||||
<ul>
|
||||
<li><strong>Enable contact form</strong> — turn the form (and its submit handler) on or off.</li>
|
||||
<li><strong>Thank-you message</strong> — what the visitor sees after sending.</li>
|
||||
<li><strong>SMTP relay</strong> (host, port, authentication, username, password, STARTTLS, SSL/TLS, from
|
||||
address, "Send submissions to") — optional: with a blank host or recipient, submissions are only stored.
|
||||
The password is saved encrypted and never shown again. It belongs to the relay login it was typed for: a
|
||||
save that changes the host, port, username or a TLS switch without retyping the password clears it, and
|
||||
the settings page says so — enter it again. <strong>Send a test email</strong> checks the relay.</li>
|
||||
</ul>
|
||||
|
||||
<h2>Anti-spam & privacy notes</h2>
|
||||
<p>The form is sent as a <strong>POST</strong>, so a visitor's name, email and message travel in the request body
|
||||
and never appear in a web address, their browser history or a proxy log. The platform lets this one form address
|
||||
accept a post from a visitor without a session (it takes nothing else and acts for nobody), and the form keeps
|
||||
its guards: a hidden <em>honeypot</em> field (a bot that fills it is silently ignored), your site's CAPTCHA when
|
||||
you configured one, and the platform's per-address rate limit.</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,80 @@
|
||||
/* Runway Contact plugin — form styles. Served at /__plugin/contact/static/contact.css.
|
||||
Neutral defaults; override any .rw-contact* rule from your own CSS to match your theme. */
|
||||
|
||||
.rw-contact {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: .75rem;
|
||||
max-width: 32rem;
|
||||
}
|
||||
|
||||
.rw-contact-label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: .25rem;
|
||||
font: 500 .95rem/1.3 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||
}
|
||||
|
||||
.rw-contact-input {
|
||||
padding: .5rem .75rem;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: .375rem;
|
||||
font-size: 1rem;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
textarea.rw-contact-input {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.rw-contact-submit {
|
||||
align-self: flex-start;
|
||||
padding: .5rem 1.25rem;
|
||||
border: 1px solid transparent;
|
||||
border-radius: .375rem;
|
||||
background: #0d6efd;
|
||||
color: #fff;
|
||||
font-size: 1rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.rw-contact-submit:hover {
|
||||
filter: brightness(.95);
|
||||
}
|
||||
|
||||
.rw-contact-error {
|
||||
color: #b02a37;
|
||||
background: #f8d7da;
|
||||
border-radius: .375rem;
|
||||
padding: .5rem .75rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.rw-contact-success {
|
||||
color: #0f5132;
|
||||
background: #d1e7dd;
|
||||
border-radius: .375rem;
|
||||
padding: .75rem 1rem;
|
||||
}
|
||||
|
||||
/* Honeypot: visually and semantically hidden, but present for naive bots to fill. */
|
||||
.rw-contact-hp {
|
||||
position: absolute;
|
||||
left: -9999px;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.rw-contact-main {
|
||||
max-width: 40rem;
|
||||
margin: 2rem auto;
|
||||
padding: 0 1rem;
|
||||
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||
color: #1a1a1a;
|
||||
}
|
||||
|
||||
.rw-contact-title {
|
||||
font-size: 1.5rem;
|
||||
margin: 0 0 1.25rem;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<!-- Admin fragment — rendered below this plugin's per-tenant settings form. Bare fragment; binding in .th.xml.
|
||||
First card: the ready-made "Contact page" — install it (once) or see where it lives (it becomes a normal,
|
||||
editable site page). Then the SMTP readiness + a self-test button, and the recent submissions (a th:each row
|
||||
template) so a site manager reads messages in the console. -->
|
||||
<div class="card mt-3">
|
||||
<div class="card-header"><h3 class="card-title" id="cp-title">Contact page</h3></div>
|
||||
<div class="card-body">
|
||||
<!-- Not yet installed: explain + a one-click install action. A POST carrying the console's CSRF token (it
|
||||
creates a page, so a cross-site link must not be able to trigger it); the plain-text result opens in
|
||||
a new tab. -->
|
||||
<div id="cp-install">
|
||||
<p class="text-secondary" id="cp-desc">Install a ready-made contact page carrying the form. It becomes
|
||||
a normal site page — edit, restyle, move or rename it from Pages.</p>
|
||||
<form id="cp-install-form" method="post" action="/contact/install-page" target="_blank" rel="noopener"
|
||||
class="m-0">
|
||||
<input id="cp-csrf" type="hidden" name="_csrf" value="">
|
||||
<button id="cp-install-btn" type="submit" class="btn btn-primary">
|
||||
<i class="fa-solid fa-file-circle-plus me-1"></i><span id="cp-install-label">Install contact page</span></button>
|
||||
</form>
|
||||
</div>
|
||||
<!-- Already installed: show the live path (from PageStore — follows moves) + where to edit it. -->
|
||||
<div id="cp-installed" class="d-flex align-items-center">
|
||||
<span class="badge bg-success-lt me-2" id="cp-badge">Installed</span>
|
||||
<span id="cp-at">Installed at</span> <code id="cp-path" class="ms-1">/contact</code>
|
||||
<span class="text-secondary ms-2" id="cp-edit">— edit it under Pages.</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mt-3">
|
||||
<div class="card-header">
|
||||
<h3 class="card-title" id="cn-title">Contact submissions</h3>
|
||||
<span class="ms-auto text-secondary"><span id="cn-count">0</span></span>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<!-- SMTP readiness row + operator-only self-test: a POST carrying the console's CSRF token (it sends an
|
||||
email); the plain-text result opens in a new tab. -->
|
||||
<div class="d-flex align-items-center mb-3" id="cn-smtp">
|
||||
<span class="me-2" id="cn-smtp-label">SMTP relay</span>
|
||||
<span id="cn-smtp-ok" class="badge bg-success-lt">Configured</span>
|
||||
<span id="cn-smtp-missing" class="badge bg-red-lt">Not configured</span>
|
||||
<form id="cn-smtp-test-form" method="post" action="/contact/smtp-test" target="_blank" rel="noopener"
|
||||
class="m-0 ms-auto">
|
||||
<input id="cn-csrf" type="hidden" name="_csrf" value="">
|
||||
<button id="cn-smtp-test" type="submit" class="btn btn-sm btn-outline-secondary">
|
||||
<i class="fa-solid fa-paper-plane me-1"></i><span id="cn-smtp-test-label">Send a test email</span></button>
|
||||
</form>
|
||||
</div>
|
||||
<p class="text-secondary mb-0" id="cn-empty">No submissions yet.</p>
|
||||
<div class="table-responsive" id="cn-table">
|
||||
<table class="table table-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th id="cn-h-when">When</th>
|
||||
<th id="cn-h-name">Name</th>
|
||||
<th id="cn-h-email">Email</th>
|
||||
<th id="cn-h-msg">Message</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr id="cn-row">
|
||||
<td class="cn-when text-nowrap">time</td>
|
||||
<td class="cn-name">name</td>
|
||||
<td class="cn-email">email</td>
|
||||
<td class="cn-excerpt">excerpt</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-footer">
|
||||
<a id="cn-help" href="/__plugin/contact/static/contact-help.html" target="_blank" rel="noopener">
|
||||
<i class="fa-solid fa-circle-question me-1"></i><span id="cn-help-label">Contact help & reference</span></a>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,57 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Admin fragment logic. The recent-submissions table repeats #cn-row over ${@contactAdminModel.recent(...)};
|
||||
nested cells use '//' descendant selectors (pitfall #8). The empty note and the table are mutually exclusive
|
||||
via th:if on the count. The SMTP readiness row shows exactly one of the two badges via th:if. -->
|
||||
<thlogic>
|
||||
<!-- "Contact page" card: exactly one of the two blocks shows, gated on the live install status. The install
|
||||
form's action is the constant /contact/install-page in the static markup (no th:action: the restricted
|
||||
URL/attr context forbids ${@bean}); the live path is bound with th:text (which permits @bean). The hidden
|
||||
field carries the console session's CSRF token (the request attribute _csrf, never a bean), which the
|
||||
kernel's tenant chain demands on this non-anonymous POST. -->
|
||||
<attr sel="#cp-title" th:text="#{contact.page.card.title}"/>
|
||||
<attr sel="#cp-install" th:if="${!@contactAdminModel.pageInstalled(tenantSiteId)}"/>
|
||||
<attr sel="#cp-desc" th:text="#{contact.page.card.desc}"/>
|
||||
<attr sel="#cp-csrf"
|
||||
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
|
||||
<attr sel="#cp-install-btn" th:title="#{contact.page.card.install.tip}"/>
|
||||
<attr sel="#cp-install-label" th:text="#{contact.page.card.install}"/>
|
||||
<attr sel="#cp-installed" th:if="${@contactAdminModel.pageInstalled(tenantSiteId)}"/>
|
||||
<attr sel="#cp-badge" th:text="#{contact.page.card.badge}"/>
|
||||
<attr sel="#cp-at" th:text="#{contact.page.card.at}"/>
|
||||
<attr sel="#cp-path" th:text="${@contactAdminModel.pagePath(tenantSiteId)}"/>
|
||||
<attr sel="#cp-edit" th:text="#{contact.page.card.edit}"/>
|
||||
|
||||
<attr sel="#cn-title" th:text="#{contact.admin.title}"/>
|
||||
<attr sel="#cn-count" th:text="${@contactAdminModel.count(tenantSiteId)}"/>
|
||||
|
||||
<!-- SMTP readiness: exactly one badge; the self-test link's label. -->
|
||||
<attr sel="#cn-smtp-label" th:text="#{contact.admin.smtp}"/>
|
||||
<attr sel="#cn-smtp-ok" th:if="${@contactAdminModel.smtpConfigured(tenantSiteId)}"
|
||||
th:text="#{contact.admin.smtp.ok}"/>
|
||||
<attr sel="#cn-smtp-missing" th:if="${!@contactAdminModel.smtpConfigured(tenantSiteId)}"
|
||||
th:text="#{contact.admin.smtp.missing}"/>
|
||||
<!-- No th:action: the action is the constant /contact/smtp-test already in the static markup, and BOTH
|
||||
th:attr AND the dedicated URL processors (th:href/th:action) evaluate in a RESTRICTED context that forbids
|
||||
${@bean} access (unlike th:text/th:if/th:value) — binding the URL from the bean here would 500 this
|
||||
fragment. The CSRF field reads the _csrf request attribute (not a bean), and the title is a message. -->
|
||||
<attr sel="#cn-csrf"
|
||||
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
|
||||
<attr sel="#cn-smtp-test" th:title="#{contact.admin.smtp.test.tip}"/>
|
||||
<attr sel="#cn-smtp-test-label" th:text="#{contact.admin.smtp.test}"/>
|
||||
|
||||
<attr sel="#cn-empty" th:if="${@contactAdminModel.count(tenantSiteId) == 0}" th:text="#{contact.admin.empty}"/>
|
||||
<attr sel="#cn-table" th:if="${@contactAdminModel.count(tenantSiteId) > 0}"/>
|
||||
|
||||
<attr sel="#cn-h-when" th:text="#{contact.admin.when}"/>
|
||||
<attr sel="#cn-h-name" th:text="#{contact.form.name}"/>
|
||||
<attr sel="#cn-h-email" th:text="#{contact.form.email}"/>
|
||||
<attr sel="#cn-h-msg" th:text="#{contact.form.message}"/>
|
||||
|
||||
<attr sel="#cn-row" th:each="s : ${@contactAdminModel.recent(tenantSiteId)}"/>
|
||||
<attr sel="#cn-row//.cn-when" th:text="${s.time()}"/>
|
||||
<attr sel="#cn-row//.cn-name" th:text="${s.name()}"/>
|
||||
<attr sel="#cn-row//.cn-email" th:text="${s.email()}"/>
|
||||
<attr sel="#cn-row//.cn-excerpt" th:text="${s.excerpt()}"/>
|
||||
|
||||
<attr sel="#cn-help-label" th:text="#{contact.admin.help}"/>
|
||||
</thlogic>
|
||||
@@ -0,0 +1,15 @@
|
||||
<!-- Tenant dashboard card fragment — __plugin__/contact/dashboard. Bare fragment; binding in .th.xml. -->
|
||||
<div class="card">
|
||||
<div class="card-status-start bg-teal"></div>
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<span class="bg-teal-lt avatar"><i class="fa-solid fa-envelope"></i></span>
|
||||
<div class="ms-3">
|
||||
<div class="fw-bold" id="cd-title">Contact</div>
|
||||
<div class="text-secondary small">
|
||||
<span id="cd-count">0</span> <span id="cd-count-lbl">submissions</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Dashboard card logic. Values from ${@contactAdminModel...(tenantSiteId)}. -->
|
||||
<thlogic>
|
||||
<attr sel="#cd-title" th:text="#{contact.card.title}"/>
|
||||
<attr sel="#cd-count" th:text="${@contactAdminModel.count(tenantSiteId)}"/>
|
||||
<attr sel="#cd-count-lbl" th:text="#{contact.card.submissions}"/>
|
||||
</thlogic>
|
||||
Reference in new issue
Block a user