Runway 1.0.0

This commit is contained in:
Runway committed 2026-10-21 11:34:34 -06:00
commit dcf819146b
1372 files changed
+188168

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
# Changelog
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
## [2.3.0] — 2026-10-21
First public release of `search`: on-site search with a search-box widget that renders results on an editable
page, a JSON API, highlighted
matches and a no-results log; each language searches its own text. Publishes its own SPI (`SearchCorpus`,
`SiteSearchEngine`) so an engine plugin such as `search-lucene` can replace the built-in engine. 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`).
+661
View File
@@ -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/>.
+44
View File
@@ -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.
+56
View File
@@ -0,0 +1,56 @@
# Runway Search plugin
On-site search for [Runway](../README.md) sites: an embeddable **search box**, an installable, editable
**`/search`** results page (created `noindex` — the canonical opt-out for search results), a **`/search/api`**
JSON endpoint, and a built-in **full-text** engine over the site's published content — your pages AND any
content source's items (blog entries, product pages, …), titles, descriptions and bodies alike — backed by the
plugin's own SPI, so a companion plugin (`../search-lucene`) can upgrade the engine with no change to the search UX.
Since 2.0.0 it links **only the Runway SPI** (needs a kernel whose SPI is `1.0.0` or later).
- **Plugin id:** `search` — install folder `external/plugins/search/`
- **Java package:** `mx.quest.search` · **Published SPI:** `mx.quest.search.spi.SearchCorpus` (what every engine
indexes) and `mx.quest.search.spi.SiteSearchEngine` (the engine extension point)
## What it adds
| Surface | Where |
|---|---|
| Search box widget | `<div id="x" data-widget="search/box"></div>` on any page/master |
| Results page | an installed, editable tenant page at `/search` carrying the query-aware box widget (created `noindex`; styled by `/__plugin/search/static/search.css`); installed through the kernel's `SitePages`, so it follows the site's editorial level (published, waiting for review, or a draft the quality checks blocked) |
| JSON API | `GET /search/api?q=…` → `{query,count,results:[{url,title,snippet,score,link,terms}]}` (rate-limited per client IP as the kernel's trusted-proxy gate resolved it, `noindex`) |
| Corpus | `SearchCorpus`: every published page and content item of the kernel's `ContentCatalogView`, minus the site's exclude list — what the built-in engine and `search-lucene` both index |
| Built-in engine | full-text match over each item's title + description + **body**, in the item's own language, linked at its real URL |
| Highlighted snippets | `<mark>`-wrapped, length-bounded, XSS-safe (escape-then-mark) |
| Highlight on the result page (2.1.0) | a result link carries the matched words (`#rw-hl=…`); the page it opens highlights them and scrolls to the first (CSS Custom Highlight API, restyle with `::highlight(rw-search)`); per-site switch `highlight` |
| Box only in the chrome (2.1.0) | a header/footer box no longer repeats the results on the results page; per-placement `results` setting (`auto`/`always`/`never`) on Site → Content widgets |
| Instant freshness | any page write, content-source change, site lifecycle event or plugin settings save drops that site's index at once (the plugin's `SiteEventListener`); the TTL is only the backstop |
| Operator actions | the **Rebuild index** and **Install search page** buttons and **Clear list** — CSRF-checked `POST /search/reindex`, `/search/install-page`, `/search/no-results/clear`, gated by the `search|settings` control point |
| Searches with no results | opt-in per site (**off by default** — terms can be personal data): term + count + last seen, bounded (500 terms, 90-day retention by default), never an IP or a user; listed on the settings page with a Clear action; **declared personal data**, so a site's transfer copy leaves it out |
| App settings | index freshness + per-client rate limit (`runway.plugin.search.*`) |
| Per-site settings | enable, max results, results page path, placeholder, exclude list, snippet length, highlight on the result page, ranking weights, no-result recording + its retention |
| Console | a tenant dashboard card + an admin status panel (searchable items, active engine, the two buttons) + the no-result searches card |
## Build
```bash
export JAVA_HOME=/path/to/jdk-25
mvn -q verify
# → target/runway-plugin-search.jar
# target/search/ (cp -r into <external>/plugins/ and restart)
# target/runway-plugin-search-2.3.0.zip (upload at /__app/plugins → install)
HOST_JAR=/path/to/runway/runway-app/target/runway-app-<version>-exec.jar \
JAVA_HOME=/path/to/jdk-25 scripts/verify-against-host.sh # boots the PACKAGED host and proves the contract live
```
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 build is reproducible: two builds of the same source give a byte-identical zip.
See [`docs/SEARCH-PLUGIN.md`](docs/SEARCH-PLUGIN.md) for the design and the SPI contract.
## 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, including
search's own SPI for engines, may carry any license.
+332
View File
@@ -0,0 +1,332 @@
# Runway Search plugin — design & reference
> On-site search as a **query surface + a swappable engine over one corpus**. `search` publishes its own SPI —
> `SearchCorpus` (what every engine indexes) and `SiteSearchEngine` (the engine extension point); `../search-lucene`
> implements the second and reads the first. Since 2.0.0 the plugin links **only the Runway SPI** (service tier,
> SPI `1.0.0`). See the shared `../docs/PLUGIN-AUTHORING-GUIDE.md` and
> [`docs/PLUGIN-DEVELOPMENT.md`](../../../docs/PLUGIN-DEVELOPMENT.md) at the root of the repository for the seams.
## 1. What it does
- **Query-aware search box** — a `ContentWidget` (`key = "search"`). A site manager drops
`<div id="site-search" data-widget="search/box"></div>` on any page or the master chrome; the widget renders a
GET form that submits `?q=` to the site's results page (the `resultsPath` setting, default `/search`). It is
**query-aware** (kernel `WidgetView.query()`): when the page carrying it is opened with a non-blank `q`, it
renders the ranked results **inline below the box** (referencing the plugin's own `/__plugin/search/static/search.css`,
which a site overrides to match its theme). So the results page is a **normal, editable tenant page**, not a
plugin-owned surface. Its words come from `Messages.site` (the site's bundle first, then this plugin's) for the
request locale. **Where results are listed (2.1.0):** each placement has a `results` setting (Site → Content
widgets, `widgetSettings` in `plugin.yml`): `auto` (the default) lists them unless the box sits in the **master
chrome** (`WidgetView.isChrome()`), so a header or footer box does not repeat the results page's list; `always`
and `never` override that. Before 2.1.0 every box on a page opened with `?q=` listed the results.
- **Result highlighting (2.1.0)** — the page a result opens highlights the words the search matched there and
scrolls to the first visible one. How it travels:
1. The engine reports the matched words **as the page writes them** (`SearchHit.terms`, §2): the built-in engine
the whole words around each match, `search-lucene` the surface forms its analyzer matched (stemming and typo
tolerance included: `maestría` finds `maestrías`).
2. Each result link (inline results and the API's `link`) carries them in the fragment:
`/mba#rw-hl=maestr%C3%ADas%20maestr%C3%ADa` (`HighlightMarker`). A fragment never reaches the server, so the
target page is served and cached exactly as without it.
3. `SearchHighlightHead` (a `HeadContributor`) puts one `<script src=".../highlight-loader.js" defer>` on every
page of a site with search and `highlight` on. The loader (~500 bytes) does nothing unless the address carries
the marker; then it loads `highlight.js`, which highlights every whole-word occurrence (ignoring case) inside
`<main id="content">` (else `<main>`, else `<body>`) with the **CSS Custom Highlight API** (no DOM change), at
most 200, scrolls to the first visible one, and removes the marker with `history.replaceState`. A
`hashchange` re-runs it. It adds `highlight.css` before the site's own stylesheets, so a site restyles it with
its own `::highlight(rw-search) { … }`.
- **Why an external loader and not an inline script:** the kernel stamps the CSP nonce only on scripts its host
allowlist would also run, so an inline script stays blocked under `enforce`. **Cost:** the loader is referenced
by every page. A browser keeps it for an hour (`runway.http-cache.plugin-assets`) and then revalidates it
against its ETag. Every plugin file URL ends in `?v=<version>` (`SearchConfig.VERSION`), so the next release's
files are fetched at once. Turning `highlight` off removes the loader.
- **Browsers:** the Highlight API is in Chrome/Edge 105+, Safari 17.2+ and Firefox 140+. Elsewhere nothing is
highlighted and the marker is still removed.
- **Limits:** a match split across inline elements (`<b>mae</b>stría`) is not found. Text outside the content
slot is not highlighted, by design: with no `#content` or `<main>`, the script searches `<body>` but skips
`<header>`, `<nav>`, `<footer>` and `<aside>`, so it never scrolls to a menu item. Java lowercases the Turkish
capital `İ` to `i` plus a combining dot, which a browser never matches case-insensitively, so the script lets
every `i` match `İ` (`src/test/js/highlight-pattern.js`).
- **JSON API** — `GET /search/api?q=…` (`EndpointContributor`, tenant realm, `noindex`) returns the results as
JSON (`{query,count,results:[{url,title,snippet,score,link,terms}]}`) for a site's own scripts (e.g. an
autocomplete box). `link` (2.1.0) is the URL with the highlight marker (the plain URL when `highlight` is off);
`terms` the matched words as plain text.
Rate-limited per client (`SearchRateLimiter`, §4). Every string is JSON-escaped and the angle brackets are
unicode-escaped so a payload embedded in an HTML `<script>` can't break out. (The HTML results rendering lives
in the widget; rendered during page render it carries no search-specific limiter — the kernel's edge
protection and `resultLimit` bound a flood — while the JSON API keeps its dedicated limiter.)
- **The corpus** — `SearchCorpus` (§2): the kernel's content listing (`ContentCatalogView.entries`: every
**published** real page and every content source's item — blog entries, … — re-filtered fail-closed by the
host, with host-computed URLs) **minus the site's `exclude` list and its results page** (the page at
`resultsPath`, in all its languages; since 2.1.1, because it matched the subjects it describes and was listed
among its own results). Every engine builds from it, so the exclusion rule lives in one place.
- **Built-in engine** — `SimpleSearchEngine`, a dependency-free full-text matcher. Since 2.2.0, **one document per
corpus entry and language it exists in**: localized **title**, **description**, and the plain-text **body**
(`SearchCorpus.indexableText` for that language — the page as rendered there, bundle strings included —
reduced by `HtmlText`), linked at `CatalogEntry.pathFor` that language — the item's real address there.
A query searches the documents of its own language (`SearchQuery.locale()`: the results page's
language, or the API's `?lang=`) plus, for an item that does not exist in that language, the item's
**primary-locale** document (the site's default language when the item exists in it, else its first language),
so a page in one language only is still found from every other; a language the site does not speak searches the
site default's documents. (Before 2.2.0 only the primary-locale document existed.) It holds a small
per-site index (at most 512 sites, least recently used dropped first), **dropped the moment anything that may
reshape the corpus changes** (§3), with the freshness TTL kept as the backstop for changes nobody announces (a
file edited by hand). Always available; no external index.
- **Configurable ranking** (per-site): `titleWeight` (8), `descriptionWeight` (4), `bodyWeight` (1 per
occurrence, capped at 20 occurrences per term), plus flat bonuses for containing **all** terms
(`allTermsBonus`) and the whole query as a **phrase** in the title/body (`phraseTitleBonus`/`phraseBodyBonus`).
All data — a site tunes ranking with no code change.
- **Highlighted snippets** built by `SearchSnippet` from the body (falling back to the description),
honouring the frozen `SearchHit.snippet` contract (see §5).
- **Operator maintenance** — three **CSRF-checked `POST`s** reached from buttons on the plugin's settings page,
each gated by the `search|settings` control point (`AccessCheck`), fail-closed to `404`, answered in the
operator's language (`Messages.console`):
- `POST /search/reindex` — rebuilds this site's index on **every** registered engine via the SPI's `reindex`
hook (the built-in and any contributed engine alike), reporting the fresh document count of the engine that
actually serves the site's queries. The built-in engine first refreshes the kernel's listing
(`SearchCorpus.refresh`): the button exists for changes no event announced. The settings page's **Rebuild
index** button submits it (the plain-text answer opens in a new tab).
- `POST /search/install-page` — installs a first-class, master-wrapped tenant page at `/search` carrying the
query-aware search-box widget anchor, through the kernel's `SitePages.install`, which **never overwrites** and
follows the site's **editorial level**. The operator is told what happened: *installed at /search*
(`PUBLISHED`), *waiting in the review queue* (`PENDING_REVIEW`: a Reviewed site and a user without
`APPROVE_PAGES`), *created as a draft because the quality checks blocked publishing* with each blocking
finding listed (`DRAFT_BLOCKED`: an Enforced site, or a Reviewed one with approval, whose checks fail), or
*already exists at <path>* (`ALREADY_EXISTS`, wherever the page now lives). Once installed it is an ordinary
site page — listed under Pages, restyleable, movable — so the operator owns the results page. It is created
**`noindex`** — the canonical index opt-*out* for internal search results (thin/duplicate/infinite crawl
space); since the page is the operator's own after install, the setting can be flipped in the page meta.
- `POST /search/no-results/clear` — forgets the site's recorded no-result terms (below), then `303`s back to
the settings page.
- **Searches with no results** (since 2.0.0; `NoResultsLog`) — the platform's own content-gap signal: a per-site list of what visitors searched for and did not find, shown on the settings page
with a **Clear list** action. Both the widget (inline results) and the JSON API hand a query that found nothing
to `NoResultsLog.record`.
- **Why it is off by default.** A search term is free text a visitor typed; people search for names, email
addresses, order or phone numbers. Recording is therefore an explicit per-site choice (`recordNoResults`,
default `false`) rather than something an upgrade turns on silently. When it is on, the list holds **only a
normalized term, a count, and a last-seen time** — no IP, no user, no session, no per-search timestamp — and
a term that looks like an email address (an `@` followed by a dot) or a phone / ID number (seven or more
digits in a run, ignoring spaces, dashes, dots, slashes, parentheses and `+`) is dropped unrecorded. The
term never appears in an application log line (a failure logs the site and the exception class only).
- **Declared personal data (2.0.0).** `plugin.yml` declares `siteData.personal: [no-results.tsv]`, so a
site's **transfer copy** (the one meant for someone outside the organisation) leaves the file out and lists it
under `omitted:` in the archive's `manifest.yml`; a **full backup** keeps it. A restored transfer copy simply
starts with an empty list.
- **Normalization.** Unicode NFC, control/format characters removed, whitespace runs collapsed to one space,
trimmed, lower-cased (`Locale.ROOT`), cut at 100 characters without splitting a surrogate pair — so
"Opening Hours" and "opening hours" are one entry.
- **Bounds.** At most **500** terms per site: admitting a new term to a full list evicts the least frequent one
(the longest-unseen among equals), so a flood of one-off junk churns only the bottom and recurring gaps
survive. A term not searched for `noResultsRetentionDays` (default 90) drops off listings and the next
write. The same term on the same site within one second counts once — a page with a box in the master
chrome *and* one in the content renders (and would record) the same empty result twice per request.
- **Storage.** In memory per site, loaded lazily from `no-results.tsv` in the plugin's own per-site folder
(`PluginSiteFiles`: `sites/<id>/plugins/search/no-results.tsv`); written atomically by
a background flush every 30 s when something changed and on shutdown, never synchronously on the public search
path. A crash loses at most the last 30 s. On a site lifecycle event that replaces the site wholesale
(`RESTORED` / `DELETED`) the in-memory copy is dropped **unwritten**, so the restored file is what is read
next and a deleted site's list is never written back (a late write for a missing site folder fails rather than
creating it). A file over 512 KiB is ignored rather than read. A file that **cannot be read** (an I/O error) is
never overwritten: the site's list stays unloaded — nothing is recorded for it — until a read succeeds.
- **What it does not see.** Searches served from an engine that returns results are not recorded; a site whose
search is disabled records nothing; a search box rendered from a cached page response (if a proxy caches
`?q=` pages) never reaches the plugin.
## 2. The plugin's own SPI (`mx.quest.search.spi`)
```java
public interface SearchCorpus { // since 2.0.0 — one bean, `searchCorpus`, injected by type
List<CatalogEntry> corpus(String siteId); // the kernel's listing minus the site's `exclude` list
String indexableText(String siteId, CatalogEntry entry, Locale locale); // "" for an excluded entry
void refresh(String siteId); // drop the kernel's cached listing (manual reindex)
}
public interface SiteSearchEngine { // unchanged since 1.2.0
String key(); // stable, namespaced, e.g. "search/simple"
List<SearchHit> search(SearchQuery query); // best-first, ≤ query.limit(); empty = no matches
default int priority() { return 0; } // higher wins
default boolean available(String siteId) { return true; } // false ⇒ fall back to the next engine
default int reindex(String siteId) { return 0; } // rebuild derived state NOW; returns the fresh doc count
}
record SearchQuery(String siteId, String text, Locale locale, int limit) {}
record SearchHit(String url, String title, String snippet, double score, List<String> terms) {
SearchHit(String url, String title, String snippet, double score) // the 2.0.0 form: no terms
}
```
**Why `SearchCorpus` exists.** Before 2.0.0, `search-lucene` read the kernel's
`ContentCatalog` and **this plugin's settings** (`SitePluginConfigService.config(site, "search")`) to apply the
`exclude` list itself — host linkage, and a cross-plugin settings read the service tier forbids
(`PluginSettings` only ever returns the *calling* plugin's settings). Now `search` reads its own settings and
publishes the filtered corpus; an engine never touches either.
- **Exclusion rule.** An entry is left out when its **own id** (`entry.ref().id()`: a page's slug, a content
source's item id — never the composite `source:id`) equals, ignoring case, one of the `exclude` values; a leading
`/` and blanks around a value are ignored. A YAML list or a comma/newline-separated string.
- **Freshness.** Nothing is cached on the plugin side: every call reads the kernel's listing (cached per site by the
kernel, evicted by every change that can reshape it) and the current settings. An engine with an index of its own
drops it from a `SiteEventListener.onCatalogChanged` callback for **every** cause — a page write, a content
change, a site lifecycle event, and any plugin's settings save (this plugin's `exclude` list included).
- **Rules.** Every method takes a site id; an unsafe id throws `IllegalArgumentException`, an unknown site answers
empty or `""`; thread-safe; never `null`.
Both interfaces are **binary API**: they evolve by adding `default` methods only — `reindex` (added in 1.2.0)
defaults to a no-op returning `0`, so an engine compiled against an earlier SPI keeps loading unchanged.
`SiteSearchEngine`, `SearchQuery` and `SearchHit` did not change in 2.0.0: an engine built against 1.x links and
behaves the same. **2.1.0 adds `SearchHit.terms`** — the words the engine matched, as the item writes them;
lowercase, distinct, at most 20 of at most 64 characters (the record normalizes them). The four-argument
constructor stays, so an engine built before 2.1.0 still links and its hits simply carry no words (no highlight on
the target page). An engine that fills `terms` calls the five-argument constructor and must therefore declare
`requires: search >= 2.1.0` (`search-lucene` 3.1.0 does).
The `SearchEndpoint` and the widget inject `List<SiteSearchEngine>` and, per request, select the
highest-`priority()` engine whose `available(siteId)` is true. So:
- **Installing `search-lucene`** (which registers an engine at priority 100 and is available once its index
exists) **transparently upgrades** search — the widget and endpoint are untouched.
- If the Lucene index isn't built yet (`available()` false), the surface **falls back** to the built-in engine —
a not-yet-built index never breaks search.
`search-lucene` compiles against this plugin's jar as a `provided` dependency and declares `requires: search`; at
runtime both plugin jars share one classloader, so the SPI types have one `Class` identity.
## 3. Freshness: the plugin's change listener
`SearchSiteEvents` is the plugin's one `SiteEventListener` (phase `CONSUMER`: it reads the listing, contributes
none). The kernel delivers it **after** every kernel cache the change affects has been evicted and after every
content source dropped its own state, and never while the host holds a write lock.
| Callback | What the plugin does |
|---|---|
| `onCatalogChanged` (every cause: `PAGE`, `CONTENT`, `SITE`, `SETTINGS`) | drops the built-in engine's index for the site; the next query rebuilds from the new state |
| `onSiteLifecycle` with `wholesale()` (`RESTORED`, `DELETED`) | `NoResultsLog` forgets the site's in-memory list unwritten |
Both run on every node, for local and replayed changes alike — they only drop local state. A query that was
building the index while a change arrived (another thread) answers its own caller but is **not cached**, so a
build that may have read the old state never outlives the change.
## 4. Settings
### App-level (`settings`, superadmin, applied on restart — platform concerns only)
Bound from `external/plugin-settings/search.yml` (prefix `runway.plugin.search`) into `SearchProperties`, through
the `@ConfigurationProperties` on the `searchProperties` `@Bean` (not `@EnableConfigurationProperties`, whose
generated bean name would break the plugin bean-name rule).
| Key | Type | Default | Effect |
|---|---|---|---|
| `refresh-minutes` | int (1–1440) | `60` | Freshness TTL of a built-in per-site index before the next query rebuilds it. Changes the kernel announces are reflected immediately (§3); the TTL re-captures what nobody announces. |
| `rate-limit.per-ip-per-minute` | int (0 = off) | `30` | Per-client query ceiling on the JSON API, per minute. |
| `rate-limit.per-ip-per-hour` | int (0 = off) | `600` | Per-client query ceiling on the JSON API, per hour. |
These are deliberately **not** per-tenant — a tenant must not set a global timer or an abuse limit.
### Per-tenant (`siteSettings`, applied immediately)
| Key | Type | Default | Effect |
|---|---|---|---|
| `enabled` | boolean | `true` | Off ⇒ the box (and its inline results) render nothing and the JSON API 404s (opt out without uninstalling). |
| `resultLimit` | int (1–100) | `20` | Max hits shown inline / returned by the API. |
| `resultsPath` | string | `/search` | Where the box submits `?q=` — the results page carrying this widget, by any of its addresses; set it if you move/rename that page. Since 2.2.0 a box on a localized page submits to that page's address in the box's language (`/es/buscar` from a Spanish page), else to this value as written. |
| `placeholder` | string | — | The search box's greyed prompt (falls back to a localized default). |
| `exclude` | list | — | Ids kept out of every engine's corpus: page slugs and content-source item ids. |
| `snippetLength` | int (40–400) | `160` | Characters of context per result snippet. |
| `highlight` | boolean | `true` | Result links carry the matched words and the site's pages highlight them (§1, 2.1.0). Off: plain links, no loader on the pages. |
| `titleWeight` / `descriptionWeight` / `bodyWeight` | int | `8` / `4` / `1` | Ranking weight per field. |
| `allTermsBonus` / `phraseTitleBonus` / `phraseBodyBonus` | int | `1000` / `400` / `300` | Flat ranking bonuses. |
| `recordNoResults` | boolean | `false` | Keep the "Searches with no results" list (§1). Off by default because terms can be personal data. |
| `noResultsRetentionDays` | int (1–365) | `90` | A recorded term nobody searched for in this many days drops off the list. |
Read live through the kernel's `PluginSettings.site(siteId)` (bound to this plugin by its jar): the stored value,
else the descriptor default, else the code fallback — and every code fallback in `SearchSiteConfig` equals its
descriptor default (`SearchConfigTest` holds them equal). The `settings` control point gates the editor **and**
the operator maintenance actions.
## 5. Boundaries & safety
- **Every state change is a CSRF-checked `POST`.** Reindex, install-page and clear change state (an index is
rebuilt, a page is created, data is deleted), so each is an ordinary, non-anonymous `POST` route. The plugin
endpoint is servlet-free, but it is dispatched *inside* the tenant security chain, whose CSRF filter checks the
`_csrf` field the admin fragment's forms render from the console page (`${_csrf}`). A `GET` on those paths
matches no route (the kernel answers `404`), so another web site cannot trigger them through a signed-in
operator's browser with a link or an `<img>` — which 1.x's `GET /search/reindex` and `GET /search/install-page`
allowed. `scripts/verify-against-host.sh` proves it live: `GET` 404, no token 403, forged token 403, an
anonymous caller with a valid token 404 (the permission check), the console's token accepted. The only `GET`s are
the JSON API (a read) and the box's own form (a `GET` to the results page — an ordinary tenant page).
- **No-result terms are visitor text.** The admin card binds them with `th:text` only; they never reach a log
line; recording is opt-in per site; the file is declared personal data (§1).
- **The `snippet` safety contract (frozen).** A `SearchHit.snippet` is **pre-escaped, highlight-bearing HTML**:
the engine HTML-escapes every character from the page and leaves `<mark>…</mark>` — and nothing else — as raw
markup around the matched terms. The widget therefore renders the snippet as **raw HTML** (so the
highlight shows as emphasis, not literal `&lt;mark&gt;`), which is XSS-safe precisely because escaping happened
at the engine — a crafted page title or body cannot forge a tag. `SearchSnippet` does escape-then-mark; both the
built-in engine and `search-lucene` honour the contract, so the one raw-render serves both.
- **Output safety.** The query, page titles, and every non-snippet value are escaped by `Html.escape`; the JSON
API escapes strings and unicode-escapes angle brackets. The JSON API is `noindex`; the results page is a normal
tenant page **installed with `noindex` on**, and the operator owns its page meta and can flip it.
- **Abuse guard.** `SearchRateLimiter` caps the **JSON API** per client with two fixed windows (a minute and an
hour, each starting at the client's first query in it); over the ceiling ⇒ `429` with
`{"error":"rate_limited"}`. A blank query is not counted. **The key is `RouteRequest.clientIp()`** — the client
address after the kernel's **trusted-proxy gate**: a forwarded header counts only when the
immediate peer is a configured trusted proxy. 1.x keyed on the first `X-Forwarded-For` hop it read itself, so a
visitor could send a made-up header per request and never be limited. A request with no client IP shares one
`shared` bucket rather than escaping. The table holds at most 50,000 clients: when full, clients whose windows
have expired are dropped first, and if all are active the table restarts (fails open — this is a courtesy limit;
the kernel edge guard is the platform's DoS floor beneath it, and also bounds the inline results the widget
renders during page render).
- **No host internals.** The compiled classes reference nothing under `mx.quest.runway` but `mx.quest.runway.spi`
(`SearchConfigTest` scans the bytecode; the kernel's load-time scanner reports nothing), and nothing of Caffeine
either: it is a kernel implementation detail, not one of the platform libraries a plugin may rely on.
- **Isolation.** Every surface is scoped to the bound tenancy (`req.site().id()` / `view.site().id()`); the index
is keyed per site, so one tenant never sees another's content; the plugin's files are confined by the kernel to
`sites/<id>/plugins/search/`.
## 6. Inventory
| Piece | Type | File |
|---|---|---|
| `mainClass` `@Configuration` | `SearchConfig` | wires every bean explicitly over SPI services; every bean name starts with `search` |
| **Published SPI** | `spi/SearchCorpus`, `spi/SiteSearchEngine` + `SearchQuery` + `SearchHit` | the corpus and the extension point |
| Corpus | `SiteSearchCorpus` | `ContentCatalogView` minus the `exclude` list (`PluginSettings`) |
| Built-in engine | `SimpleSearchEngine` | full-text over title/description/body, bounded per-site index cache |
| Change listener | `SearchSiteEvents` (`SiteEventListener`, `CONSUMER`) | drops the index on every catalog change; forgets the no-result list on a wholesale lifecycle event |
| Body extraction | `HtmlText` | HTML → plain text for indexing (strips script/style/comments/tags) |
| Snippet builder | `SearchSnippet` | escape-then-mark; honours the frozen snippet contract |
| Indexed document | `SearchDocument` | one per item: display + pre-lowercased match fields |
| Request endpoint | `SearchEndpoint` (`EndpointContributor`) | `GET /search/api`; `POST /search/reindex`, `/search/install-page`, `/search/no-results/clear` (no `/search` page) |
| No-result terms | `NoResultsLog` | opt-in per-site content-gap list over `PluginSiteFiles` (`no-results.tsv`, declared personal) |
| Rate limiter | `SearchRateLimiter` + `SearchClientId` | per-client two-window courtesy cap (JSON API), keyed on the gated client IP |
| Query-aware search box | `SearchBoxWidget` (`ContentWidget` `search`) | embeddable GET form + inline results when `?q=` (per-placement `results`) |
| Result highlighting | `MatchedWords`, `HighlightMarker`, `SearchHighlightHead` (`HeadContributor`), `static/highlight-loader.js`, `static/highlight.js`, `static/highlight.css` | the matched words, the `#rw-hl=` link marker, the page script |
| App settings | `SearchProperties` | `runway.plugin.search.*` (refresh + rate-limit) |
| Per-site settings | `SearchSiteConfig` | typed accessors over `SettingsView` |
| Console model | `SearchAdminModel` + `templates/` | dashboard card + admin status (searchable items = the corpus size) + the forms |
| i18n (EN/ES), static (help + CSS) | `i18n/`, `static/` | console + public strings |
## 7. Verify
`scripts/verify-against-host.sh` builds the plugin offline (never `mvn install`), drops it into a throwaway
deployment (`VERIFY_TMPDIR`), boots the **packaged** host (`HOST_JAR`, else the host checkout's jar matching its pom
version) in ACTIVE mode via the first-run wizard, with three sites (Advisory, Enforced, Reviewed) and loopback made
an **untrusted** peer, and proves the 2.1.1 contract: zero host-linkage and bean-name/surface warnings in the boot
log; the app settings bind; the JSON API serves and there is no `/search` page until one is installed; the three
operator actions are CSRF-checked POSTs (GET 404, no token 403, forged 403, anonymous-with-token 404) offered as POST
forms by the console; reindex reports a count; the starter page installs on all three editorial levels, renders
results inline and is `noindex`, and a second install changes nothing; the `exclude` list applies on the save; the
no-result list is off by default, records when on (never an email-like term), is flushed to the plugin's file,
carried by a full backup and **omitted (and listed) by a transfer copy**, and cleared only by the CSRF-checked POST;
made-up `X-Forwarded-For` headers do not evade the API's per-client ceiling while another address keeps its own
budget; result links (page and API) carry `#rw-hl=<words>`, every page carries the loader script stamped with the
nonce its CSP allows, and the loader, `highlight.js` and `highlight.css` are served. `VERIFY_LOG_DIR` keeps the host logs, the install answers and both backup manifests. Never
`spring-boot:run`.
Unit tests run on `runway-spi-testkit` (`FakePluginSettings`, `TempDirSiteFiles`, `FakeSiteServices`,
`FakeContentCatalog`, `EventDispatch`): `SearchConfigTest` (wiring over SPI services only, bean names, template
beans, descriptor floor/version/personal data, code fallbacks = descriptor defaults, bundles, the bytecode scan),
`SearchAdminTemplateTest` (every operator action is a POST form carrying the token; no link), `SiteSearchCorpusTest`,
`SimpleSearchEngineTest` (matching, ranking, exclusion, the primary-locale URL, every change cause dropping the
index, the raced build not kept, the bounded cache), `SearchEndpointTest` (routes, JSON API, rate-limit key, gated
reindex and install with every outcome), `SearchBoxWidgetTest`, `SearchAdminModelTest`, `NoResultsLogTest`,
`NoResultsRecordingTest`, `SearchRateLimiterTest`, `SearchSnippetTest`, `HtmlTextTest`, `HighlightTest` (matched words, the link marker, the
loader, the JSON fields, and the page script agreeing with the Java side) — 155 in all. The page script itself was
checked in Chrome under an enforcing CSP: highlights on arrival and on `hashchange`, the marker removed
with the query kept, no console error.
+92
View File
@@ -0,0 +1,92 @@
# Runway Search plugin — English strings. Appended LAST to the operator-console and every per-site message
# source (may ADD keys, never override a core key). Console labels resolve automatically; public-facing strings
# (search.box.*, search.results.*, search.page.title) are resolved with Messages.site for the site and the request
# locale; the operator actions' answers with Messages.console, in the operator's language.
# Grantable permission (permissions matrix label)
search.perm.settings=Configure search
# App-level settings form labels (superadmin; platform concerns)
search.set.refresh=Index freshness (minutes)
search.set.perMinute=Max searches per IP per minute (0 = no limit)
search.set.perHour=Max searches per IP per hour (0 = no limit)
# Per-tenant settings form labels
search.set.enabled=Enable search
search.set.resultLimit=Maximum results
search.set.resultsPath=Results page path
search.set.placeholder=Search box placeholder
search.set.exclude=Excluded content (one page slug or entry id per line)
search.set.snippetLength=Snippet length (characters)
search.set.highlight=Highlight the matches on the page a result opens
search.set.titleWeight=Title match weight
search.set.descriptionWeight=Description match weight
search.set.bodyWeight=Body match weight (per occurrence)
search.set.allTermsBonus=All-terms bonus
search.set.phraseTitleBonus=Title phrase bonus
search.set.phraseBodyBonus=Body phrase bonus
search.set.recordNoResults=Record searches with no results
search.set.noResultsRetention=Keep unrepeated terms for (days)
search.help.recordNoResults=Lists what visitors searched for and did not find, so you can see which content is missing. Off by default: search terms are typed by visitors and can contain personal data. Only the term, how often, and when it was last searched are kept — never an IP address or a user. Terms that look like an email address or a phone number are not kept.
search.help.highlight=A result link carries the words the search matched, and the page it opens highlights them and scrolls to the first one. The words travel after the # of the address, so they never reach the server, and they are removed from the address once the page has read them. Off: plain result links, and the small script that does this is not added to your pages.
search.help.noResultsRetention=A term nobody has searched for in this many days is dropped from the list.
# Dashboard card
search.card.title=Search
search.card.pages=searchable items
# Admin status fragment
search.admin.title=Search status
search.admin.enabled=Enabled
search.admin.engine=Active engine
search.admin.pages=Searchable items
search.admin.note=Add a search box to any page with a data-widget anchor; when a page is opened with ?q= it shows the results inline.
search.admin.help=Search help & reference
# "Search page" install card (admin fragment)
search.page.card.desc=Install a ready-made search results page carrying the box. It becomes a normal site page — edit, restyle, move or rename it from Pages.
search.page.card.install=Install search page
search.page.card.install.tip=Seed a ready-made, editable search results page (idempotent — it never overwrites an existing page)
search.page.card.badge=Installed
search.page.card.at=Installed at
search.page.card.edit=— edit it under Pages.
# Shared on/off
search.on=on
search.off=off
# Public-facing (search box widget + /search results page)
search.box.placeholder=Search…
search.box.submit=Search
search.results.heading=Search
search.results.none=No results for
search.results.count=result(s) for
search.rate.limited=Too many searches — please try again shortly.
# Maintenance actions + installed page (operator-only)
search.reindex.done=Search index rebuilt.
search.reindex.desc=Changed files outside the console? Rebuild the index now.
search.reindex.button=Rebuild index
search.reindex.tip=Re-read every page and content item and rebuild the search index of every engine now
search.page.title=Search
search.page.installed=Search page installed at
search.page.pending=The search page was created and is waiting in the review queue:
search.page.blocked=The search page was created as a draft because the quality checks blocked publishing; fix it in the page editor:
search.page.exists=A search page already exists at
search.page.failed=Could not install the search page.
search.page.other=The search page install finished:
# "Searches with no results" card (admin fragment)
search.noresults.title=Searches with no results
search.noresults.intro=What visitors searched for on this site and did not find — candidates for new pages, better titles or descriptions, or a redirect.
search.noresults.off=Recording is off for this site. Turn on "Record searches with no results" above to start the list.
search.noresults.col.term=Search term
search.noresults.col.count=Searches
search.noresults.col.lastSeen=Last searched
search.noresults.empty=No searches without results recorded yet.
search.noresults.retention=Terms nobody searched for in {0} days drop off the list; at most {1} terms are kept, the most frequent first.
search.noresults.clear=Clear list
search.noresults.clear.tip=Forget every recorded term for this site (it cannot be undone)
search.noresults.clearFailed=Could not clear the list of searches with no results.
search.widget.results=List the results here
search.widget.help.results=What this box shows when its page is opened with a search (?q=). auto: the results, unless the box is in the master template (a header or footer box), so the results page does not list them twice. always: the results, wherever the box is. never: only the box.
@@ -0,0 +1,89 @@
# Runway Search plugin — cadenas en español.
# Permiso otorgable (etiqueta de la matriz de permisos)
search.perm.settings=Configurar búsqueda
# Etiquetas de configuración a nivel de aplicación (superadmin; asuntos de plataforma)
search.set.refresh=Frescura del índice (minutos)
search.set.perMinute=Máx. búsquedas por IP por minuto (0 = sin límite)
search.set.perHour=Máx. búsquedas por IP por hora (0 = sin límite)
# Etiquetas del formulario de configuración por sitio
search.set.enabled=Activar búsqueda
search.set.resultLimit=Máximo de resultados
search.set.resultsPath=Ruta de la página de resultados
search.set.placeholder=Marcador del cuadro de búsqueda
search.set.exclude=Contenido excluido (un slug de página o id de entrada por línea)
search.set.highlight=Resaltar las coincidencias en la página que abre un resultado
search.set.snippetLength=Longitud del fragmento (caracteres)
search.set.titleWeight=Peso de coincidencia en el título
search.set.descriptionWeight=Peso de coincidencia en la descripción
search.set.bodyWeight=Peso de coincidencia en el cuerpo (por aparición)
search.set.allTermsBonus=Bonificación por todos los términos
search.set.phraseTitleBonus=Bonificación por frase en el título
search.set.phraseBodyBonus=Bonificación por frase en el cuerpo
search.set.recordNoResults=Registrar búsquedas sin resultados
search.set.noResultsRetention=Conservar términos no repetidos durante (días)
search.help.recordNoResults=Muestra lo que los visitantes buscaron y no encontraron, para ver qué contenido falta. Desactivado por omisión: los términos los escriben los visitantes y pueden contener datos personales. Solo se guarda el término, cuántas veces y cuándo se buscó por última vez — nunca una dirección IP ni un usuario. Los términos que parecen un correo electrónico o un número de teléfono no se guardan.
search.help.highlight=El enlace de cada resultado lleva las palabras que encontró la búsqueda, y la página que abre las resalta y se desplaza a la primera. Las palabras van después del # de la dirección, así que nunca llegan al servidor, y se quitan de la dirección en cuanto la página las lee. Desactivado: enlaces simples, y el pequeño script que hace esto no se agrega a tus páginas.
search.help.noResultsRetention=Un término que nadie ha buscado en estos días se quita de la lista.
# Tarjeta del panel
search.card.title=Búsqueda
search.card.pages=elementos indexables
# Fragmento de estado (admin)
search.admin.title=Estado de la búsqueda
search.admin.enabled=Activada
search.admin.engine=Motor activo
search.admin.pages=Elementos indexables
search.admin.note=Añade un cuadro de búsqueda a cualquier página con un ancla data-widget; cuando la página se abre con ?q= muestra los resultados en línea.
search.admin.help=Ayuda y referencia de búsqueda
# Tarjeta de instalación de la «Página de búsqueda» (fragmento admin)
search.page.card.desc=Instala una página de resultados de búsqueda lista para usar con el cuadro. Se convierte en una página normal del sitio: edítala, cámbiale el estilo, muévela o renómbrala desde Páginas.
search.page.card.install=Instalar página de búsqueda
search.page.card.install.tip=Crea una página de resultados de búsqueda lista y editable (idempotente: nunca sobrescribe una página existente)
search.page.card.badge=Instalada
search.page.card.at=Instalada en
search.page.card.edit=— edítala desde Páginas.
# on/off compartido
search.on=activada
search.off=desactivada
# De cara al público (widget de cuadro de búsqueda + página de resultados /search)
search.box.placeholder=Buscar…
search.box.submit=Buscar
search.results.heading=Búsqueda
search.results.none=Sin resultados para
search.results.count=resultado(s) para
search.rate.limited=Demasiadas búsquedas — inténtalo de nuevo en un momento.
# Acciones de mantenimiento + página instalada (solo operador)
search.reindex.done=Índice de búsqueda reconstruido.
search.reindex.desc=¿Cambiaste archivos fuera de la consola? Reconstruye el índice ahora.
search.reindex.button=Reconstruir índice
search.reindex.tip=Volver a leer cada página y contenido y reconstruir ahora el índice de búsqueda de todos los motores
search.page.title=Búsqueda
search.page.installed=Página de búsqueda instalada en
search.page.pending=La página de búsqueda se creó y está esperando en la cola de revisión:
search.page.blocked=La página de búsqueda se creó como borrador porque los controles de calidad bloquearon la publicación; corrígela en el editor de páginas:
search.page.exists=Ya existe una página de búsqueda en
search.page.failed=No se pudo instalar la página de búsqueda.
search.page.other=La instalación de la página de búsqueda terminó:
# Tarjeta "Búsquedas sin resultados" (fragmento de administración)
search.noresults.title=Búsquedas sin resultados
search.noresults.intro=Lo que los visitantes buscaron en este sitio y no encontraron — candidatos para nuevas páginas, mejores títulos o descripciones, o una redirección.
search.noresults.off=El registro está desactivado para este sitio. Active "Registrar búsquedas sin resultados" arriba para empezar la lista.
search.noresults.col.term=Término buscado
search.noresults.col.count=Búsquedas
search.noresults.col.lastSeen=Última búsqueda
search.noresults.empty=Aún no hay búsquedas sin resultados registradas.
search.noresults.retention=Los términos que nadie buscó en {0} días salen de la lista; se conservan como máximo {1} términos, los más frecuentes primero.
search.noresults.clear=Vaciar lista
search.noresults.clear.tip=Olvidar todos los términos registrados de este sitio (no se puede deshacer)
search.noresults.clearFailed=No se pudo vaciar la lista de búsquedas sin resultados.
search.widget.results=Mostrar aquí los resultados
search.widget.help.results=Lo que muestra este cuadro cuando su página se abre con una búsqueda (?q=). auto: los resultados, salvo que el cuadro esté en la plantilla maestra (un cuadro del encabezado o del pie), para que la página de resultados no los muestre dos veces. always: los resultados, esté donde esté el cuadro. never: solo el cuadro.
+94
View File
@@ -0,0 +1,94 @@
# =============================================================================
# Runway Search Plugin — descriptor
# On-site search: a built-in full-text engine over page title/description/body,
# delivered as a query-aware CONTENT WIDGET (data-widget="search/box") on a
# normal editable page — it renders the box, and when the page is opened with
# ?q= it renders the results inline. The operator installs a ready-made,
# editable results page in one click from the settings (then it behaves like
# any site page). The endpoint owns only GET /search/api (JSON) and three
# operator-gated, CSRF-checked POSTs: /search/reindex, /search/install-page and
# /search/no-results/clear. Publishes its own SPI — the SearchCorpus every engine
# builds from, and the SiteSearchEngine a companion plugin (search-lucene) can
# implement to upgrade the engine. Links ONLY the Runway SPI (service tier).
# The install folder name MUST equal this `id`: external/plugins/search/.
# =============================================================================
id: search
name: Search
version: 2.3.0
# The @Configuration registered into the host context before refresh. Its package (mx.quest.search) lives
# OUTSIDE mx.quest.runway so the host never double-scans it. Beans are wired EXPLICITLY (no @ComponentScan).
mainClass: mx.quest.search.SearchConfig
# Built against the SPI service tier: PluginSettings, PluginSiteFiles, Sites, Messages, AccessCheck, SitePages,
# ContentCatalogView and SiteEventListener. A kernel below SPI 1.0.0 BLOCKS this plugin at startup with a reason.
requiresSpi: ">=1.0.0"
# --- Personal data ---------------------------------------------------------------------------------------
# no-results.tsv holds search terms visitors typed (recorded only when a site opts in). 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/search/.
siteData:
personal:
- no-results.tsv
# No hard dependency (always loads); NOT essential. Adds a public /search surface + an embeddable box, backed by
# a pluggable engine. The built-in engine needs no external index, so search works the moment it is installed.
# --- Grantable control-point permission -----------------------------------------------------------------
# `settings` is the reserved id that gates this plugin's per-tenant config editor AND the operator-only
# maintenance actions (reindex, install-page, clear the no-result list). defaultRoles is EMPTY: the control point
# starts ungranted — admins hold it via the wildcard tier; a tenant superadmin grants it to OPERATOR or a custom role.
permissions:
- { id: settings, realm: tenant, label: search.perm.settings, defaultRoles: [] }
# --- App-level settings (superadmin; PLATFORM concerns only) ----------------------------------------------
# Over external/plugin-settings/search.yml, bound to runway.plugin.search.* into SearchProperties; applied
# on restart. Only platform knobs live here — the index freshness timer and the per-IP abuse guard. Every
# tenant-owned knob (enable, ranking, exclusions, snippet) is per-site below (a tenant must not set a global
# timer or an abuse limit).
settings:
- { key: refresh-minutes, type: int, default: 60, range: "1..1440", label: search.set.refresh }
- { key: rate-limit.per-ip-per-minute, type: int, default: 30, range: "0..100000", label: search.set.perMinute }
- { key: rate-limit.per-ip-per-hour, type: int, default: 600, range: "0..1000000", label: search.set.perHour }
# --- Per-tenant settings (tenant-owned BEHAVIOUR; over sites/<id>/plugins/search.yml; applied IMMEDIATELY) --
# The whole tenant-owned surface: enable/limit/placeholder, the ranking weights, the exclude list, and the
# snippet length. Every default here MUST match a default in SearchSiteConfig.
siteSettings:
- { key: enabled, type: boolean, default: true, label: search.set.enabled }
- { key: resultLimit, type: int, default: 20, range: "1..100", label: search.set.resultLimit }
# Where the box submits ?q= to — the results page carrying this widget (install it from the card below). The
# box widget falls back to /search when unset; set this if you move/rename the results page.
- { key: resultsPath, type: string, default: /search, label: search.set.resultsPath }
- { key: placeholder, type: string, label: search.set.placeholder }
- { key: exclude, type: list, label: search.set.exclude }
- { key: snippetLength, type: int, default: 160, range: "40..400", label: search.set.snippetLength }
# Since 2.1.0: a result link carries the words the engine matched (#rw-hl=…), and the page it opens highlights
# them (static/highlight.js, loaded only when the marker is present). Off: plain links and no loader on the pages.
- { key: highlight, type: boolean, default: true, label: search.set.highlight, help: search.help.highlight }
- { key: titleWeight, type: int, default: 8, range: "0..1000000", label: search.set.titleWeight }
- { key: descriptionWeight, type: int, default: 4, range: "0..1000000", label: search.set.descriptionWeight }
- { key: bodyWeight, type: int, default: 1, range: "0..1000000", label: search.set.bodyWeight }
- { key: allTermsBonus, type: int, default: 1000, range: "0..1000000000", label: search.set.allTermsBonus }
- { key: phraseTitleBonus, type: int, default: 400, range: "0..1000000000", label: search.set.phraseTitleBonus }
- { key: phraseBodyBonus, type: int, default: 300, range: "0..1000000000", label: search.set.phraseBodyBonus }
# Searches with no results (since 2.0.0; developed as the unreleased 1.4.0) — a content-gap list shown on this
# page. OFF by default: a search term is free text a visitor typed and may be personal data, so a site opts in. Only term + count + last seen are kept (no IP,
# no user); email- and phone-number-like terms are never stored. Every default here MUST match NoResultsLog.
- { key: recordNoResults, type: boolean, default: false, label: search.set.recordNoResults,
help: search.help.recordNoResults }
- { key: noResultsRetentionDays, type: int, default: 90, range: "1..365", label: search.set.noResultsRetention,
help: search.help.noResultsRetention, showWhen: recordNoResults }
# --- Per-placement settings of the search box (since 2.1.0; Site → Content widgets, one form per data-widget) ---
# results: whether this box lists the results when its page is opened with ?q=. auto (the default) lists them
# unless the box is in the master chrome, so a header or footer box does not repeat the results page's list.
widgetSettings:
search:
- { key: results, type: enum, default: auto, range: "auto,always,never", label: search.widget.results,
help: search.widget.help.results }
# --- Tenant dashboard card (fragment resolves to __plugin__/search/dashboard = templates/dashboard.*) -----
dashboardCards:
- { realm: tenant, order: 40, fragment: dashboard, permission: "search|settings" }
+137
View File
@@ -0,0 +1,137 @@
<?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 Runway kernel uses (Spring Boot 4.0.6), so every `provided`
Spring type the plugin compiles against is byte-identical to the class the host loads. A plugin is NOT
a Spring Boot application — NO spring-boot-maven-plugin repackage; `mvn package` produces a THIN jar of
only this plugin's own classes (including its published SPI — SiteSearchEngine, SearchCorpus, SearchQuery,
SearchHit — which search-lucene compiles against as `provided`).
-->
<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-search</artifactId>
<version>2.3.0</version>
<packaging>jar</packaging>
<name>Runway Search 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>
On-site search for Runway: a built-in full-text engine over the site's published pages and content items,
an embeddable query-aware search-box content widget, and a JSON API — all backed by a published
SiteSearchEngine SPI (and the SearchCorpus every engine builds from) that a companion plugin (search-lucene)
can implement to transparently upgrade the engine. 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-21T17:23:00Z</project.build.outputTimestamp>
<!-- The runway-spi (and runway-spi-testkit) version this plugin compiles and tests against, from ~/.m2. -->
<runway.version>1.0.0</runway.version>
</properties>
<dependencies>
<!-- The dependency-free extension API (SPI interfaces + immutable model records). COMPILE. -->
<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 no longer compiles 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>
<!-- Spring context/Boot for @Configuration/@Bean at compile time; host-provided at runtime. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<scope>provided</scope>
</dependency>
<!-- Wiring/unit tests run against the compiled classes (NEVER spring-boot:run). -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!-- Stable deployed filename (no version/classifier): target/runway-plugin-search.jar. -->
<finalName>runway-plugin-search</finalName>
<plugins>
<!-- After the jar is built, assemble BOTH installable forms the platform accepts:
1. target/search/ — the install-ready folder (cp -r into external/plugins/ + restart).
2. target/runway-plugin-search-<version>.zip — the UI-uploadable archive (/__app/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}/search"/>
<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-search.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="search"/>
</touch>
<zip destfile="${project.build.directory}/runway-plugin-search-${project.version}.zip">
<zipfileset dir="${project.build.directory}" includes="search/**"/>
</zip>
<echo message="Staged install folder: ${stage}"/>
<echo message="UI-uploadable archive: ${project.build.directory}/runway-plugin-search-${project.version}.zip"/>
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
+375
View File
@@ -0,0 +1,375 @@
#!/usr/bin/env bash
# Build this plugin, drop it into a throwaway Runway deployment, boot the PACKAGED host in ACTIVE mode, and prove
# the search 2.1.1 contract end to end (SPI 0.6.0):
# - it loads with ZERO host-linkage and bean-name/surface warnings, and its app-level settings bind;
# - the JSON API serves results anonymously; there is no plugin-owned /search page until one is installed;
# - the three 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 rebuild-index and install-page buttons are POST forms carrying the token;
# the starter page installs through SitePages on an Advisory, an Enforced and a Reviewed site (each outcome
# reported), renders results inline, and a second install changes nothing;
# - the `exclude` setting reaches the index on the save (through the kernel's change event), without a reindex;
# - searches with no results: off by default, recorded once turned on (email-like terms never), written to the
# plugin's own per-site file; a FULL backup carries no-results.tsv and a TRANSFER copy leaves it out and lists it
# in its manifest; the clear POST is CSRF-checked;
# - the API's rate limit keys on the kernel-gated client IP: made-up X-Forwarded-For headers do not evade it;
# - the result highlighter: result links (page and API) carry #rw-hl=<words>, every page carries the loader
# script stamped with the nonce its CSP allows, and the loader, highlight.js and highlight.css are served;
# - the installed results page is never among its own results (2.1.1).
# The deployment holds three sites copied from the wizard's default one before the ACTIVE boot: default (Advisory),
# enforced, reviewed — 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)
# VERIFY_TMPDIR=/dir where the throwaway deployment goes (default: $TMPDIR or /tmp)
# VERIFY_LOG_DIR=/dir keep copies of the host logs, the install answers 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) and HOST_TARGET (default: 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
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=Search-Admin-2026; SITE_USER=owner; SITE_PW=Search-Site-2026
PER_MINUTE=25
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)"
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}}/search-verify.XXXXXX")"
cleanup() {
[ -z "${VERIFY_LOG_DIR:-}" ] || { mkdir -p "$VERIFY_LOG_DIR" \
&& cp "$SCRATCH"/*.log "$SCRATCH"/*-manifest.yml "$SCRATCH"/install-*.txt "$VERIFY_LOG_DIR"/ 2>/dev/null; }
# Wait for the host to exit before deleting: a JVM still shutting down rewrites files under external/ (the
# no-result list is flushed on shutdown) 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/search" "$EXT/plugins/search"
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
ck() { if eval "$2" >/dev/null 2>&1; then echo " PASS $1"; PASS=$((PASS+1)); else echo " FAIL $1"; FAIL=$((FAIL+1)); fi; }
# The shipped application.yml trusts loopback as a same-host reverse proxy. This deployment trusts only a TEST-NET
# address instead, so curl on loopback is an untrusted peer: a forwarded header it sends must be ignored.
boot() { ( cd "$SCRATCH" && exec "$JAVA" -jar "$JAR" --server.port="$PORT" --runway.storage.external="$EXT" \
--runway.proxy.trusted-cidrs=192.0.2.1/32 ) >"$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
# --- Two 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
sed -i 's/^ - "default"$/ - "default"\n - "enforced"\n - "reviewed"/' "$EXT/site-users.yml"
# A bilingual page whose visible copy comes ONLY from the site's bundles (decoupled th:text): the template holds an
# empty element. Kernel 1.0.0-rc6+ indexes the page as rendered in each language; search 2.2.0+ searches each
# language's own documents (on 2.1.1 + rc5, "facultad" found nothing).
sed -i '/^locales:/a - "es"' "$SITES/default/site.yml"
T="$SITES/default/templates"
cat > "$T/faculty.html" <<'HTML'
<!DOCTYPE html><html><head><title>Faculty</title></head>
<body><main id="content"><h1>Faculty</h1><p id="faculty-copy"></p></main></body></html>
HTML
cat > "$T/faculty.th.xml" <<'XML'
<?xml version="1.0"?>
<thlogic>
<attr sel="#faculty-copy" th:text="#{verify.faculty}"/>
</thlogic>
XML
printf 'path: /faculty\nlocalizedPaths:\n es: /facultad\nlocales: [en, es]\ntitle:\n en: Faculty\n es: Profesores\n' > "$T/faculty.meta.yml"
mkdir -p "$SITES/default/i18n"
printf '\nverify.faculty=Our students learn from a faculty of researchers.\n' >> "$SITES/default/i18n/messages.properties"
printf '\nverify.faculty=Nuestros alumnos aprenden con una facultad de excelencia.\n' >> "$SITES/default/i18n/messages_es.properties"
# The app-level settings, in the file the plugins screen writes: a low per-minute ceiling the last section floods.
mkdir -p "$EXT/plugin-settings"
cat > "$EXT/plugin-settings/search.yml" <<YML
runway:
plugin:
search:
refresh-minutes: 60
"rate-limit.per-ip-per-minute": $PER_MINUTE
"rate-limit.per-ip-per-hour": 100000
YML
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"
echo "== plugin load (SPI 0.6.0 contract) =="
ck "plugins registered (1), 0 blocked" "grep -qE 'plugins: 1 registered, 0 blocked' '$LOG'"
ck "not blocked / quarantined" "! grep -qE \"plugin 'search' 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 'search' linkage scan\" '$LOG'"
ck "ZERO bean-name/surface findings" "! grep -qE \"plugin 'search'.*(allowed until Runway 1.0|bean name|may not contribute)\" '$LOG'"
ck "no WARN/ERROR names the plugin" "! grep -E ' (WARN|ERROR) ' '$LOG' | grep -qiE \"plugin 'search'|mx\\.quest\\.search\""
ck "no key collision / degraded" "! grep -qiE 'collision|duplicate key|degraded' '$LOG'"
echo "== static assets =="
ck "search.css served" "curl -s -o /dev/null -w '%{http_code}' '$BASE/__plugin/search/static/search.css' | grep -q 200"
ck "help page served" "curl -s -o /dev/null -w '%{http_code}' '$BASE/__plugin/search/static/search-help.html' | grep -q 200"
ck "highlight.js served as JavaScript" \
"curl -s -D - -o /dev/null '$BASE/__plugin/search/static/highlight.js' | grep -qiE '^content-type: (text|application)/javascript'"
ck "highlight.css served" "curl -s -o /dev/null -w '%{http_code}' '$BASE/__plugin/search/static/highlight.css' | grep -q 200"
PLUGIN_VERSION="$(sed -n 's/^version: //p' "$HERE/plugin.yml")"
echo "== the result highlighter (since 2.1.0) =="
if command -v node >/dev/null 2>&1; then
ck "the page scripts parse (node --check)" "node --check '$HERE/static/highlight.js' && node --check '$HERE/static/highlight-loader.js'"
ck "the word pattern folds as the server lowercases (Turkish İ, accents, symbols)" \
"node '$HERE/src/test/js/highlight-pattern.js' '$HERE/static/highlight.js'"
else
echo " SKIP node not found: the page scripts were not parsed"
fi
curl -s -D "$SCRATCH/home.headers" "$BASE/" > "$SCRATCH/home.html"
ck "every page carries the loader script, stamped with the nonce the kernel's CSP allows" \
"n=\$(grep -oE '<script [^>]*src=\"/__plugin/search/static/highlight-loader.js[?]v=[0-9.]+\"[^>]*>' '$SCRATCH/home.html' | grep -oE 'nonce=\"[^\"]+\"' | sed -E 's/nonce=\"(.*)\"/\\1/'); [ -n \"\$n\" ] && grep -i '^content-security-policy' '$SCRATCH/home.headers' | grep -q \"nonce-\$n\""
ck "plugin files are cacheable with a content ETag (kernel 1.0.0-rc5+; rc4 and earlier send no-store)" \
"curl -s -D - -o /dev/null '$BASE/__plugin/search/static/highlight-loader.js?v=$PLUGIN_VERSION' | grep -qiE '^etag: ' || [ \"\${HOST_BEFORE_RC5:-0}\" = 1 ]"
ck "highlight-loader.js served as JavaScript" \
"curl -s -D - -o /dev/null '$BASE/__plugin/search/static/highlight-loader.js' | grep -qiE '^content-type: (text|application)/javascript'"
echo "== the public surfaces (anonymous) =="
code() { curl -s -o /dev/null -w '%{http_code}' "$@"; }
ck "no /search page until one is installed (404)" "[ \"\$(code '$BASE/search?q=about')\" = 404 ]"
curl -s "$BASE/search/api?q=about" > "$SCRATCH/api-1.json"
ck "the JSON API serves results from the catalog" \
"grep -q '\"query\":\"about\"' '$SCRATCH/api-1.json' && grep -q '\"url\":\"/about\"' '$SCRATCH/api-1.json'"
ck "…each result with its matched words and a link carrying them (2.1.0)" \
"grep -q '\"link\":\"/about#rw-hl=about\"' '$SCRATCH/api-1.json' && grep -q '\"terms\":\\[\"about\"' '$SCRATCH/api-1.json'"
ck "the JSON API answers JSON" \
"curl -s -D - -o /dev/null '$BASE/search/api?q=about' | grep -qi '^content-type: application/json'"
echo "== every language searches its own text, bundle strings included (kernel 1.0.0-rc6+, search 2.2.0+) =="
ck "the default site speaks Spanish too (fixture)" "grep -q '^- \"es\"' '$SITES/default/site.yml'"
ck "the page's copy is rendered from the bundle (fixture)" \
"curl -s '$BASE/es/facultad' | grep -q 'facultad de excelencia'"
curl -s "$BASE/search/api?q=researchers&lang=en" > "$SCRATCH/api-en.json"
curl -s "$BASE/search/api?q=excelencia&lang=es" > "$SCRATCH/api-es.json"
ck "an English bundle string is searchable in English, at the English address" \
"grep -q '\"url\":\"/faculty\"' '$SCRATCH/api-en.json'"
ck "a Spanish bundle string is searchable in Spanish, at the Spanish address, with the Spanish title" \
"grep -q '\"url\":\"/es/facultad\"' '$SCRATCH/api-es.json' && grep -q '\"title\":\"Profesores\"' '$SCRATCH/api-es.json'"
ck "…and its snippet is the Spanish text (JSON writes < as \\u003c)" \
"grep -qF 'facultad de \u003cmark\u003eexcelencia' '$SCRATCH/api-es.json'"
ck "English does not search the Spanish text" \
"! curl -s '$BASE/search/api?q=excelencia&lang=en' | grep -q '/faculty'"
ck "Spanish does not search the English text" \
"! curl -s '$BASE/search/api?q=researchers&lang=es' | grep -q 'facultad'"
ck "a page in the default language only is still found from Spanish (its primary document)" \
"curl -s '$BASE/search/api?q=about&lang=es' | grep -q '\"url\":\"/about\"'"
echo "== the operator actions are CSRF-protected POSTs (a link or an <img> changes nothing) =="
token() { grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//'; }
site_url() { [ "$1" = default ] && echo "$BASE" || echo "http://$1.test:$PORT"; }
sc() { # site curl-args... (one cookie jar per site host; --resolve maps <site>.test to the local host)
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)"
}
no_page() { ! ls "$SITES/$1/templates"/search.* >/dev/null 2>&1; }
ck "anonymous GET of reindex / install-page -> 404 (no GET route)" \
"[ \"\$(code '$BASE/search/reindex')\" = 404 ] && [ \"\$(code '$BASE/search/install-page')\" = 404 ]"
ck "anonymous POST without a CSRF token -> 403 (the tenant chain's CSRF check)" \
"[ \"\$(code -X POST '$BASE/search/reindex' -d x=1)\" = 403 ] && [ \"\$(code -X POST '$BASE/search/install-page' -d x=1)\" = 403 ] && [ \"\$(code -X POST '$BASE/search/no-results/clear' -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/search/install-page' --data-urlencode '_csrf=$ANON_TOKEN')\" = 404 ] && [ \"\$(code -c '$ANON_JAR' -b '$ANON_JAR' -X POST '$BASE/search/reindex' --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 /search/install-page -> 404 and no page (a cross-site link installs nothing)" \
"[ \"\$(sc default -o /dev/null -w '%{http_code}' '$BASE/search/install-page')\" = 404 ] && no_page default"
ck "signed-in owner: GET /search/reindex -> 404" \
"[ \"\$(sc default -o /dev/null -w '%{http_code}' '$BASE/search/reindex')\" = 404 ]"
ck "signed-in owner: POST without the CSRF token -> 403 and no page" \
"[ \"\$(sc default -o /dev/null -w '%{http_code}' -X POST '$BASE/search/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/search/install-page' -d _csrf=forged-token)\" = 403 ] && no_page default"
SETTINGS="$BASE/__admin/plugins/search/settings"
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=\"sp-install-form\" method=\"post\" action=\"/search/install-page\"' '$SCRATCH/settings-0.html' && grep -qE 'id=\"sp-csrf\" type=\"hidden\" name=\"_csrf\" value=\"[^\"]+\"' '$SCRATCH/settings-0.html'"
ck "…and the index rebuild as a POST form carrying a non-empty CSRF token" \
"grep -q 'id=\"sr-reindex-form\" method=\"post\" action=\"/search/reindex\"' '$SCRATCH/settings-0.html' && grep -qE 'id=\"sr-csrf\" type=\"hidden\" name=\"_csrf\" value=\"[^\"]+\"' '$SCRATCH/settings-0.html'"
ck "…and no link points at either action" "! grep -qE 'href=\"/search/(install-page|reindex)' '$SCRATCH/settings-0.html'"
ck "…and counts the searchable items (pages and content items)" "grep -qE 'id=\"sa-pages\">[1-9][0-9]*<' '$SCRATCH/settings-0.html'"
sc default -X POST "$BASE/search/reindex" --data-urlencode "_csrf=$(token < "$SCRATCH/settings-0.html")" > "$SCRATCH/reindex.txt"
ck "POST /search/reindex with the page's token rebuilds and reports the count" \
"grep -qE '^Search index rebuilt\. \([1-9][0-9]*\)$' '$SCRATCH/reindex.txt'"
echo "== the starter page through SitePages (Advisory, Enforced, Reviewed) =="
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/search/install-page" --data-urlencode "_csrf=$(sc "$1" "$u/__admin/plugins/search/settings" | token)"
}
install default > "$SCRATCH/install-default.txt"
ck "Advisory: POST with the token installs and publishes at /search" "grep -qx 'Search page installed at /search' '$SCRATCH/install-default.txt'"
curl -s -D "$SCRATCH/search-page.headers" "$BASE/search?q=about" > "$SCRATCH/search-page.html"
ck "…the installed page renders the box and the results inline" \
"grep -q 'class=\"rw-search-box\"' '$SCRATCH/search-page.html' && grep -q 'href=\"/about#rw-hl=about\"' '$SCRATCH/search-page.html'"
ck "…and is noindex (a search-results page is the canonical index opt-out)" \
"grep -qi 'noindex' '$SCRATCH/search-page.html' '$SCRATCH/search-page.headers'"
ck "…and is never among its own results, though its title matches the query (2.1.1)" \
"grep -qiE '<title[^>]*>[^<]*search' '$SCRATCH/search-page.html' && ! curl -s '$BASE/search/api?q=search' | grep -q '\"url\":\"/search\"'"
install default > "$SCRATCH/install-again.txt"
ck "a second install changes nothing and says where the page is" "grep -qx 'A search page already exists at /search' '$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
ck "Enforced: a documented outcome, never an error" \
"grep -qE '^(Search page installed at /search|The search page was created as a draft because the quality checks blocked publishing; fix it in the page editor: /search)' '$SCRATCH/install-enforced.txt'"
ck "Reviewed (as the owner, who may approve): a documented outcome" \
"grep -qE '^(Search page installed at /search|The search page was created and is waiting in the review queue: /search|The search 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\"/search.* >/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=\"sp-path\"[^>]*>/search<' '$SCRATCH/settings-1.html'"
echo "== settings: the exclude list reaches the index on the save; no-result terms are opt-in =="
NR_FILE="$SITES/default/plugins/search/no-results.tsv"
curl -s -o /dev/null "$BASE/search/api?q=zebra%20crossing%20xyzzy"
ck "off by default: the card says so and a no-result search is not recorded" \
"grep -q 'id=\"nr-off\"' '$SCRATCH/settings-1.html' && ! sc default '$SETTINGS' | grep -q 'zebra crossing xyzzy'"
sc default -o /dev/null -X POST "$SETTINGS" --data-urlencode "enabled=true" --data-urlencode "exclude=about" \
--data-urlencode "recordNoResults=true" --data-urlencode "_csrf=$(token < "$SCRATCH/settings-1.html")"
ck "the settings save is stored (exclude + recording on)" \
"grep -q 'about' '$SITES/default/plugins/search.yml' && grep -q 'recordNoResults: true' '$SITES/default/plugins/search.yml'"
ck "an excluded page leaves the results at once (no reindex)" "! curl -s '$BASE/search/api?q=about' | grep -q '\"url\":\"/about\"'"
curl -s -o /dev/null "$BASE/search/api?q=Zebra%20%20Crossing%20XYZZY"
curl -s -o /dev/null "$BASE/search/api?q=someone%40example.com"
sc default "$SETTINGS" > "$SCRATCH/settings-2.html"
ck "on: the normalized no-result term is listed" "grep -q '>zebra crossing xyzzy<' '$SCRATCH/settings-2.html'"
ck "on: an email-like term is never kept" "! grep -q 'someone@example.com' '$SCRATCH/settings-2.html'"
echo " waiting for the background flush of the no-result list (every 30 s) ..."
for _ in $(seq 1 45); do [ -s "$NR_FILE" ] && break; sleep 1; done
ck "the list is written to the plugin's own per-site file" "grep -q '^zebra crossing xyzzy' '$NR_FILE'"
echo "== backups: a full backup keeps no-results.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/search/no-results.tsv with the terms" \
"zipq '$SCRATCH/full.zip' read plugins/search/no-results.tsv | grep -q 'zebra crossing xyzzy'"
ck "the transfer copy has NO plugins/search/no-results.tsv" "! zipq '$SCRATCH/transfer.zip' has plugins/search/no-results.tsv"
ck "…and its manifest lists the omission" "grep -q 'plugins/search/no-results.tsv' '$SCRATCH/transfer-manifest.yml'"
ck "…while the settings file travels" "zipq '$SCRATCH/transfer.zip' has plugins/search.yml"
ck "the full backup's manifest omits nothing of search" "! grep -q 'plugins/search/no-results.tsv' '$SCRATCH/full-manifest.yml'"
echo "== clearing the no-result list (CSRF-checked POST) =="
ck "clear without the CSRF token is refused (403)" \
"[ \"\$(sc default -o /dev/null -w '%{http_code}' -X POST '$BASE/search/no-results/clear')\" = 403 ]"
ck "a GET does not clear (404)" "[ \"\$(sc default -o /dev/null -w '%{http_code}' '$BASE/search/no-results/clear')\" = 404 ]"
ck "clear with the page's token redirects back to the settings (303)" \
"[ \"\$(sc default -o /dev/null -w '%{http_code}' -X POST '$BASE/search/no-results/clear' --data-urlencode \"_csrf=\$(token < '$SCRATCH/settings-2.html')\")\" = 303 ]"
ck "the list and the file are gone" "! sc default '$SETTINGS' | grep -q 'zebra crossing xyzzy' && [ ! -e '$NR_FILE' ]"
echo "== a Messages save reaches the index at once (kernel 1.0.0-rc6+: no reindex) =="
login default
MSG_TOKEN="$(sc default "$BASE/__admin/messages" | token)"
ck "the Messages save is accepted" \
"sc default -X POST '$BASE/__admin/messages/apply' -H 'Content-Type: application/json' -H \"X-CSRF-TOKEN: \$MSG_TOKEN\" \
--data '{\"cells\":[{\"key\":\"verify.faculty\",\"locale\":\"en\",\"value\":\"Our students learn from astronomers.\"}]}' \
| grep -q '\"saved\":1'"
ck "the new English string is found by the next query" \
"curl -s '$BASE/search/api?q=astronomers&lang=en' | grep -q '\"url\":\"/faculty\"'"
ck "…and the old one is gone" "! curl -s '$BASE/search/api?q=researchers&lang=en' | grep -q '/faculty'"
echo "== the API's rate limit keys on the kernel-gated client IP =="
# Every request below comes from ::1 (an untrusted peer here) and carries a different made-up X-Forwarded-For. The
# kernel's trusted-proxy gate ignores the header, so all of them share the ::1 key and the ceiling applies; a request
# from 127.0.0.1 is another client with its own budget.
V6="http://[::1]:$PORT"; V4="http://127.0.0.1:$PORT"
LIMITED=0
for i in $(seq 1 $((PER_MINUTE + 5))); do
c="$(curl -s -o /dev/null -w '%{http_code}' -H "Host: localhost:$PORT" \
-H "X-Forwarded-For: 10.9.$((i / 250)).$((i % 250))" "$V6/search/api?q=rate$i")"
[ "$c" = 429 ] && LIMITED=$((LIMITED + 1))
done
ck "made-up X-Forwarded-For headers do not evade the per-minute ceiling of $PER_MINUTE ($LIMITED of $((PER_MINUTE + 5)) answered 429)" \
"[ $LIMITED -ge 5 ]"
ck "…the 429 is the API's JSON answer" \
"curl -s -H 'Host: localhost:$PORT' '$V6/search/api?q=again' | grep -qx '{\"error\":\"rate_limited\"}'"
ck "another client address has its own budget (200)" \
"[ \"\$(curl -s -o /dev/null -w '%{http_code}' -H 'Host: localhost:$PORT' '$V4/search/api?q=other')\" = 200 ]"
ck "a blank query is not counted (still 200 at the ceiling)" \
"[ \"\$(curl -s -o /dev/null -w '%{http_code}' -H 'Host: localhost:$PORT' '$V6/search/api?q=')\" = 200 ]"
ck "still no WARN/ERROR names the plugin after the run" "! grep -E ' (WARN|ERROR) ' '$LOG' | grep -qiE \"plugin 'search'|mx\\.quest\\.search\""
echo; echo "RESULT: $PASS passed, $FAIL failed"
if [ "$KEEP" = "yes" ]; then echo "[verify] kept at $BASE (scratch $SCRATCH; kill $PID to stop)"; wait "$PID"; fi
exit "$FAIL"
@@ -0,0 +1,32 @@
package mx.quest.search;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import mx.quest.search.spi.SearchHit;
/**
* The link from a search result to the page it found, carrying the words to highlight there: the hit's URL plus the
* fragment {@code #rw-hl=<words>}, the words separated by spaces and percent-encoded as one component. The fragment
* never reaches the server, so the page is served and cached exactly as without it; {@code static/highlight.js} on
* the target page reads it, highlights the words and removes it from the address bar (see {@link SearchHighlightHead}).
*
* <p>A hit with no matched words, or whose URL already has a fragment, links plainly.
*/
final class HighlightMarker {
/** The fragment key the page script reads. Changing it breaks links already shared, so it is fixed. */
static final String KEY = "rw-hl";
private HighlightMarker() {
}
/** The hit's link: its URL, with the marker when it has matched words and no fragment of its own. */
static String link(SearchHit hit) {
if (hit.terms().isEmpty() || hit.url().indexOf('#') >= 0) {
return hit.url();
}
// URLEncoder writes a space as '+', which decodeURIComponent leaves alone; %20 decodes the same everywhere.
String words = URLEncoder.encode(String.join(" ", hit.terms()), StandardCharsets.UTF_8).replace("+", "%20");
return hit.url() + "#" + KEY + "=" + words;
}
}
@@ -0,0 +1,21 @@
package mx.quest.search;
/**
* Minimal HTML escaping for the plugin's own generated markup (the search box widget and the results page).
* The plugin owns escaping of every value it interpolates — page titles, snippets, the user's query — so a
* crafted query or page title can never inject markup into the results page.
*/
final class Html {
private Html() {
}
/** Escapes text for an element body or a double-quoted attribute value. */
static String escape(String value) {
if (value == null || value.isEmpty()) {
return "";
}
return value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
.replace("\"", "&quot;").replace("'", "&#39;");
}
}
@@ -0,0 +1,43 @@
package mx.quest.search;
import java.util.regex.Pattern;
/**
* Reduces a page's raw HTML source to searchable plain text so the built-in engine can index a page's
* <b>body</b>, not just its metadata. It removes {@code <script>}/{@code <style>} blocks and HTML comments
* (whose contents are not visible prose), strips the remaining tags, decodes the handful of entities a page body
* commonly carries, and collapses runs of whitespace to single spaces.
*
* <p>This is deliberately a best-effort extractor, not a conforming HTML parser: a malformed or exotic page must
* still yield <em>some</em> reasonable text rather than throw, because indexing must never fail on a single bad
* page. The output is plain text with no markup — the snippet builder is what later re-introduces the safe
* {@code <mark>} highlight over an escaped slice of it.
*/
final class HtmlText {
/** {@code <script>…</script>} / {@code <style>…</style>} — content is code/CSS, never indexable prose. */
private static final Pattern SCRIPT_STYLE = Pattern.compile("(?is)<(script|style)\\b[^>]*>.*?</\\1>");
private static final Pattern COMMENT = Pattern.compile("(?s)<!--.*?-->");
private static final Pattern TAG = Pattern.compile("<[^>]+>");
private static final Pattern WHITESPACE = Pattern.compile("\\s+");
private HtmlText() {
}
/** The visible text of {@code html} (never {@code null}; empty for {@code null}/blank input). */
static String toText(String html) {
if (html == null || html.isBlank()) {
return "";
}
String text = SCRIPT_STYLE.matcher(html).replaceAll(" ");
text = COMMENT.matcher(text).replaceAll(" ");
text = TAG.matcher(text).replaceAll(" ");
// Decode the common named/numeric entities a body carries; &amp; is decoded LAST so a literal
// "&amp;lt;" round-trips to "&lt;" rather than being over-decoded to "<".
text = text.replace("&nbsp;", " ")
.replace("&lt;", "<").replace("&gt;", ">")
.replace("&quot;", "\"").replace("&#39;", "'").replace("&apos;", "'")
.replace("&amp;", "&");
return WHITESPACE.matcher(text).replaceAll(" ").strip();
}
}
@@ -0,0 +1,65 @@
package mx.quest.search;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import mx.quest.search.spi.SearchHit;
/**
* The words the built-in engine matched in one document, for {@link SearchHit#terms()}. The built-in engine matches
* a query term anywhere inside a word ({@code maestr} finds {@code maestrías}), so the word to highlight on the
* target page is the whole word around each occurrence, not the term. Reads the lowercased fields of a
* {@link SearchDocument}, title first, so the words a visitor sees first are the ones kept when the cap is reached.
*/
final class MatchedWords {
/** Occurrences of one term examined per field; enough to collect the distinct forms of a real page. */
private static final int MAX_OCCURRENCES_PER_TERM = 200;
private MatchedWords() {
}
/** The distinct whole words containing any of {@code terms}, in field order, at most {@link SearchHit#MAX_TERMS}. */
static List<String> in(SearchDocument doc, List<String> terms) {
Set<String> words = new LinkedHashSet<>();
for (String field : List.of(doc.normTitle(), doc.normDescription(), doc.normBody())) {
for (String term : terms) {
collect(field, term, words);
if (words.size() >= SearchHit.MAX_TERMS) {
return List.copyOf(words);
}
}
}
return List.copyOf(words);
}
private static void collect(String text, String term, Set<String> words) {
if (term.isEmpty()) {
return;
}
int seen = 0;
for (int i = text.indexOf(term); i >= 0 && seen < MAX_OCCURRENCES_PER_TERM;
i = text.indexOf(term, i + term.length())) {
seen++;
int start = i;
while (start > 0 && isWordChar(text.charAt(start - 1))) {
start--;
}
int end = i + term.length();
while (end < text.length() && isWordChar(text.charAt(end))) {
end++;
}
if (end - start <= SearchHit.MAX_TERM_LENGTH) {
words.add(text.substring(start, end));
if (words.size() >= SearchHit.MAX_TERMS) {
return;
}
}
}
}
/** A letter, digit or combining mark: the characters the page highlighter also treats as part of a word. */
private static boolean isWordChar(char c) {
return Character.isLetterOrDigit(c) || Character.getType(c) == Character.NON_SPACING_MARK;
}
}
@@ -0,0 +1,440 @@
package mx.quest.search;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.Normalizer;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import mx.quest.runway.spi.model.FileEntry;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.spi.service.PluginSiteFiles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Remembers, per site, the searches that found <b>nothing</b> — a content-gap signal for the site manager (what
* visitors look for that the site does not have). Each entry is only a <b>normalized term, a count, and the last
* time it was seen</b>: no IP, no user, no session, no full query string, no timestamp per search.
*
* <h2>Off by default</h2>
* A search term is free text a visitor typed, so it can carry personal data (a name, an email, a phone number).
* Recording is therefore opt-in per site ({@code recordNoResults}, default {@code false}); when it is off,
* {@link #record} does nothing at all. Even when on, a term that <b>looks like</b> an email address or a phone /
* ID number (seven or more digits once spaces, dashes, dots, parentheses and a leading plus are ignored) is
* dropped unrecorded. The term never reaches an application log line.
*
* <h2>Bounded</h2>
* <ul>
* <li><b>Term length</b> — after normalization (Unicode NFC, trimmed, lower-cased, whitespace runs collapsed to
* one space, control characters removed) a term is cut to {@link #MAX_TERM_CHARS} characters.</li>
* <li><b>Term count</b> — at most {@link #MAX_TERMS} per site. Admitting a new term to a full list evicts the
* least frequent one (the longest-unseen among equals), so a flood of one-off junk queries churns only the
* bottom of the list and the recurring gaps stay.</li>
* <li><b>Retention</b> — a term not seen for {@code noResultsRetentionDays} (default
* {@link #DEFAULT_RETENTION_DAYS}) is dropped from listings and from the next write.</li>
* <li><b>Repeats</b> — the same term on the same site within {@link #REPEAT_WINDOW} counts once, because a page
* carrying two search boxes renders (and would record) the same empty result twice per request.</li>
* </ul>
*
* <h2>Storage</h2>
* In memory per site, loaded lazily from the plugin's own per-site file {@value #FILE} in its
* {@link PluginSiteFiles} folder ({@code sites/<id>/plugins/search/no-results.tsv}: inside the tenant folder, so a
* full backup carries it; declared {@code siteData.personal} in {@code plugin.yml}, so a <b>transfer copy leaves it
* out</b>), and written back by a background flush every {@link #FLUSH_INTERVAL} when something changed, and on
* shutdown — never synchronously on the public search path, so a burst of searches costs no disk I/O per request. A
* crash loses at most the last interval. A wholesale site replacement (restore / delete) drops the in-memory copy
* unwritten ({@link #forget}), so the restored file is what is read next. {@link #clear} empties both at once. A file
* that cannot be read is not replaced: the site's list stays unloaded (nothing is recorded for it, and nothing is
* written over the file) until a later read succeeds.
*
* <p>Thread-safe: each site's list is guarded by its own monitor.
*/
public class NoResultsLog implements AutoCloseable {
private static final Logger log = LoggerFactory.getLogger(NoResultsLog.class);
/** The per-site setting that turns recording on (default off). */
static final String ENABLED_KEY = "recordNoResults";
/** The per-site setting for how long an unseen term is kept. */
static final String RETENTION_KEY = "noResultsRetentionDays";
static final int DEFAULT_RETENTION_DAYS = 90;
static final int MAX_RETENTION_DAYS = 365;
static final int MAX_TERMS = 500;
static final int MAX_TERM_CHARS = 100;
static final Duration REPEAT_WINDOW = Duration.ofSeconds(1);
static final Duration FLUSH_INTERVAL = Duration.ofSeconds(30);
/** The per-site file, relative to this plugin's own {@link PluginSiteFiles} folder. */
static final String FILE = "no-results.tsv";
/** Upper bound on the file, read or written (500 terms of at most 100 chars + numbers fits well inside). */
static final long MAX_FILE_BYTES = 512L * 1024;
/**
* One recorded term.
*
* @param term the normalized term
* @param count how many no-result searches used it
* @param lastSeen when it was last searched
*/
public record Entry(String term, long count, Instant lastSeen) {
}
/** One site's in-memory list plus its write state; guarded by its own monitor. */
private static final class SiteTerms {
final Map<String, MutableEntry> terms = new HashMap<>();
boolean dirty;
String lastTerm;
long lastAtMillis;
}
private static final class MutableEntry {
long count;
long lastSeenMillis;
MutableEntry(long count, long lastSeenMillis) {
this.count = count;
this.lastSeenMillis = lastSeenMillis;
}
}
private final PluginSiteFiles files;
private final PluginSettings settings;
private final Clock clock;
private final ConcurrentMap<String, SiteTerms> sites = new ConcurrentHashMap<>();
private final ScheduledExecutorService flusher;
/** Production wiring: system clock and a daemon thread flushing every {@link #FLUSH_INTERVAL}. */
public NoResultsLog(PluginSiteFiles files, PluginSettings settings) {
this(files, settings, Clock.systemUTC(), true);
}
/** Test seam: a controllable clock, and no background thread (tests call {@link #flush()} themselves). */
NoResultsLog(PluginSiteFiles files, PluginSettings settings, Clock clock, boolean background) {
this.files = files;
this.settings = settings;
this.clock = clock;
if (background) {
this.flusher = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "search-no-results-flush");
t.setDaemon(true);
return t;
});
long period = FLUSH_INTERVAL.toMillis();
flusher.scheduleWithFixedDelay(this::flushQuietly, period, period, TimeUnit.MILLISECONDS);
} else {
this.flusher = null;
}
}
/** Whether recording is turned on for {@code siteId} (the per-site {@code recordNoResults}, default off). */
public boolean enabled(String siteId) {
return settings.site(siteId).bool(ENABLED_KEY, false);
}
/** The site's retention in days ({@code noResultsRetentionDays}, clamped to {@code 1..365}). */
public int retentionDays(String siteId) {
return (int) settings.site(siteId).integer(RETENTION_KEY, DEFAULT_RETENTION_DAYS, 1, MAX_RETENTION_DAYS);
}
/**
* Records that {@code rawQuery} found nothing on {@code siteId}. A no-op when recording is off for the site,
* when the term normalizes to nothing, or when it looks like personal data. Never throws and never blocks on
* disk — the public search path calls it.
*/
public void record(String siteId, String rawQuery) {
try {
if (siteId == null || !enabled(siteId)) {
return;
}
String term = normalize(rawQuery);
if (term == null || looksPersonal(term)) {
return;
}
long now = clock.millis();
SiteTerms site = site(siteId);
synchronized (site) {
if (term.equals(site.lastTerm) && now - site.lastAtMillis < REPEAT_WINDOW.toMillis()) {
return; // the same render seen twice (two boxes on one page) — count the search once
}
site.lastTerm = term;
site.lastAtMillis = now;
MutableEntry entry = site.terms.get(term);
if (entry == null) {
if (site.terms.size() >= MAX_TERMS) {
evictOne(site.terms);
}
site.terms.put(term, new MutableEntry(1, now));
} else {
entry.count++;
entry.lastSeenMillis = Math.max(entry.lastSeenMillis, now);
}
site.dirty = true;
}
} catch (RuntimeException e) {
// Deliberately no term in the message: it is visitor text that may be personal data.
log.warn("could not record a no-result search for site '{}': {}", siteId, e.getClass().getSimpleName());
}
}
/**
* The site's recorded terms within retention, most frequent first (then most recently seen, then
* alphabetical). Read-only; empty when nothing has been recorded.
*/
public List<Entry> list(String siteId) {
long cutoff = cutoffMillis(siteId);
SiteTerms site = site(siteId);
List<Entry> out = new ArrayList<>();
synchronized (site) {
site.terms.forEach((term, e) -> {
if (e.lastSeenMillis >= cutoff) {
out.add(new Entry(term, e.count, Instant.ofEpochMilli(e.lastSeenMillis)));
}
});
}
out.sort(Comparator.comparingLong(Entry::count).reversed()
.thenComparing(Entry::lastSeen, Comparator.reverseOrder())
.thenComparing(Entry::term));
return List.copyOf(out);
}
/** Forgets every recorded term for {@code siteId}, in memory and on disk. */
public void clear(String siteId) throws IOException {
SiteTerms site = site(siteId);
synchronized (site) {
site.terms.clear();
site.lastTerm = null;
site.dirty = false;
files.delete(siteId, FILE);
}
}
/** Writes every site whose list changed since its last write (pruning expired terms first). */
public void flush() {
for (Map.Entry<String, SiteTerms> e : sites.entrySet()) {
String siteId = e.getKey();
SiteTerms site = e.getValue();
synchronized (site) {
if (!site.dirty) {
continue;
}
long cutoff = cutoffMillis(siteId);
site.terms.values().removeIf(entry -> entry.lastSeenMillis < cutoff);
String text = serialize(site.terms);
if (text.getBytes(StandardCharsets.UTF_8).length > MAX_FILE_BYTES) {
log.warn("not writing an oversized no-result search list for site '{}'", siteId);
continue;
}
try {
files.writeText(siteId, FILE, text);
site.dirty = false;
} catch (IOException | RuntimeException ex) {
log.warn("could not write the no-result search list for site '{}': {}", siteId, ex.toString());
}
}
}
}
/**
* A site's files were replaced wholesale (restored from a backup, or deleted): drop the in-memory list
* <b>without</b> writing it, so the next read loads whatever the site folder now holds. Called by the plugin's
* {@code SiteEventListener} for a wholesale lifecycle event.
*/
void forget(String siteId) {
sites.remove(siteId);
}
/** Stops the background flush and writes what is pending (the host calls it on shutdown). */
@Override
public void close() {
if (flusher != null) {
flusher.shutdownNow();
}
flushQuietly();
}
private void flushQuietly() {
try {
flush();
} catch (RuntimeException e) {
log.warn("no-result search flush failed: {}", e.toString());
}
}
private long cutoffMillis(String siteId) {
return clock.millis() - Duration.ofDays(retentionDays(siteId)).toMillis();
}
/**
* The site's list, loaded on first use. A list whose file could not be read is handed out but <b>not kept</b>:
* what is recorded into it is lost and it is never flushed, so an unreadable file is never overwritten with a
* partial list; the next call tries to read the file again.
*/
private SiteTerms site(String siteId) {
SiteTerms known = sites.get(siteId);
if (known != null) {
return known;
}
SiteTerms loaded = load(siteId);
if (loaded == null) {
return new SiteTerms();
}
SiteTerms raced = sites.putIfAbsent(siteId, loaded);
return raced != null ? raced : loaded;
}
/**
* Reads the site's file (bounded; a missing, oversized or garbled file yields an empty or partial list);
* {@code null} when the file exists but cannot be read.
*/
private SiteTerms load(String siteId) {
SiteTerms site = new SiteTerms();
String text;
try {
Optional<FileEntry> stat = files.stat(siteId, FILE);
if (stat.isEmpty() || stat.get().directory() || stat.get().size() <= 0) {
return site;
}
if (stat.get().size() > MAX_FILE_BYTES) {
log.warn("ignoring an oversized no-result search list for site '{}' ({} bytes)", siteId,
stat.get().size());
return site;
}
text = files.readText(siteId, FILE).orElse("");
} catch (IOException | RuntimeException e) {
log.warn("could not read the no-result search list for site '{}': {}", siteId, e.toString());
return null;
}
for (String line : text.split("\n")) {
String[] parts = line.split("\t");
if (parts.length != 3) {
continue;
}
String term = normalize(parts[0]);
if (term == null) {
continue;
}
try {
long count = Long.parseLong(parts[1].strip());
long lastSeen = Long.parseLong(parts[2].strip());
if (count < 1) {
continue;
}
MutableEntry existing = site.terms.get(term);
if (existing != null) {
existing.count += count;
existing.lastSeenMillis = Math.max(existing.lastSeenMillis, lastSeen);
continue;
}
if (site.terms.size() >= MAX_TERMS) {
evictOne(site.terms);
}
site.terms.put(term, new MutableEntry(count, lastSeen));
} catch (NumberFormatException e) {
// a hand-edited or truncated line — skip it
}
}
return site;
}
private static String serialize(Map<String, MutableEntry> terms) {
StringBuilder b = new StringBuilder(terms.size() * 32);
terms.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEach(e -> b.append(e.getKey()).append('\t').append(e.getValue().count).append('\t')
.append(e.getValue().lastSeenMillis).append('\n'));
return b.toString();
}
/** Removes the least frequent term, the longest-unseen among equals (then the alphabetically last). */
private static void evictOne(Map<String, MutableEntry> terms) {
String victim = null;
MutableEntry worst = null;
for (Map.Entry<String, MutableEntry> e : terms.entrySet()) {
MutableEntry m = e.getValue();
if (worst == null || m.count < worst.count
|| (m.count == worst.count && m.lastSeenMillis < worst.lastSeenMillis)
|| (m.count == worst.count && m.lastSeenMillis == worst.lastSeenMillis
&& e.getKey().compareTo(victim) > 0)) {
victim = e.getKey();
worst = m;
}
}
if (victim != null) {
terms.remove(victim);
}
}
/**
* The canonical form a term is counted under: Unicode NFC, control characters removed, whitespace runs
* collapsed to one space, trimmed, lower-cased ({@link Locale#ROOT}), and cut to {@link #MAX_TERM_CHARS}
* (never splitting a surrogate pair). {@code null} when nothing is left.
*/
static String normalize(String raw) {
if (raw == null) {
return null;
}
String s = Normalizer.normalize(raw, Normalizer.Form.NFC);
StringBuilder b = new StringBuilder(Math.min(s.length(), MAX_TERM_CHARS * 2));
boolean pendingSpace = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isWhitespace(c) || Character.isSpaceChar(c)) {
pendingSpace = b.length() > 0;
continue;
}
if (Character.isISOControl(c) || Character.getType(c) == Character.FORMAT) {
continue;
}
if (pendingSpace) {
b.append(' ');
pendingSpace = false;
}
b.append(c);
}
String term = b.toString().toLowerCase(Locale.ROOT);
if (term.length() > MAX_TERM_CHARS) {
int end = MAX_TERM_CHARS;
if (Character.isHighSurrogate(term.charAt(end - 1))) {
end--;
}
term = term.substring(0, end).strip();
}
return term.isEmpty() ? null : term;
}
/**
* Whether a normalized term looks like personal data that should not be stored: an email address (an
* {@code @} with a dot somewhere after it), or a phone / ID number — seven or more digits in a run where
* spaces, dashes, dots, slashes, parentheses and a plus sign between them are ignored.
*/
static boolean looksPersonal(String term) {
int at = term.indexOf('@');
if (at > 0 && term.indexOf('.', at) > at + 1) {
return true;
}
int digits = 0;
for (int i = 0; i < term.length(); i++) {
char c = term.charAt(i);
if (Character.isDigit(c)) {
if (++digits >= 7) {
return true;
}
} else if (c != ' ' && c != '-' && c != '.' && c != '/' && c != '(' && c != ')' && c != '+') {
digits = 0;
}
}
return false;
}
}
@@ -0,0 +1,61 @@
package mx.quest.search;
import java.util.Locale;
import java.util.Objects;
import mx.quest.runway.spi.model.CatalogEntry;
import mx.quest.runway.spi.model.LocalizedUrl;
import mx.quest.runway.spi.service.ContentCatalogView;
/**
* Where the search box submits in a given language (since 2.2.0). The {@code resultsPath} setting names the results
* page by one of its addresses; a box on a Spanish page must submit to that page's Spanish address, so the results
* — and the documents searched — are Spanish. Before 2.2.0 every box submitted to the setting as written, which
* sent a visitor on {@code /es/…} to the default-language results.
*/
class ResultsPageLinks {
private final ContentCatalogView catalog;
ResultsPageLinks(ContentCatalogView catalog) {
this.catalog = Objects.requireNonNull(catalog, "catalog");
}
/**
* The results page's address in {@code locale}'s language: the page whose address in some language is
* {@code resultsPath} (compared as {@link SiteSearchCorpus#normalizePath} does), at its address in that
* language. {@code resultsPath} as written when no page has that address, or the page does not exist in
* that language.
*
* @param siteId the site
* @param resultsPath the {@code resultsPath} setting
* @param locale the language of the page the box is on
* @return the address to submit to; never {@code null}
*/
String pathFor(String siteId, String resultsPath, Locale locale) {
String wanted = SiteSearchCorpus.normalizePath(resultsPath);
try {
for (CatalogEntry entry : catalog.entries(siteId)) {
if (entry.isPage() && hasAddress(entry, wanted)) {
for (LocalizedUrl url : entry.urls()) {
if (url.locale().getLanguage().equals(locale.getLanguage())) {
return url.path();
}
}
return resultsPath;
}
}
} catch (RuntimeException e) {
// The listing is the kernel's; if it cannot be read the box still submits to the setting as written.
}
return resultsPath;
}
private static boolean hasAddress(CatalogEntry entry, String wanted) {
for (LocalizedUrl url : entry.urls()) {
if (wanted.equals(SiteSearchCorpus.normalizePath(url.path()))) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,115 @@
package mx.quest.search;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.spi.service.SitePages;
import mx.quest.search.spi.SearchCorpus;
import mx.quest.search.spi.SiteSearchEngine;
/**
* Status model for the plugin's console surfaces — the tenant dashboard card ({@code dashboard.html})
* and the admin fragment ({@code admin.html}) rendered below the per-tenant settings form. Templates read it by
* bean name, e.g. {@code ${@searchAdminModel.activeEngineKey(tenantSiteId)}}. Every method is per-site scoped and
* answers a neutral value for a {@code null} site (the application console has no bound site).
*/
public class SearchAdminModel {
private static final DateTimeFormatter LAST_SEEN =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(ZoneId.systemDefault());
private final List<SiteSearchEngine> engines;
private final SearchCorpus corpus;
private final SitePages pages;
private final PluginSettings settings;
private final NoResultsLog noResults;
public SearchAdminModel(List<SiteSearchEngine> engines, SearchCorpus corpus, SitePages pages,
PluginSettings settings, NoResultsLog noResults) {
this.engines = List.copyOf(engines);
this.corpus = Objects.requireNonNull(corpus, "corpus");
this.pages = Objects.requireNonNull(pages, "pages");
this.settings = Objects.requireNonNull(settings, "settings");
this.noResults = Objects.requireNonNull(noResults, "noResults");
}
/** Whether this site records searches that found nothing (the opt-in {@code recordNoResults}). */
public boolean noResultsRecording(String siteId) {
return siteId != null && noResults.enabled(siteId);
}
/** The site's no-result terms within retention, most frequent first (empty when none). */
public List<NoResultsLog.Entry> noResults(String siteId) {
return siteId == null ? List.of() : noResults.list(siteId);
}
/** The site's no-result retention in days (for the hint under the list). */
public int noResultsRetentionDays(String siteId) {
return siteId == null ? NoResultsLog.DEFAULT_RETENTION_DAYS : noResults.retentionDays(siteId);
}
/** The most terms a site's list keeps (for the hint under the list). */
public int noResultsMaxTerms() {
return NoResultsLog.MAX_TERMS;
}
/**
* A recorded term's last-seen time as {@code yyyy-MM-dd HH:mm} in the server's zone — the same clock the
* site's logs and the kernel's Site insights screen use — which also sorts correctly as text.
*/
public String lastSeen(NoResultsLog.Entry entry) {
return entry == null ? "" : LAST_SEEN.format(entry.lastSeen());
}
/** Whether search is enabled for this site (per-tenant flag, default true). */
public boolean enabled(String siteId) {
return siteId == null ? SearchSiteConfig.ENABLED_DEFAULT
: SearchSiteConfig.of(settings.site(siteId)).enabled();
}
/** The {@code key()} of the engine that would serve this site now (highest-priority available), or "none". */
public String activeEngineKey(String siteId) {
if (siteId == null) {
return "none";
}
return engines.stream()
.filter(e -> e.available(siteId))
.max(Comparator.comparingInt(SiteSearchEngine::priority))
.map(SiteSearchEngine::key)
.orElse("none");
}
/** How many search engines are installed (the built-in one plus any contributed by other plugins). */
public int engineCount() {
return engines.size();
}
/**
* How many items the site's search covers: every published page and content-source item of the kernel's
* listing (a safe path, not part of the reserved surface), minus the site's {@code exclude} list — exactly what
* every engine indexes ({@link SearchCorpus}).
*/
public int searchableItems(String siteId) {
return siteId == null ? 0 : corpus.corpus(siteId).size();
}
/**
* Whether this site already has the ready-made search results page (the one {@code /search/install-page}
* seeds), in any state. Asked by the installer's stable slug, so it stays true after the operator moves or
* renames the page.
*/
public boolean pageInstalled(String siteId) {
return siteId != null && pages.pathOf(siteId, SearchEndpoint.INSTALLED_PAGE_SLUG).isPresent();
}
/**
* The current URL path of the installed search page (e.g. {@code /search}, 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 siteId == null ? "" : pages.pathOf(siteId, SearchEndpoint.INSTALLED_PAGE_SLUG).orElse("");
}
}
@@ -0,0 +1,174 @@
package mx.quest.search;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
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.WidgetView;
import mx.quest.runway.spi.service.Messages;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.search.spi.SearchHit;
import mx.quest.search.spi.SearchQuery;
import mx.quest.search.spi.SiteSearchEngine;
/**
* The {@code search} content widget: a site manager drops a search box into any page (or the master chrome) with
* {@code <div id="x" data-widget="search/box"></div>} and the host renders the anchor. It emits a small GET form
* that submits {@code ?q=…} to the site's <b>results page</b> (the {@code resultsPath} setting, default
* {@code /search} — a normal, editable tenant page the operator installs from the settings, carrying this same
* widget). The widget is <b>query-aware</b> (kernel {@code WidgetView.query()}): when the page it sits on is
* requested with a non-blank {@code q}, it renders the results <b>inline below the box</b>, so the results page is
* an ordinary, restyleable site page rather than a plugin-owned surface. On a page without {@code q} (e.g. a home
* page) it renders just the box. A box in the master chrome (a header or footer) renders just the box by default, so
* the results page does not list its results twice; the per-placement {@code results} setting overrides that
* ({@link #listsResults}). Each result link carries the words the engine matched ({@link HighlightMarker}), which
* the page it opens highlights, unless the site turned {@code highlight} off.
*
* <p>Honors the per-tenant {@code enabled} flag (disabled ⇒ {@link RenderFragment#empty()}) and the
* {@code placeholder}/{@code resultLimit} settings (this plugin's {@link PluginSettings}); its words come from
* {@link Messages#site} for the site and the request locale (the site's own bundle first, then this plugin's). Titles and the query are HTML-escaped by {@link Html}; each hit's snippet is pre-escaped,
* {@code <mark>}-bearing HTML (the frozen {@link SearchHit} contract) emitted RAW. Engine selection mirrors the
* endpoint's: the highest-priority <b>available</b> {@link SiteSearchEngine} (so {@code search-lucene} takes over
* transparently). Rendering results during page render carries no per-client rate limiter (a {@code WidgetView} has no
* client IP); a query flood is bounded by the kernel's edge protection and by {@code resultLimit}. The JSON API
* ({@code GET /search/api}) keeps its dedicated {@link SearchRateLimiter}.
*
* <p>A query that finds nothing is handed to {@link NoResultsLog#record}, which does nothing unless the site turned
* recording on.
*/
public class SearchBoxWidget implements ContentWidget {
/** The per-placement setting ({@code widgetSettings} in plugin.yml) choosing whether this box lists results. */
static final String RESULTS_SETTING = "results";
static final String RESULTS_AUTO = "auto";
private final List<SiteSearchEngine> engines;
private final PluginSettings settings;
private final Messages messages;
private final NoResultsLog noResults;
/** Null in tests that do not exercise the localized action: the box then submits to the setting as written. */
private final ResultsPageLinks resultsPages;
/**
* @param noResults where a query that found nothing is recorded; {@code null} records nothing
*/
public SearchBoxWidget(List<SiteSearchEngine> engines, PluginSettings settings, Messages messages,
NoResultsLog noResults) {
this(engines, settings, messages, noResults, null);
}
SearchBoxWidget(List<SiteSearchEngine> engines, PluginSettings settings, Messages messages,
NoResultsLog noResults, ResultsPageLinks resultsPages) {
this.engines = List.copyOf(engines);
this.settings = Objects.requireNonNull(settings, "settings");
this.messages = Objects.requireNonNull(messages, "messages");
this.noResults = noResults;
this.resultsPages = resultsPages;
}
@Override
public String key() {
return "search";
}
@Override
public RenderFragment render(WidgetView view) {
String siteId = view.site().id();
SearchSiteConfig cfg = SearchSiteConfig.of(settings.site(siteId));
if (!cfg.enabled()) {
return RenderFragment.empty();
}
Locale locale = view.locale();
String placeholder = cfg.placeholder(msg(siteId, "search.box.placeholder", "Search…", locale));
String submit = msg(siteId, "search.box.submit", "Search", locale);
// The results page in this page's language (2.2.0): a box on /es/… submits to the Spanish results.
String action = resultsPages == null ? cfg.resultsPath()
: resultsPages.pathFor(siteId, cfg.resultsPath(), locale);
String query = view.query().getOrDefault("q", "").strip();
StringBuilder b = new StringBuilder(512);
b.append("<link rel=\"stylesheet\" href=\"/__plugin/search/static/search.css")
.append(SearchConfig.ASSET_QUERY).append("\">")
.append("<form class=\"rw-search-box\" method=\"get\" action=\"").append(Html.escape(action))
.append("\" role=\"search\">")
.append("<input class=\"rw-search-box-input\" type=\"search\" name=\"q\" value=\"")
.append(Html.escape(query)).append("\" placeholder=\"").append(Html.escape(placeholder))
.append("\" aria-label=\"").append(Html.escape(placeholder)).append("\">")
.append("<button class=\"rw-search-box-submit\" type=\"submit\">").append(Html.escape(submit))
.append("</button></form>");
// Query-aware: when this page is requested with ?q=…, render the results below the box (the results page
// is a normal editable page carrying this widget), so there is no plugin-owned results surface.
if (!query.isBlank() && listsResults(view)) {
List<SearchHit> hits = search(siteId, query, locale, cfg.resultLimit());
if (hits.isEmpty() && noResults != null) {
noResults.record(siteId, query); // a content gap (a no-op unless the site opted in)
}
b.append(renderResults(siteId, query, hits, locale, cfg.highlight()));
}
return RenderFragment.of(b.toString());
}
/**
* Whether this placement lists results when its page carries {@code ?q=} — the placement's {@code results}
* setting (since 2.1.0): {@code always}, {@code never}, or {@code auto} (the default), which lists them unless the
* box sits in the master chrome. A header or footer box is in the chrome and appears on the results page too;
* before 2.1.0 it listed the results a second time there.
*/
static boolean listsResults(WidgetView view) {
Object setting = view.config().get(RESULTS_SETTING);
String mode = setting == null ? RESULTS_AUTO : setting.toString().strip().toLowerCase(Locale.ROOT);
return switch (mode) {
case "always" -> true;
case "never" -> false;
default -> !view.isChrome();
};
}
/** The results block (count/empty + hit list) rendered inline below the box; empty string on a blank query. */
private String renderResults(String siteId, String query, List<SearchHit> hits, Locale locale,
boolean highlight) {
StringBuilder b = new StringBuilder(512);
if (hits.isEmpty()) {
return b.append("<p class=\"rw-search-empty\">")
.append(Html.escape(msg(siteId, "search.results.none", "No results for", locale)))
.append(" “").append(Html.escape(query)).append("”.</p>").toString();
}
b.append("<p class=\"rw-search-count\">").append(hits.size()).append(' ')
.append(Html.escape(msg(siteId, "search.results.count", "result(s) for", locale)))
.append(" “").append(Html.escape(query)).append("”</p><ol class=\"rw-search-hits\">");
for (SearchHit hit : hits) {
b.append("<li class=\"rw-search-hit\"><a class=\"rw-search-hit-link\" href=\"")
.append(Html.escape(highlight ? HighlightMarker.link(hit) : hit.url())).append("\">")
.append(Html.escape(hit.title())).append("</a>");
if (!hit.snippet().isBlank()) {
// Pre-escaped, <mark>-bearing HTML (frozen SearchHit contract): emit RAW so the highlight shows as
// emphasis, not literal &lt;mark&gt;. XSS-safe because the engine escaped every source character.
b.append("<p class=\"rw-search-hit-snippet\">").append(hit.snippet()).append("</p>");
}
b.append("</li>");
}
return b.append("</ol>").toString();
}
/** Runs the query through the highest-priority available engine (empty on a blank query or no engine). */
private List<SearchHit> search(String siteId, String query, Locale locale, int limit) {
SiteSearchEngine engine = engines.stream()
.filter(e -> e.available(siteId))
.max(Comparator.comparingInt(SiteSearchEngine::priority))
.orElse(null);
return engine == null ? List.of() : engine.search(new SearchQuery(siteId, query, locale, limit));
}
private String msg(String siteId, String key, String fallback, Locale locale) {
return messages.site(siteId, locale, key, fallback);
}
@Override
public Capabilities capabilities() {
return Capabilities.of("widget.search");
}
}
@@ -0,0 +1,27 @@
package mx.quest.search;
import mx.quest.runway.spi.model.RouteRequest;
/**
* The per-client key for the search {@link SearchRateLimiter}: the request's client IP as the kernel resolved it
* <b>after its trusted-proxy gate</b> ({@link RouteRequest#clientIp()}, SPI 0.5.0) — a forwarded header counts only
* when the immediate peer is a configured trusted proxy, and never reaches the plugin otherwise. Search 1.x read the
* first hop of {@code X-Forwarded-For} itself, which any visitor could set to a fresh value per request to evade the
* limit.
*
* <p>When the kernel has no client IP for a request, every such request shares one {@value #SHARED} bucket, so it
* still counts against <em>a</em> limit rather than escaping it.
*/
final class SearchClientId {
static final String SHARED = "shared";
private SearchClientId() {
}
/** The trusted client IP, else the shared fallback bucket. */
static String of(RouteRequest request) {
String ip = request.clientIp();
return (ip == null || ip.isBlank()) ? SHARED : ip.strip();
}
}
@@ -0,0 +1,133 @@
package mx.quest.search;
import java.util.List;
import mx.quest.runway.spi.ContentWidget;
import mx.quest.runway.spi.EndpointContributor;
import mx.quest.runway.spi.HeadContributor;
import mx.quest.runway.spi.service.AccessCheck;
import mx.quest.runway.spi.service.ContentCatalogView;
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.SiteEventListener;
import mx.quest.runway.spi.service.SitePages;
import mx.quest.runway.spi.service.Sites;
import mx.quest.search.spi.SearchCorpus;
import mx.quest.search.spi.SiteSearchEngine;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* The plugin's {@code mainClass} — the single {@code @Configuration} the host registers into its context before
* refresh. Every bean is wired EXPLICITLY (no {@code @ComponentScan}). The package {@code mx.quest.search} 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 0.6.0):
* {@link PluginSettings} (this plugin's per-site settings) and {@link PluginSiteFiles} (this plugin's per-site
* folder, where the no-result terms are kept) are bound to this plugin by the jar this class was loaded from;
* {@link ContentCatalogView}, {@link Sites}, {@link Messages}, {@link AccessCheck} and {@link SitePages} are kernel
* singletons. Nothing outside {@code mx.quest.runway.spi} is linked. Every bean name starts with the plugin id
* ({@code search…}), the kernel's rule for a bean namespace plugins share.
*
* <p>The plugin publishes its own SPI ({@code mx.quest.search.spi}): the {@link SearchCorpus} every engine builds
* from (the content listing minus the site's exclusions) and the {@link SiteSearchEngine} extension point, with the
* built-in {@link SimpleSearchEngine}. The {@link SearchEndpoint} and {@link SearchBoxWidget} are list-collected
* kernel SPIs — plain {@code @Bean}s, NEVER {@code @Primary}; both inject {@code List<SiteSearchEngine>}, so a
* companion plugin (e.g. {@code search-lucene}) that contributes a higher-priority engine is picked up transparently.
* One {@link SiteEventListener} ({@link SearchSiteEvents}) keeps the built-in index and the no-result list fresh, and
* one {@link HeadContributor} ({@link SearchHighlightHead}) lets a page opened from a result highlight the matches.
*
* <p>App-level knobs bind from {@code external/plugin-settings/search.yml} into {@link SearchProperties} through
* the {@code @ConfigurationProperties} on {@link #searchProperties()}.
*/
@Configuration(proxyBeanMethods = false)
public class SearchConfig {
/**
* This release's version, appended as {@code ?v=} to the plugin's own file URLs (search.css, the highlighter) so
* a browser fetches the new files right after an upgrade instead of keeping the previous copy for the kernel's
* plugin-file cache lifetime. {@code SearchConfigTest} holds it equal to {@code plugin.yml}'s version and to the
* URLs inside the static scripts.
*/
public static final String VERSION = "2.3.0";
/** The query a plugin file URL ends with. */
static final String ASSET_QUERY = "?v=" + VERSION;
/** The app-level settings ({@code runway.plugin.search.*}), bound by the host's properties binder. */
@Bean
@ConfigurationProperties(prefix = "runway.plugin.search")
public SearchProperties searchProperties() {
return new SearchProperties();
}
/** What every engine indexes: the kernel's content listing minus the site's {@code exclude} list. */
@Bean
public SearchCorpus searchCorpus(ContentCatalogView catalog, PluginSettings settings) {
return new SiteSearchCorpus(catalog, settings);
}
/** The built-in engine — a full-text matcher over title/description/body; always available, priority 0. */
@Bean
public SimpleSearchEngine searchSimpleEngine(SearchCorpus corpus, Sites sites, PluginSettings settings,
SearchProperties properties) {
return new SimpleSearchEngine(corpus, sites, settings, properties);
}
/** The per-client query limiter for the JSON API, built from the app-level rate-limit settings. */
@Bean
public SearchRateLimiter searchRateLimiter(SearchProperties properties) {
return new SearchRateLimiter(properties.getRateLimit());
}
/**
* The per-site record of searches that found nothing (opt-in per site; see {@link NoResultsLog}). Its
* {@code close()} is the bean's inferred destroy method, so pending terms are written on shutdown.
*/
@Bean
public NoResultsLog searchNoResultsLog(PluginSiteFiles files, PluginSettings settings) {
return new NoResultsLog(files, settings);
}
/** Drops the built-in index on every content-surface change, and the no-result list on a restore/delete. */
@Bean
public SiteEventListener searchSiteEvents(SimpleSearchEngine engine, NoResultsLog noResults) {
return new SearchSiteEvents(engine, noResults);
}
/** The JSON API and the gated maintenance actions (reindex, page install, clear no-result terms). */
@Bean
public EndpointContributor searchResultsEndpoint(List<SiteSearchEngine> engines, PluginSettings settings,
Messages messages, SearchRateLimiter rateLimiter,
AccessCheck access, SitePages pages, NoResultsLog noResults) {
return new SearchEndpoint(engines, settings, messages, rateLimiter, access, pages, noResults);
}
/**
* The embeddable, query-aware search box ({@code data-widget="search/box"}): renders the box, and when its
* page is requested with {@code ?q=…} renders the results inline — so the results page is a normal editable
* tenant page, not a plugin-owned surface.
*/
@Bean
public ContentWidget searchBoxWidget(List<SiteSearchEngine> engines, PluginSettings settings, Messages messages,
NoResultsLog noResults, ContentCatalogView catalog) {
return new SearchBoxWidget(engines, settings, messages, noResults, new ResultsPageLinks(catalog));
}
/**
* The result highlighter's loader on every page of a site with search and {@code highlight} on: a page opened
* from a result highlights the words the engine matched. A list-collected kernel SPI — a plain {@code @Bean}.
*/
@Bean
public HeadContributor searchHighlightHead(PluginSettings settings) {
return new SearchHighlightHead(settings);
}
/** Status model for the dashboard card + admin fragment (including the no-result terms list). */
@Bean
public SearchAdminModel searchAdminModel(List<SiteSearchEngine> engines, SearchCorpus corpus, SitePages pages,
PluginSettings settings, NoResultsLog noResults) {
return new SearchAdminModel(engines, corpus, pages, settings, noResults);
}
}
@@ -0,0 +1,30 @@
package mx.quest.search;
import java.util.Locale;
/**
* One indexed page for the built-in engine: the display fields (URL, title, description) plus a plain-text
* <b>body</b> extracted from the page HTML, alongside pre-lowercased copies of title/description/body so scoring
* is a cheap {@code contains}/count without re-casing on every query. Immutable and built once per index build.
*
* @param slug the page slug (used for exclusion matching and diagnostics)
* @param url the public URL to link to
* @param title the display title
* @param description the display description (a snippet source when the body has no hit)
* @param body the extracted plain-text body (the snippet source and the bulk of the searchable text)
* @param normTitle {@code title} lowercased for matching
* @param normDescription {@code description} lowercased for matching
* @param normBody {@code body} lowercased for matching
*/
record SearchDocument(String slug, String url, String title, String description, String body,
String normTitle, String normDescription, String normBody) {
/** Builds a document, deriving the normalized (lowercased) match fields from the display fields. */
static SearchDocument of(String slug, String url, String title, String description, String body) {
String t = title == null ? "" : title;
String d = description == null ? "" : description;
String b = body == null ? "" : body;
return new SearchDocument(slug, url, t, d, b,
t.toLowerCase(Locale.ROOT), d.toLowerCase(Locale.ROOT), b.toLowerCase(Locale.ROOT));
}
}
@@ -0,0 +1,370 @@
package mx.quest.search;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import mx.quest.runway.spi.EndpointContributor;
import mx.quest.runway.spi.model.Capabilities;
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 mx.quest.search.spi.SearchHit;
import mx.quest.search.spi.SearchQuery;
import mx.quest.search.spi.SiteSearchEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The search plugin's request surface — it owns <b>no visible page</b>. The search box + inline results are a
* query-aware {@link SearchBoxWidget} on a normal, editable tenant page (the operator installs the ready-made
* results page from the settings). This endpoint only:
* <ul>
* <li><b>{@code GET /search/api?q=…}</b> — results as JSON, for a site's own scripts / an autocomplete box.
* Picks the highest-priority <b>available</b> {@link SiteSearchEngine} (so {@code search-lucene} takes over
* transparently). {@code noindex} (fail-safe posture) and rate-limited per client by
* {@link SearchRateLimiter}, keyed on the client IP the kernel resolved behind its trusted-proxy gate
* ({@link RouteRequest#clientIp()}). A query that finds nothing is handed to {@link NoResultsLog#record} (a
* no-op unless the site opted in).</li>
* <li><b>{@code POST /search/reindex}</b> — rebuilds this site's index on <b>every</b> registered engine via
* {@link SiteSearchEngine#reindex} (the built-in and any contributed engine alike).</li>
* <li><b>{@code POST /search/install-page}</b> — installs the ready-made, editable results page at
* {@code /search} carrying the search-box widget through {@link SitePages#install}, which follows the site's
* editorial level and never overwrites; the operator is told which outcome happened. It is created
* {@code noindex} (see {@link #handleInstallPage}).</li>
* <li><b>{@code POST /search/no-results/clear}</b> — forgets the site's recorded no-result terms
* ({@link NoResultsLog}), then redirects back to the settings page.</li>
* </ul>
*
* <h2>The three operator actions are CSRF-checked {@code POST}s</h2>
* Each changes state (an index is rebuilt, a page is created, data is deleted), so each is an ordinary,
* <b>non-anonymous</b> {@code POST} route: the kernel's tenant chain demands the console session's CSRF token (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 any of them matches no route (the kernel
* answers 404) and {@link #handle} refuses a wrong method too, as a second line. Each is gated by the
* {@code search|settings} control point through {@link AccessCheck} and fails <b>closed</b> ({@code 404}) for
* anyone who lacks it. Their answers are console text, in the operator's language ({@link Messages#console}).
*
* <p>The public API honours the per-tenant {@code enabled} flag (disabled ⇒ {@code 404}). The JSON snippet is
* rendered per the frozen {@link SearchHit} contract: the query is escaped by the JSON writer and the pre-escaped,
* {@code <mark>}-bearing snippet travels verbatim as a JSON string.
*/
public class SearchEndpoint implements EndpointContributor {
private static final Logger log = LoggerFactory.getLogger(SearchEndpoint.class);
static final String PLUGIN_ID = "search";
/** The control point that gates the maintenance actions (declared in {@code plugin.yml}). */
static final String SETTINGS_PERMISSION = "search|settings";
/** The slug/path the ready-made, editable results page is installed at (then owned + movable by the operator). */
static final String INSTALLED_PAGE_SLUG = "search";
static final String API_PATH = "/search/api";
static final String REINDEX_PATH = "/search/reindex";
static final String INSTALL_PATH = "/search/install-page";
/** The POST action (from the admin fragment's CSRF-carrying form) that forgets the site's no-result terms. */
static final String CLEAR_NO_RESULTS_PATH = "/search/no-results/clear";
/** Where the clear action sends the operator back to: this plugin's per-tenant settings page. */
static final String SETTINGS_PAGE = "/__admin/plugins/" + PLUGIN_ID + "/settings";
private final List<SiteSearchEngine> engines;
private final PluginSettings settings;
private final Messages messages;
private final SearchRateLimiter rateLimiter;
private final AccessCheck access;
private final SitePages pages;
private final NoResultsLog noResults;
public SearchEndpoint(List<SiteSearchEngine> engines, PluginSettings settings, Messages messages,
SearchRateLimiter rateLimiter, AccessCheck access, SitePages pages,
NoResultsLog noResults) {
this.engines = List.copyOf(engines);
this.settings = Objects.requireNonNull(settings, "settings");
this.messages = Objects.requireNonNull(messages, "messages");
this.rateLimiter = Objects.requireNonNull(rateLimiter, "rateLimiter");
this.access = Objects.requireNonNull(access, "access");
this.pages = Objects.requireNonNull(pages, "pages");
this.noResults = Objects.requireNonNull(noResults, "noResults");
}
@Override
public String key() {
return "search/results";
}
@Override
public List<Route> routes() {
// No public /search PAGE — the box + inline results are a widget on a normal editable page. These are the
// JSON API + the three 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 applies.
return List.of(
new Route("GET", API_PATH, Realm.TENANT, SurfacePosture.safeDefault()),
new Route("POST", REINDEX_PATH, Realm.TENANT, SurfacePosture.safeDefault()),
new Route("POST", INSTALL_PATH, Realm.TENANT, SurfacePosture.safeDefault()),
new Route("POST", CLEAR_NO_RESULTS_PATH, Realm.TENANT, SurfacePosture.safeDefault()));
}
@Override
public RouteResponse handle(RouteRequest req) {
// The kernel dispatches by method + path; these method checks are the second line.
boolean post = "POST".equalsIgnoreCase(req.method());
return switch (req.path()) {
case API_PATH -> "GET".equalsIgnoreCase(req.method()) ? handleApi(req) : RouteResponse.notFound();
case REINDEX_PATH -> post ? handleReindex(req) : RouteResponse.notFound();
case INSTALL_PATH -> post ? handleInstallPage(req) : RouteResponse.notFound();
case CLEAR_NO_RESULTS_PATH -> post ? handleClearNoResults(req) : RouteResponse.notFound();
default -> RouteResponse.notFound();
};
}
// --- JSON API ----------------------------------------------------------------------------------
private RouteResponse handleApi(RouteRequest req) {
String siteId = req.site().id();
SearchSiteConfig cfg = SearchSiteConfig.of(settings.site(siteId));
if (!cfg.enabled()) {
return RouteResponse.notFound();
}
String query = req.query().getOrDefault("q", List.of()).stream().findFirst().orElse("").strip();
if (!query.isBlank() && !rateLimiter.tryAcquire(SearchClientId.of(req))) {
return json(429, "{\"error\":\"rate_limited\"}");
}
List<SearchHit> hits = search(siteId, query, req.locale(), cfg.resultLimit());
if (hits.isEmpty() && !query.isBlank()) {
noResults.record(siteId, query); // a content gap (a no-op unless the site opted in)
}
return json(200, toJson(query, hits, cfg.highlight()));
}
/**
* Serializes results as JSON with a hand-rolled, correctly-escaped writer (no Jackson dependency): every
* string value is JSON-escaped, and the snippet — pre-escaped HTML with {@code <mark>} — travels verbatim as
* a JSON string, so a consumer can insert it as HTML on its side under the same contract. Since 2.1.0 each
* result also has {@code terms} (the matched words, plain text) and {@code link}: the URL with the highlight
* marker ({@link HighlightMarker}), or the plain URL when the site turned {@code highlight} off.
*/
static String toJson(String query, List<SearchHit> hits, boolean highlight) {
StringBuilder b = new StringBuilder(256);
b.append("{\"query\":").append(jsonString(query)).append(",\"count\":").append(hits.size())
.append(",\"results\":[");
for (int i = 0; i < hits.size(); i++) {
SearchHit hit = hits.get(i);
if (i > 0) {
b.append(',');
}
b.append("{\"url\":").append(jsonString(hit.url()))
.append(",\"title\":").append(jsonString(hit.title()))
.append(",\"snippet\":").append(jsonString(hit.snippet()))
.append(",\"score\":").append(hit.score())
.append(",\"link\":").append(jsonString(highlight ? HighlightMarker.link(hit) : hit.url()))
.append(",\"terms\":[");
for (int t = 0; t < hit.terms().size(); t++) {
b.append(t > 0 ? "," : "").append(jsonString(hit.terms().get(t)));
}
b.append("]}");
}
return b.append("]}").toString();
}
// --- maintenance: reindex ----------------------------------------------------------------------
/**
* Rebuilds this site's index on <b>every</b> registered engine via {@link SiteSearchEngine#reindex} — not
* only the built-in one, so a contributed engine (e.g. {@code search-lucene}) is rebuilt by the same button.
* The reported count is the fresh document count of the engine that actually serves this site's queries (the
* highest-priority available one), since that is the index whose results the operator is looking at.
*/
private RouteResponse handleReindex(RouteRequest req) {
if (!access.may(SETTINGS_PERMISSION)) {
return RouteResponse.notFound(); // fail closed: never reveal the action to the unauthorized
}
String siteId = req.site().id();
SiteSearchEngine active = pick(siteId);
int total = 0;
for (SiteSearchEngine engine : engines) {
int documents = engine.reindex(siteId);
if (engine == active) {
total = documents;
}
}
return RouteResponse.text(200, console("search.reindex.done", "Search index rebuilt.") + " (" + total + ")");
}
// --- maintenance: clear the no-result terms ----------------------------------------------------
/**
* Forgets every recorded no-result term for this site, then sends the operator back to the settings page
* ({@code 303}).
*/
private RouteResponse handleClearNoResults(RouteRequest req) {
if (!access.may(SETTINGS_PERMISSION)) {
return RouteResponse.notFound();
}
try {
noResults.clear(req.site().id());
} catch (IOException | RuntimeException e) {
log.warn("could not clear the no-result search list for site '{}': {}", req.site().id(), e.toString());
return RouteResponse.text(500, console("search.noresults.clearFailed",
"Could not clear the list of searches with no results."));
}
return new RouteResponse(303, Map.of("Location", SETTINGS_PAGE), new byte[0]);
}
// --- maintenance: install search landing page --------------------------------------------------
/**
* Installs a first-class, editable tenant page at {@code /search} carrying the query-aware search-box widget,
* so the results page is a real, master-wrapped site page the operator owns. {@link SitePages#install} never
* overwrites (an existing page is reported with where it lives now) and follows the site's editorial level. The
* page is created {@code noindex}: a search-results page is the platform design docs' canonical index
* opt-<b>out</b> (thin, duplicate, infinite crawl space engines discourage indexing); since the page is the
* operator's own after install, the setting can still be flipped in the page meta.
*/
private RouteResponse handleInstallPage(RouteRequest req) {
if (!access.may(SETTINGS_PERMISSION)) {
return RouteResponse.notFound();
}
String siteId = req.site().id();
// The installed page is titled in the SITE default language (the page is site-default-only).
Locale siteDefault = req.site().defaultLocale();
String title = messages.site(siteId, siteDefault, "search.page.title", "Search");
StarterPage page = new StarterPage(INSTALLED_PAGE_SLUG, "/" + INSTALLED_PAGE_SLUG,
Map.of(siteDefault.getLanguage(), title), installedPageHtml(title), installedPageLogic(), true);
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("search page install failed for site '{}': {}", siteId, e.toString());
return RouteResponse.text(500, console("search.page.failed", "Could not install the search 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("search.page.installed", "Search page installed at") + " " + path;
case PENDING_REVIEW -> console("search.page.pending",
"The search page was created and is waiting in the review queue:") + " " + path;
case DRAFT_BLOCKED -> {
StringBuilder text = new StringBuilder(console("search.page.blocked",
"The search 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("search.page.exists", "A search page already exists at") + " " + path;
default -> console("search.page.other", "The search page install finished:") + " "
+ result.outcome() + " " + path;
};
}
/**
* The body ({@code .html}) of the installed page: a normal tenant page with the master's chrome seams
* ({@code #site-header}/{@code #site-footer}/{@code head}, filled by {@link #installedPageLogic()}) whose
* {@code #content} carries the search-box widget anchor. The anchor bears both an {@code id} and
* {@code data-widget="search/box"} on the same element (the widget-binding contract) so the host's widget
* scanner renders the box in place.
*/
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=\"search-page-title\">" + t + "</h1>\n"
+ " <div id=\"search-box\" data-widget=\"search/box\"></div>\n"
+ "</main>\n<footer id=\"site-footer\"></footer>\n</body>\n</html>\n";
}
/**
* The decoupled logic ({@code .th.xml}) of the installed page: pulls the master's chrome via the
* {@code ${master}} model variable (never a literal {@code __…__} name) and sets the page title.
*/
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=\"#search-page-title\" th:text=\"${pageTitle}\"/>\n"
+ "</thlogic>\n";
}
// --- engine selection --------------------------------------------------------------------------
private List<SearchHit> search(String siteId, String query, Locale locale, int limit) {
if (query.isBlank()) {
return List.of();
}
SiteSearchEngine engine = pick(siteId);
return engine == null ? List.of() : engine.search(new SearchQuery(siteId, query, locale, limit));
}
/** The highest-priority engine that can serve {@code siteId} right now; {@code null} if none can. */
SiteSearchEngine pick(String siteId) {
return engines.stream()
.filter(e -> e.available(siteId))
.max(Comparator.comparingInt(SiteSearchEngine::priority))
.orElse(null);
}
// --- helpers -----------------------------------------------------------------------------------
private static RouteResponse json(int status, String body) {
return new RouteResponse(status, Map.of("Content-Type", "application/json; charset=utf-8"),
body.getBytes(StandardCharsets.UTF_8));
}
private String console(String key, String fallback) {
return messages.console(key, fallback);
}
/** JSON-escapes a string into a quoted JSON literal (control chars, quotes, backslashes, and the angle brackets). */
private static String jsonString(String value) {
if (value == null) {
return "\"\"";
}
StringBuilder b = new StringBuilder(value.length() + 8).append('"');
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
switch (c) {
case '"' -> b.append("\\\"");
case '\\' -> b.append("\\\\");
case '\n' -> b.append("\\n");
case '\r' -> b.append("\\r");
case '\t' -> b.append("\\t");
// Escape < and > with unicode escapes so a JSON string embedded in an HTML <script> block
// can't be broken out of with a literal close tag; the snippet's own mark tag survives escaped.
case '<' -> b.append("\\u003c");
case '>' -> b.append("\\u003e");
default -> {
if (c < 0x20) {
b.append(String.format("\\u%04x", (int) c));
} else {
b.append(c);
}
}
}
}
return b.append('"').toString();
}
@Override
public Capabilities capabilities() {
return Capabilities.of("endpoint.tenant", "search.results");
}
}
@@ -0,0 +1,47 @@
package mx.quest.search;
import java.util.Objects;
import mx.quest.runway.spi.HeadContributor;
import mx.quest.runway.spi.model.HeadContext;
import mx.quest.runway.spi.service.PluginSettings;
/**
* Puts the result highlighter on every page of a site that has search and {@code highlight} on (since 2.1.0). What
* it adds to the {@code <head>} is one {@code <script src defer>} for {@code static/highlight-loader.js}, a file of a
* few hundred bytes that does nothing unless the address carries the {@link HighlightMarker} fragment, now or after a
* {@code hashchange}; only then does it load {@code static/highlight.js}, which does the work.
*
* <p><b>CSP.</b> An external same-origin script, because the kernel stamps the page's nonce only on scripts the
* host-allowlist policy would also run: an inline script stays unstamped, and blocked, under {@code enforce}. The
* plugin writes no nonce itself; the script the loader creates is trusted through {@code 'strict-dynamic'} (and is
* same-origin under an allowlist policy).
*
* <p>Nothing is added to an editor preview, which no result links to. The output depends only on this plugin's
* per-site settings, which the kernel folds into the page's {@code ETag} itself, so {@link #headInputs} stays empty.
*/
public class SearchHighlightHead implements HeadContributor {
/** The one tag added to each page. */
static final String LOADER = "<script src=\"/__plugin/search/static/highlight-loader.js"
+ SearchConfig.ASSET_QUERY + "\" defer></script>";
private final PluginSettings settings;
public SearchHighlightHead(PluginSettings settings) {
this.settings = Objects.requireNonNull(settings, "settings");
}
@Override
public String key() {
return "search.highlight";
}
@Override
public String render(HeadContext context) {
if (context.preview()) {
return "";
}
SearchSiteConfig cfg = SearchSiteConfig.of(settings.site(context.site().id()));
return cfg.enabled() && cfg.highlight() ? LOADER : "";
}
}
@@ -0,0 +1,67 @@
package mx.quest.search;
/**
* The plugin's <b>app-level</b> settings — the platform concerns, bound from the UI-owned property source
* {@code external/plugin-settings/search.yml} under {@code runway.plugin.search.*} (declared as {@code settings:}
* in {@code plugin.yml}; applied on restart). Bound by the {@code @ConfigurationProperties} on its {@code @Bean}
* method ({@code searchProperties} in {@link SearchConfig}) rather than {@code @EnableConfigurationProperties}, so the
* bean carries the plugin-id prefix every plugin bean name needs. These are deliberately NOT per-tenant: a tenant must not be able to
* set filesystem/timer/abuse knobs that affect the platform.
*
* <ul>
* <li>{@code refresh-minutes} — how long a built-in per-site index stays fresh before it is rebuilt on the next
* query. It re-captures changes an event can't announce (notably i18n edits) without a manual reindex.</li>
* <li>{@code rate-limit.*} — the per-IP query ceiling on the public search endpoints, a small abuse guard so a
* query flood can't hammer the index. Two windows: per minute and per hour.</li>
* </ul>
*/
public class SearchProperties {
/** Minutes a built-in per-site index is considered fresh before the next query rebuilds it (default 60). */
private int refreshMinutes = 60;
private final RateLimit rateLimit = new RateLimit();
public int getRefreshMinutes() {
return refreshMinutes;
}
public void setRefreshMinutes(int refreshMinutes) {
this.refreshMinutes = refreshMinutes;
}
public RateLimit getRateLimit() {
return rateLimit;
}
/** Freshness TTL in millis, floored at one minute so a misconfigured 0 can't rebuild on every query. */
long freshnessMillis() {
return Math.max(1, refreshMinutes) * 60_000L;
}
/** The two-window per-IP ceiling for the public search endpoints. */
public static class RateLimit {
/** Maximum queries one IP may make per rolling minute (default 30). */
private int perIpPerMinute = 30;
/** Maximum queries one IP may make per rolling hour (default 600). */
private int perIpPerHour = 600;
public int getPerIpPerMinute() {
return perIpPerMinute;
}
public void setPerIpPerMinute(int perIpPerMinute) {
this.perIpPerMinute = perIpPerMinute;
}
public int getPerIpPerHour() {
return perIpPerHour;
}
public void setPerIpPerHour(int perIpPerHour) {
this.perIpPerHour = perIpPerHour;
}
}
}
@@ -0,0 +1,119 @@
package mx.quest.search;
import java.time.Clock;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* A tiny per-client query limiter for the public JSON search API — the small in-plugin abuse guard that keeps a
* query flood from hammering the index. Two fixed windows per client, one minute and one hour, each starting at the
* client's first query in it; a window whose ceiling is {@code <= 0} is disabled.
*
* <h2>The key</h2>
* The caller keys it with {@link SearchClientId#of}: the request's client IP <b>after the kernel's trusted-proxy
* gate</b> ({@code RouteRequest.clientIp()}, SPI 0.5.0). A forwarded header is applied by the kernel only when the
* immediate peer is a configured trusted proxy, so a visitor cannot pick a fresh key per request by sending a made-up
* {@code X-Forwarded-For} (search 1.x keyed on that header's first hop and could be evaded that way). The kernel's
* edge guard stays the real, platform-wide DoS floor beneath this courtesy limit.
*
* <h2>Bounded</h2>
* At most {@link #MAX_KEYS} clients are tracked. When the table is full, clients whose windows have all expired are
* dropped first; if every tracked client is still active, the table is emptied (every window restarts) — the limiter
* fails open rather than growing without bound, which is acceptable for a courtesy limit with a floor beneath it.
*
* <p>Thread-safe.
*/
public class SearchRateLimiter {
/** Bounds the number of distinct clients held, so the limiter itself can't be turned into a memory-growth vector. */
static final int MAX_KEYS = 50_000;
private static final long MINUTE = Duration.ofMinutes(1).toMillis();
private static final long HOUR = Duration.ofHours(1).toMillis();
private final int perMinute;
private final int perHour;
private final int maxKeys;
private final Clock clock;
private final Map<String, Windows> clients = new ConcurrentHashMap<>();
public SearchRateLimiter(SearchProperties.RateLimit config) {
this(config, Clock.systemUTC(), MAX_KEYS);
}
/** Test seam: a controllable clock and table size. */
SearchRateLimiter(SearchProperties.RateLimit config, Clock clock, int maxKeys) {
this.perMinute = config.getPerIpPerMinute();
this.perHour = config.getPerIpPerHour();
this.clock = clock;
this.maxKeys = maxKeys;
}
/**
* Records one query for {@code clientId} and reports whether it is within both windows. A blank id passes
* (no key to count); a window whose ceiling is {@code <= 0} is disabled and never rejects.
*
* @return {@code true} to allow the query, {@code false} to reject it (the caller answers {@code 429})
*/
public boolean tryAcquire(String clientId) {
if (clientId == null || clientId.isBlank()) {
return true;
}
long now = clock.millis();
if (clients.size() >= maxKeys && !clients.containsKey(clientId)) {
makeRoom(now);
}
Windows windows = clients.computeIfAbsent(clientId, k -> new Windows(now));
return windows.acquire(now, perMinute, perHour);
}
/** How many clients are tracked (for tests). */
int trackedClients() {
return clients.size();
}
private synchronized void makeRoom(long now) {
clients.values().removeIf(w -> w.expired(now));
if (clients.size() >= maxKeys) {
clients.clear();
}
}
/** One client's two fixed windows; guarded by its own monitor. */
private static final class Windows {
private long minuteStart;
private int minuteCount;
private long hourStart;
private int hourCount;
Windows(long now) {
this.minuteStart = now;
this.hourStart = now;
}
synchronized boolean acquire(long now, int perMinute, int perHour) {
if (now - minuteStart >= MINUTE) {
minuteStart = now;
minuteCount = 0;
}
if (now - hourStart >= HOUR) {
hourStart = now;
hourCount = 0;
}
minuteCount = saturatedIncrement(minuteCount);
hourCount = saturatedIncrement(hourCount);
boolean minuteOk = perMinute <= 0 || minuteCount <= perMinute;
boolean hourOk = perHour <= 0 || hourCount <= perHour;
return minuteOk && hourOk;
}
synchronized boolean expired(long now) {
return now - hourStart >= HOUR && now - minuteStart >= MINUTE;
}
private static int saturatedIncrement(int count) {
return count == Integer.MAX_VALUE ? count : count + 1;
}
}
}
@@ -0,0 +1,127 @@
package mx.quest.search;
import java.util.List;
import java.util.Locale;
import mx.quest.runway.spi.model.SettingsView;
/**
* The plugin's typed, per-site settings — an immutable view over the {@link SettingsView} the kernel's
* {@code PluginSettings.site(siteId)} returns for this plugin ({@code sites/<id>/plugins/search.yml} overlaid on the
* {@code siteSettings:} defaults of {@code plugin.yml}). The kernel already applies the descriptor defaults; the code
* fallbacks here only matter for a key the schema does not declare, and every one of them equals its descriptor
* {@code default:} (a test holds the two equal).
*
* <p>The ranking weights (title/description/body) and the phrase/all-terms bonuses shape the score; the
* {@code exclude} list drops items from every engine's corpus by their own id (a page's slug, a source item's id);
* {@code snippetLength} bounds the highlighted excerpt; {@code enabled}, {@code resultLimit}, {@code resultsPath},
* {@code placeholder} and {@code highlight} shape the public surface.
*/
final class SearchSiteConfig {
static final boolean ENABLED_DEFAULT = true;
static final boolean HIGHLIGHT_DEFAULT = true;
static final int RESULT_LIMIT_DEFAULT = 20;
static final String RESULTS_PATH_DEFAULT = "/search";
static final int SNIPPET_MIN = 40;
static final int SNIPPET_MAX = 400;
static final int SNIPPET_DEFAULT = 160;
static final int TITLE_WEIGHT_DEFAULT = 8;
static final int DESCRIPTION_WEIGHT_DEFAULT = 4;
static final int BODY_WEIGHT_DEFAULT = 1;
static final int ALL_TERMS_BONUS_DEFAULT = 1000;
static final int PHRASE_TITLE_BONUS_DEFAULT = 400;
static final int PHRASE_BODY_BONUS_DEFAULT = 300;
private final SettingsView view;
private SearchSiteConfig(SettingsView view) {
this.view = (view == null) ? SettingsView.empty() : view;
}
static SearchSiteConfig of(SettingsView view) {
return new SearchSiteConfig(view);
}
/** Whether search serves this site at all (the box and the JSON API); default on. */
boolean enabled() {
return view.bool("enabled", ENABLED_DEFAULT);
}
/**
* Whether a result link carries the matched words, so the page it opens highlights them (since 2.1.0; default
* on). Off: plain links, and the highlighter is not added to the site's pages.
*/
boolean highlight() {
return view.bool("highlight", HIGHLIGHT_DEFAULT);
}
/** The most hits a query returns, clamped to {@code 1..100} (default 20). */
int resultLimit() {
return (int) view.integer("resultLimit", RESULT_LIMIT_DEFAULT, 1, 100);
}
/** Where the box submits {@code ?q=} to: the results page (default {@code /search}). */
String resultsPath() {
return view.string("resultsPath", RESULTS_PATH_DEFAULT).strip();
}
/** The box's placeholder, or {@code fallback} (the localized default text) when the site set none. */
String placeholder(String fallback) {
String value = view.string("placeholder", "").strip();
return value.isEmpty() ? fallback : value;
}
/** Weight added when a query term appears in the title (default 8; title matches dominate). */
int titleWeight() {
return weight("titleWeight", TITLE_WEIGHT_DEFAULT, 1_000_000);
}
/** Weight added when a query term appears in the description (default 4). */
int descriptionWeight() {
return weight("descriptionWeight", DESCRIPTION_WEIGHT_DEFAULT, 1_000_000);
}
/** Weight added <em>per body occurrence</em> of a term, occurrences capped by the engine (default 1). */
int bodyWeight() {
return weight("bodyWeight", BODY_WEIGHT_DEFAULT, 1_000_000);
}
/** Flat bonus when the page contains <em>all</em> query terms across its fields (default 1000). */
int allTermsBonus() {
return weight("allTermsBonus", ALL_TERMS_BONUS_DEFAULT, 1_000_000_000);
}
/** Flat bonus when the title contains the whole query as a phrase (default 400). */
int phraseTitleBonus() {
return weight("phraseTitleBonus", PHRASE_TITLE_BONUS_DEFAULT, 1_000_000_000);
}
/** Flat bonus when the body contains the whole query as a phrase (default 300). */
int phraseBodyBonus() {
return weight("phraseBodyBonus", PHRASE_BODY_BONUS_DEFAULT, 1_000_000_000);
}
/** Characters of context per result snippet, clamped to [{@value #SNIPPET_MIN}, {@value #SNIPPET_MAX}]. */
int snippetLength() {
return (int) view.integer("snippetLength", SNIPPET_DEFAULT, SNIPPET_MIN, SNIPPET_MAX);
}
/**
* The lowercase, trimmed, distinct ids to keep out of the search corpus (never {@code null}): a page's slug or a
* content-source item's id. A YAML list or a comma/newline-separated string; a leading {@code /} and surrounding
* blanks are tolerated, so an operator can paste either {@code legal/privacy} or {@code /legal/privacy}.
*/
List<String> excludedIds() {
return view.list("exclude").stream()
.map(String::strip)
.map(s -> s.startsWith("/") ? s.substring(1) : s)
.map(s -> s.toLowerCase(Locale.ROOT))
.filter(s -> !s.isEmpty())
.distinct()
.toList();
}
private int weight(String key, int fallback, int max) {
return (int) view.integer(key, fallback, 0, max);
}
}
@@ -0,0 +1,50 @@
package mx.quest.search;
import java.util.Objects;
import mx.quest.runway.spi.model.CatalogChange;
import mx.quest.runway.spi.model.SiteLifecycleEvent;
import mx.quest.runway.spi.service.SiteEventListener;
/**
* The plugin's one {@link SiteEventListener} (a {@link Phase#CONSUMER CONSUMER}: it reads the content listing, it
* contributes none). The kernel delivers it after every kernel cache the change affects has been evicted, and after
* every content source has dropped its own state, so what it triggers rebuilds from the new state.
*
* <ul>
* <li>{@link #onCatalogChanged} — <b>every</b> cause drops the built-in engine's index for the site: a page
* write, a content source's change, a site lifecycle event, and any plugin's settings save (a source reshapes
* its items from its settings, and this plugin's own {@code exclude} list reshapes the corpus). The callback
* only evicts; the rebuild happens lazily on the next query.</li>
* <li>{@link #onSiteLifecycle} — a <b>wholesale</b> event (the site was restored from a backup, or deleted) makes
* {@link NoResultsLog} forget its in-memory list unwritten, so the restored file is what is read next and a
* deleted site's list is never written back.</li>
* </ul>
* Both run on every node, for local and replayed changes alike: they only drop local state.
*/
public class SearchSiteEvents implements SiteEventListener {
private final SimpleSearchEngine engine;
private final NoResultsLog noResults;
public SearchSiteEvents(SimpleSearchEngine engine, NoResultsLog noResults) {
this.engine = Objects.requireNonNull(engine, "engine");
this.noResults = Objects.requireNonNull(noResults, "noResults");
}
@Override
public Phase phase() {
return Phase.CONSUMER;
}
@Override
public void onSiteLifecycle(SiteLifecycleEvent event) {
if (event.wholesale()) {
noResults.forget(event.siteId());
}
}
@Override
public void onCatalogChanged(CatalogChange change) {
engine.invalidate(change.siteId());
}
}
@@ -0,0 +1,140 @@
package mx.quest.search;
import java.util.List;
import java.util.Locale;
/**
* Builds a hit's snippet honouring the {@link mx.quest.search.spi.SearchHit} safety contract: a short excerpt of
* the source text, <b>HTML-escaped in full</b>, with the matched query terms — and only those — wrapped in raw
* {@code <mark>…</mark>}. The surface can then render the result as raw HTML: the highlight shows as emphasis
* while every character that came from the page is inert, so a crafted title or body can never inject markup.
*
* <h2>Why escape-then-mark, in that order</h2>
* The naive "wrap hits in {@code <mark>} then escape" would escape the {@code <mark>} tags too (defeating the
* highlight), and "escape then search for the term" would miss hits whose characters were rewritten by escaping.
* So the builder locates hits on the <em>raw</em> text, escapes each non-hit gap and each hit's text
* independently, and emits a literal {@code <mark>}/{@code </mark>} only around the already-escaped hit text.
* The result contains no unescaped source character — the sole raw markup is the {@code <mark>} pair.
*
* <p>Matching is case-insensitive and works on whole query terms (the same terms the engine scored on). The
* excerpt is <b>windowed</b> around the first hit — a slice of at most {@code length} characters starting a
* little before the earliest match — so the snippet shows the term in context rather than always the document's
* opening. When no term is present (e.g. the hit matched only in the title) it falls back to a leading slice with
* no highlight, still fully escaped.
*/
final class SearchSnippet {
/** How far before the first hit the window may start, so the matched term isn't flush against the left edge. */
private static final int LEAD_IN = 30;
private SearchSnippet() {
}
/**
* A safe, highlighted snippet of {@code text} for the lowercase {@code terms}, at most {@code length}
* characters of source (before escaping) wide.
*
* @param text the raw source text (typically the page body or description); may be blank
* @param terms the lowercase query terms to highlight (already tokenized by the engine)
* @param length the maximum number of source characters to include (clamped to a sane minimum)
* @return escaped HTML with {@code <mark>} around hits; empty string for blank input
*/
static String build(String text, List<String> terms, int length) {
if (text == null || text.isBlank()) {
return "";
}
String source = text.strip();
int window = Math.max(20, length);
String lower = source.toLowerCase(Locale.ROOT);
int firstHit = earliestHit(lower, terms);
int start = firstHit < 0 ? 0 : Math.max(0, firstHit - LEAD_IN);
// Nudge the window start off a mid-word position so it doesn't begin with a fragment of a word.
while (start > 0 && Character.isLetterOrDigit(source.charAt(start - 1)) && start > firstHit - LEAD_IN - 12) {
start--;
if (!Character.isLetterOrDigit(source.charAt(start))) {
break;
}
}
int end = Math.min(source.length(), start + window);
String slice = source.substring(start, end);
StringBuilder out = new StringBuilder(slice.length() + 32);
if (start > 0) {
out.append("…");
}
out.append(highlight(slice, terms));
if (end < source.length()) {
out.append("…");
}
return out.toString();
}
/** The earliest index in {@code lower} at which any of {@code terms} occurs, or {@code -1} if none do. */
private static int earliestHit(String lower, List<String> terms) {
int best = -1;
for (String term : terms) {
if (term.isEmpty()) {
continue;
}
int i = lower.indexOf(term);
if (i >= 0 && (best < 0 || i < best)) {
best = i;
}
}
return best;
}
/**
* Escapes {@code slice} and wraps each occurrence of any term in {@code <mark>}. Walks the slice left to
* right, at each position taking the longest term that matches there; the gap before a match and the match
* text are escaped separately, and only the literal {@code <mark>}/{@code </mark>} tags are emitted raw.
*/
private static String highlight(String slice, List<String> terms) {
String lower = slice.toLowerCase(Locale.ROOT);
StringBuilder out = new StringBuilder(slice.length() + 16);
int i = 0;
while (i < slice.length()) {
int matchLen = longestTermAt(lower, i, terms);
if (matchLen == 0) {
out.append(escape(slice.charAt(i)));
i++;
} else {
out.append("<mark>").append(escape(slice.substring(i, i + matchLen))).append("</mark>");
i += matchLen;
}
}
return out.toString();
}
/** The length of the longest term that occurs in {@code lower} starting exactly at {@code pos}, else 0. */
private static int longestTermAt(String lower, int pos, List<String> terms) {
int best = 0;
for (String term : terms) {
int len = term.length();
if (len > best && lower.startsWith(term, pos)) {
best = len;
}
}
return best;
}
private static String escape(char c) {
return switch (c) {
case '&' -> "&amp;";
case '<' -> "&lt;";
case '>' -> "&gt;";
case '"' -> "&quot;";
case '\'' -> "&#39;";
default -> String.valueOf(c);
};
}
private static String escape(String s) {
StringBuilder b = new StringBuilder(s.length() + 8);
for (int i = 0; i < s.length(); i++) {
b.append(escape(s.charAt(i)));
}
return b.toString();
}
}
@@ -0,0 +1,373 @@
package mx.quest.search;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import mx.quest.runway.spi.model.CatalogEntry;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.spi.service.Sites;
import mx.quest.search.spi.SearchCorpus;
import mx.quest.search.spi.SearchHit;
import mx.quest.search.spi.SearchQuery;
import mx.quest.search.spi.SiteSearchEngine;
/**
* The built-in {@link SiteSearchEngine}: a dependency-free full-text matcher that indexes each site's whole
* {@link SearchCorpus} — published pages AND content-source items (the entries plugins publish, …), minus the site's search
* exclusions — by localized <b>title, description AND body</b>. It reads each entry's indexable material through the
* corpus, reduces it to plain text with {@link HtmlText}, and holds a small per-site index of {@link SearchDocument}s.
* The index is dropped the moment anything that may reshape the corpus changes ({@link #invalidate}, called by the
* plugin's {@code SiteEventListener} for every page write, content change, site lifecycle event and plugin settings
* save) and additionally refreshed by a freshness TTL. It needs no external index and is always available, so
* search works the moment the plugin is installed — a richer engine (e.g. {@code search-lucene}) transparently
* supersedes it by declaring a higher {@link #priority()}.
*
* <h2>Scoring</h2>
* Score is a configurable weighted term-frequency (per-site {@link SearchSiteConfig}): a term in the title is
* worth {@link SearchSiteConfig#titleWeight()}, in the description {@link SearchSiteConfig#descriptionWeight()},
* and per body occurrence {@link SearchSiteConfig#bodyWeight()} (body counts are capped so one keyword-stuffed
* page can't dominate). Flat bonuses reward a page that contains <em>all</em> query terms
* ({@link SearchSiteConfig#allTermsBonus()}) and one that contains the whole query as a phrase in the title or
* body. The weights are data, so a site tunes ranking with no code change.
*
* <h2>One document per item and language, and its URL</h2>
* Since 2.2.0 each corpus entry becomes one document <b>per language the item exists in</b>: its title, description
* and body in that language (the body is the page as rendered there, bundle strings included), linked at
* {@link CatalogEntry#pathFor} that language. A query searches the documents of its own language
* ({@link SearchQuery#locale()}, the results page's language) plus, for an item that does not exist in that
* language, the item's <b>primary-locale</b> document (the site's default language when the item exists in it, else
* its first language) — so a visitor on {@code /es/…} gets Spanish titles, snippets and links, and still finds a page
* the site publishes in English only. A query in a language the site does not speak searches the site default's
* documents. Before 2.2.0 only the primary-locale document existed, so every language searched default-language
* text.
*
* <h2>Snippets, isolation</h2>
* Snippets are built by {@link SearchSnippet} from the body (falling back to the description) and honour the frozen
* {@link SearchHit} snippet contract: escape everything, wrap only the matched terms in {@code <mark>}. Each hit also
* carries the whole words its terms matched ({@link MatchedWords}), which the target page highlights. Every read
* is scoped to {@code query.siteId()} — the index is keyed per site, so one tenant never sees another's content.
*/
public class SimpleSearchEngine implements SiteSearchEngine {
static final String KEY = "search/simple";
/** Bounds the per-body term count so one keyword-stuffed page can't swamp a genuinely relevant one. */
private static final int MAX_BODY_HITS_PER_TERM = 20;
/** Distinct site indexes held at once (least recently used dropped first); each is small. */
static final int MAX_SITE_INDEXES = 512;
private final SearchCorpus corpus;
private final Sites sites;
private final PluginSettings settings;
private final SearchProperties properties;
/**
* Per-site index cache, least recently used first. An entry is dropped by {@link #invalidate} and rebuilt lazily
* on the next query; the freshness TTL ({@link SearchProperties#getRefreshMinutes()}) remains as the backstop for
* changes no event announces (a file edited by hand), and {@link #reindex} drops + rebuilds eagerly.
*/
private final Map<String, SiteIndex> indexes = Collections.synchronizedMap(
new LinkedHashMap<>(16, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<String, SiteIndex> eldest) {
return size() > MAX_SITE_INDEXES;
}
});
/**
* Bumped by every {@link #invalidate}. A build started before an invalidation may have read the old corpus, so
* it is served to its own caller but not cached: the next query rebuilds from the new state.
*/
private final AtomicLong generation = new AtomicLong();
/** One build at a time per site: concurrent first queries after a change wait for one build, not start N. */
private final Map<String, Object> locks = new java.util.concurrent.ConcurrentHashMap<>();
/**
* The sites whose index this thread is building. A build renders pages (kernel 1.0.0-rc6), and a page's widget
* that searched the same site would re-enter the build and recurse; such a search answers nothing instead.
*/
private static final ThreadLocal<Set<String>> BUILDING = ThreadLocal.withInitial(java.util.HashSet::new);
public SimpleSearchEngine(SearchCorpus corpus, Sites sites, PluginSettings settings,
SearchProperties properties) {
this.corpus = Objects.requireNonNull(corpus, "corpus");
this.sites = Objects.requireNonNull(sites, "sites");
this.settings = Objects.requireNonNull(settings, "settings");
this.properties = Objects.requireNonNull(properties, "properties");
}
@Override
public String key() {
return KEY;
}
@Override
public List<SearchHit> search(SearchQuery query) {
List<String> terms = terms(query.text());
if (terms.isEmpty() || BUILDING.get().contains(query.siteId())) {
return List.of();
}
SearchSiteConfig cfg = SearchSiteConfig.of(settings.site(query.siteId()));
SiteIndex index = index(query.siteId());
List<SearchDocument> documents = index.documents(query.locale());
String phrase = query.text().toLowerCase(Locale.ROOT).strip();
List<Scored> scored = new ArrayList<>();
for (SearchDocument doc : documents) {
double score = score(doc, terms, phrase, cfg);
if (score > 0) {
scored.add(new Scored(doc, score));
}
}
scored.sort(Comparator.comparingDouble(Scored::score).reversed()
.thenComparing(s -> s.doc().title(), String.CASE_INSENSITIVE_ORDER));
// The snippet and the matched words are built for the hits returned only, not for every document scored.
List<SearchHit> hits = new ArrayList<>(Math.min(scored.size(), query.limit()));
for (Scored s : scored.subList(0, Math.min(scored.size(), query.limit()))) {
SearchDocument doc = s.doc();
hits.add(new SearchHit(doc.url(), doc.title(), snippet(doc, terms, cfg), s.score(),
MatchedWords.in(doc, terms)));
}
return List.copyOf(hits);
}
/** A document and its score, before the cut to the query's limit. */
private record Scored(SearchDocument doc, double score) {
}
/**
* Drops the cached index for {@code siteId} and rebuilds it from current content — the SPI's manual reindex
* hook. It also refreshes the kernel's listing first ({@link SearchCorpus#refresh}): the button exists for
* changes no event announced (files edited by hand), and those never evicted the listing either. Returns the
* number of items in the freshly built index (not per-language documents), so the caller can report the new size.
*/
@Override
public int reindex(String siteId) {
corpus.refresh(siteId);
invalidate(siteId);
return index(siteId).items();
}
/**
* Drops the site's cached index, so the next query rebuilds it from the current corpus. Called from the
* plugin's {@code SiteEventListener} for every change that may reshape the corpus, after the kernel has evicted
* its own caches — so the rebuild reads the new state.
*/
void invalidate(String siteId) {
generation.incrementAndGet();
indexes.remove(siteId);
}
/**
* The number of items (published, non-excluded pages and content) the built-in engine searches for a site —
* items, not per-language documents, so the count does not grow with the number of languages.
*/
public int documentCount(String siteId) {
return index(siteId).items();
}
// --- scoring -----------------------------------------------------------------------------------
private static double score(SearchDocument doc, List<String> terms, String phrase, SearchSiteConfig cfg) {
double score = 0;
int termsPresent = 0;
for (String term : terms) {
boolean inTitle = doc.normTitle().contains(term);
boolean inDescription = doc.normDescription().contains(term);
int bodyHits = Math.min(MAX_BODY_HITS_PER_TERM, count(doc.normBody(), term));
if (inTitle) {
score += cfg.titleWeight();
}
if (inDescription) {
score += cfg.descriptionWeight();
}
score += (double) cfg.bodyWeight() * bodyHits;
if (inTitle || inDescription || bodyHits > 0) {
termsPresent++;
}
}
if (score <= 0) {
return 0;
}
if (termsPresent == terms.size() && terms.size() > 1) {
score += cfg.allTermsBonus();
}
if (!phrase.isBlank()) {
if (doc.normTitle().contains(phrase)) {
score += cfg.phraseTitleBonus();
}
if (doc.normBody().contains(phrase)) {
score += cfg.phraseBodyBonus();
}
}
return score;
}
private static int count(String haystack, String needle) {
if (needle.isEmpty()) {
return 0;
}
int n = 0;
for (int i = haystack.indexOf(needle); i >= 0; i = haystack.indexOf(needle, i + needle.length())) {
n++;
}
return n;
}
private static List<String> terms(String text) {
return List.of(text.toLowerCase(Locale.ROOT).trim().split("\\s+")).stream()
.filter(s -> !s.isBlank()).distinct().toList();
}
/**
* The highlighted snippet for a hit: built from the body when the body contains a term, else from the
* description (which is where a metadata-only match's context lives), honouring the frozen snippet contract
* via {@link SearchSnippet}.
*/
private static String snippet(SearchDocument doc, List<String> terms, SearchSiteConfig cfg) {
boolean bodyHasTerm = terms.stream().anyMatch(t -> doc.normBody().contains(t));
String source = bodyHasTerm || doc.description().isBlank() ? doc.body() : doc.description();
if (source.isBlank()) {
source = doc.description().isBlank() ? doc.body() : doc.description();
}
return SearchSnippet.build(source, terms, cfg.snippetLength());
}
// --- index -------------------------------------------------------------------------------------
/** The site's index, rebuilt if absent or stale (older than the configured freshness TTL). */
private SiteIndex index(String siteId) {
SiteIndex cached = indexes.get(siteId);
if (cached != null && !cached.isStale(properties.freshnessMillis())) {
return cached;
}
synchronized (locks.computeIfAbsent(siteId, k -> new Object())) {
cached = indexes.get(siteId);
if (cached != null && !cached.isStale(properties.freshnessMillis())) {
return cached; // built by the query this one waited for
}
long before = generation.get();
SiteIndex fresh;
BUILDING.get().add(siteId);
try {
fresh = build(siteId);
} finally {
BUILDING.get().remove(siteId);
}
synchronized (indexes) {
if (generation.get() == before) {
indexes.put(siteId, fresh);
}
}
return fresh;
}
}
/**
* Builds the per-site index over the {@link SearchCorpus} — every published, non-excluded item, pages and
* content-source items alike — one {@link SearchDocument} per item and language it exists in, then one view per
* language (see the class comment). An unknown site has an empty index.
*/
private SiteIndex build(String siteId) {
SiteView site = sites.find(siteId).orElse(null);
if (site == null) {
return new SiteIndex(Map.of(), "", 0, System.currentTimeMillis());
}
Locale siteDefault = site.defaultLocale();
Map<String, List<SearchDocument>> own = new LinkedHashMap<>();
List<Item> items = new ArrayList<>();
for (CatalogEntry entry : corpus.corpus(siteId)) {
Locale primary = entry.ref().primaryLocale(siteDefault);
Set<String> languages = new LinkedHashSet<>();
SearchDocument primaryDoc = null;
for (Locale locale : itemLocales(entry, siteDefault)) {
if (!languages.add(locale.getLanguage())) {
continue;
}
SearchDocument doc = document(siteId, entry, locale);
own.computeIfAbsent(locale.getLanguage(), k -> new ArrayList<>()).add(doc);
if (locale.getLanguage().equals(primary.getLanguage())) {
primaryDoc = doc;
}
}
if (primaryDoc == null) {
primaryDoc = document(siteId, entry, primary);
}
items.add(new Item(primaryDoc, Set.copyOf(languages)));
}
Set<String> viewLanguages = new LinkedHashSet<>();
viewLanguages.add(siteDefault.getLanguage());
site.locales().forEach(l -> viewLanguages.add(l.getLanguage()));
viewLanguages.addAll(own.keySet());
Map<String, List<SearchDocument>> views = new HashMap<>();
for (String language : viewLanguages) {
List<SearchDocument> view = new ArrayList<>(own.getOrDefault(language, List.of()));
for (Item item : items) {
if (!item.languages().contains(language)) {
view.add(item.primary());
}
}
views.put(language, List.copyOf(view));
}
return new SiteIndex(Map.copyOf(views), siteDefault.getLanguage(), items.size(), System.currentTimeMillis());
}
/** The languages an item exists in, in its declared order; an empty list means the site default only. */
private static List<Locale> itemLocales(CatalogEntry entry, Locale siteDefault) {
List<Locale> locales = entry.ref().locales();
return locales.isEmpty() ? List.of(siteDefault) : locales;
}
/** The item's document in {@code locale}: title, description and body in that language, at its address there. */
private SearchDocument document(String siteId, CatalogEntry entry, Locale locale) {
String title = localized(entry.ref().title(), locale, entry.ref().id());
String description = localized(entry.ref().description(), locale, "");
// Raw indexable material (empty when a source doesn't offer it, or fails) — stripped of markup here.
String body = HtmlText.toText(corpus.indexableText(siteId, entry, locale));
return SearchDocument.of(entry.compositeId(), entry.pathFor(locale), title, description, body);
}
/** An item's primary-locale document and the languages it has documents in, while a view is assembled. */
private record Item(SearchDocument primary, Set<String> languages) {
}
/** A map value for {@code locale}'s language, else any present value, else {@code fallback}. */
private static String localized(Map<String, String> byLocale, Locale locale, String fallback) {
String v = byLocale.get(locale.getLanguage());
if (v == null || v.isBlank()) {
v = byLocale.values().stream().filter(x -> x != null && !x.isBlank()).findFirst().orElse(null);
}
return (v == null || v.isBlank()) ? fallback : v;
}
/**
* One site's built index: the documents each language searches (its own plus the primary-locale documents of
* items it lacks), the site default's language, the number of items, and the wall-clock time it was built (for
* the freshness TTL).
*/
private record SiteIndex(Map<String, List<SearchDocument>> views, String defaultLanguage, int items,
long builtAtMillis) {
/** The documents a query in {@code locale} searches; the site default's when the site lacks that language. */
List<SearchDocument> documents(Locale locale) {
List<SearchDocument> view = views.get(locale.getLanguage());
return view != null ? view : views.getOrDefault(defaultLanguage, List.of());
}
boolean isStale(long freshnessMillis) {
return System.currentTimeMillis() - builtAtMillis >= freshnessMillis;
}
}
}
@@ -0,0 +1,93 @@
package mx.quest.search;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import mx.quest.runway.spi.model.CatalogEntry;
import mx.quest.runway.spi.model.LocalizedUrl;
import mx.quest.runway.spi.service.ContentCatalogView;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.search.spi.SearchCorpus;
/**
* The search plugin's {@link SearchCorpus}: the kernel's {@link ContentCatalogView} filtered by this plugin's own
* per-site {@code exclude} setting (read through {@link PluginSettings}, bound to this plugin), and without the
* site's <b>results page</b> (since 2.1.1): the page at the {@code resultsPath} setting carries the search box and
* describes search, so it matched queries about the site's own subjects and was listed among its own results.
* It caches nothing —
* the kernel caches the listing and the settings view — so a settings save or a content change is visible on the
* very next call.
*/
public class SiteSearchCorpus implements SearchCorpus {
private final ContentCatalogView catalog;
private final PluginSettings settings;
public SiteSearchCorpus(ContentCatalogView catalog, PluginSettings settings) {
this.catalog = Objects.requireNonNull(catalog, "catalog");
this.settings = Objects.requireNonNull(settings, "settings");
}
@Override
public List<CatalogEntry> corpus(String siteId) {
List<CatalogEntry> entries = catalog.entries(siteId);
Exclusions excluded = excluded(siteId);
return entries.stream().filter(entry -> !excluded.matches(entry)).toList();
}
@Override
public String indexableText(String siteId, CatalogEntry entry, Locale locale) {
Objects.requireNonNull(entry, "entry");
Objects.requireNonNull(locale, "locale");
if (excluded(siteId).matches(entry)) {
return "";
}
return catalog.indexableText(siteId, entry, locale);
}
@Override
public void refresh(String siteId) {
catalog.refresh(siteId);
}
private Exclusions excluded(String siteId) {
SearchSiteConfig cfg = SearchSiteConfig.of(settings.site(siteId));
return new Exclusions(Set.copyOf(cfg.excludedIds()), normalizePath(cfg.resultsPath()));
}
/** Lowercase, leading {@code /}, no trailing {@code /} (except the root itself). */
static String normalizePath(String path) {
String p = path == null ? "" : path.strip().toLowerCase(Locale.ROOT);
if (!p.startsWith("/")) {
p = "/" + p;
}
while (p.length() > 1 && p.endsWith("/")) {
p = p.substring(0, p.length() - 1);
}
return p;
}
/**
* What a site leaves out: the {@code exclude} ids, and the page at {@code resultsPath} in any of its languages
* (a page whose address in some locale is the results path is the results page; its other localized addresses
* go with it). A results path of {@code /} never excludes the home page.
*/
private record Exclusions(Set<String> ids, String resultsPath) {
boolean matches(CatalogEntry entry) {
if (ids.contains(entry.ref().id().toLowerCase(Locale.ROOT))) {
return true;
}
if (!entry.isPage() || "/".equals(resultsPath)) {
return false;
}
for (LocalizedUrl url : entry.urls()) {
if (resultsPath.equals(normalizePath(url.path()))) {
return true;
}
}
return false;
}
}
}
@@ -0,0 +1,72 @@
package mx.quest.search.spi;
import java.util.List;
import java.util.Locale;
import mx.quest.runway.spi.model.CatalogEntry;
/**
* What a site's search index is built from — the search plugin's <b>own</b> published service (plugin-to-plugin,
* since search 2.0.0). It is the kernel's content surface ({@code ContentCatalogView}: every published page and
* content-source item, with host-computed URLs) <b>minus the site's search exclusions</b> (the per-site
* {@code exclude} setting of the {@code search} plugin). Every {@link SiteSearchEngine} builds from it — the
* built-in one and a contributed one such as {@code search-lucene} — so the exclusion rule is applied in exactly one
* place and no engine reads the search plugin's settings itself.
*
* <h2>How to get it</h2>
* The search plugin registers one bean of this type ({@code searchCorpus}). A companion plugin that declares
* {@code requires: "search >= 2.0.0"} receives it by ordinary Spring injection, by type.
*
* <h2>The exclusion rule</h2>
* An entry is left out when its own id ({@code entry.ref().id()}: a page's slug, a content-source item's id — never
* the composite {@code source:id} form) equals, ignoring case, one of the site's {@code exclude} values; a leading
* {@code /} and surrounding blanks on a value are ignored, so an operator may type {@code legal/privacy} or
* {@code /legal/privacy}.
*
* <h2>Freshness</h2>
* Nothing here is cached by the search plugin: every call reads the kernel's listing (cached per site by the kernel,
* evicted by every change that can reshape it) and the search plugin's current settings. A consumer that keeps an
* index of its own drops it from a {@code SiteEventListener.onCatalogChanged} callback: every cause is relevant,
* because a page write, a content change, a site lifecycle event and <b>any</b> plugin's settings save — the search
* plugin's {@code exclude} list included — can reshape this corpus.
*
* <h2>Rules</h2>
* Every method takes a site id; an unsafe id throws {@link IllegalArgumentException}, a well-formed id of an unknown
* site answers empty or {@code ""}. Thread-safe; no method returns {@code null}.
*
* <h2>Evolution</h2>
* Like {@link SiteSearchEngine}, this interface is binary API: it grows by {@code default} methods only.
*
* @since search 2.0.0
*/
public interface SearchCorpus {
/**
* The site's searchable entries: every published page and content-source item of the kernel's listing, in the
* listing's order, except the excluded ones.
*
* @param siteId the site
* @return the entries (never {@code null}; unmodifiable; empty for an unknown site)
*/
List<CatalogEntry> corpus(String siteId);
/**
* The entry's indexable material in {@code locale} — the text an engine folds in beyond the title and
* description, as HTML or plain text (strip markup before indexing). {@code ""} for an excluded entry, for a
* source that does not offer indexable text, for an unknown site, and when the source fails.
*
* @param siteId the site
* @param entry an entry from {@link #corpus} of the same site
* @param locale the locale to index
* @return the material, or {@code ""} (never {@code null})
*/
String indexableText(String siteId, CatalogEntry entry, Locale locale);
/**
* Drops the kernel's cached listing of the site, so the next {@link #corpus} re-reads every content source (the
* exclusion list is never cached, so it is always current). For the operator's manual reindex of changes no
* event announced (a file edited by hand); ordinary writes do not need it.
*
* @param siteId the site
*/
void refresh(String siteId);
}
@@ -0,0 +1,81 @@
package mx.quest.search.spi;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
/**
* One ranked result from a {@link SiteSearchEngine}: the absolute (or site-relative) URL to link to, the title
* to show, a short {@link #snippet() snippet} of context, and a score used only for ordering (higher = better).
*
* <h2>The {@code snippet} safety contract (frozen semantics — read before rendering)</h2>
* The snippet is <b>pre-escaped, highlight-bearing HTML</b>, NOT plain text: every character that comes from the
* page's own content ({@code < > & " '}) is already HTML-escaped by the engine, and the <b>only</b> raw markup
* an engine may leave in it is the pair {@code <mark>…</mark>} wrapping the matched query terms. Both shipped
* engines honour this: the built-in engine and {@code search-lucene} each escape the source passage first and
* only then splice in {@code <mark>} around the hits. The consequence is that the search surface (the results
* page and the search-box widget) MUST render the snippet as <b>raw HTML</b> (Thymeleaf {@code th:utext} or a
* direct string append), so the highlight shows as emphasis rather than literal {@code &lt;mark&gt;} text. This
* is XSS-safe precisely because the escaping happened at the engine and nothing but {@code <mark>} survives it —
* a crafted page title or body cannot forge a tag. An engine that produces no highlight simply returns the
* escaped passage with no {@code <mark>}; an empty snippet is allowed. A NEW engine implementing this SPI is
* bound by the same contract: escape everything, wrap only hits in {@code <mark>}.
*
*
* <h2>The {@code terms} component (since 2.1.0)</h2>
* The words the engine actually matched in this item, as they are written there: for a stemming engine the
* surface forms (the query {@code maestría} finding {@code maestrías}), for the built-in engine the whole words
* that contain a query term. The search surface hands them to the target page, which highlights them, so they
* are plain text, never markup: the surface escapes them like any other value. Lowercase, distinct, at most
* {@value #MAX_TERMS} of at most {@value #MAX_TERM_LENGTH} characters each; blank entries are dropped. An engine
* built before 2.1.0 calls the four-argument constructor and its hits carry no terms, which only means the target
* page highlights nothing.
*
* @param url the link target for the hit (the search surface renders it as an {@code <a href>})
* @param title the hit's display title (the surface escapes it before rendering)
* @param snippet a short, HTML-escaped, {@code <mark>}-highlighted excerpt (may be empty); the surface renders
* it as raw HTML per the safety contract above — do NOT re-escape it
* @param score the relevance score, used to sort hits best-first; not shown to the user
* @param terms the matched words as written in the item (never {@code null}; may be empty), see above
*/
public record SearchHit(String url, String title, String snippet, double score, List<String> terms) {
/** The most matched words a hit carries; more would only lengthen the link. */
public static final int MAX_TERMS = 20;
/** The longest matched word kept; a longer "word" is a token such as a hash, not something to highlight. */
public static final int MAX_TERM_LENGTH = 64;
public SearchHit {
Objects.requireNonNull(url, "url");
title = (title == null) ? "" : title;
snippet = (snippet == null) ? "" : snippet;
terms = normalize(terms);
}
/** The 2.0.0 form, before {@link #terms()}: a hit with no matched words. (Kept so older engines still link.) */
public SearchHit(String url, String title, String snippet, double score) {
this(url, title, snippet, score, List.of());
}
private static List<String> normalize(List<String> raw) {
if (raw == null || raw.isEmpty()) {
return List.of();
}
LinkedHashSet<String> kept = new LinkedHashSet<>();
for (String term : raw) {
if (term == null) {
continue;
}
String t = term.strip().toLowerCase(Locale.ROOT);
if (!t.isEmpty() && t.length() <= MAX_TERM_LENGTH) {
kept.add(t);
if (kept.size() == MAX_TERMS) {
break;
}
}
}
return List.copyOf(kept);
}
}
@@ -0,0 +1,23 @@
package mx.quest.search.spi;
import java.util.Locale;
import java.util.Objects;
/**
* An immutable search request handed to a {@link SiteSearchEngine}: the bound site, the raw query text, the
* request locale (so a locale-aware engine can prefer that language), and the maximum number of hits to return.
*
* @param siteId the bound tenancy the search is scoped to (never cross-site)
* @param text the user's query, trimmed and non-blank (the surface rejects blanks before calling an engine)
* @param locale the request locale
* @param limit the maximum number of hits to return (always {@code >= 1})
*/
public record SearchQuery(String siteId, String text, Locale locale, int limit) {
public SearchQuery {
Objects.requireNonNull(siteId, "siteId");
Objects.requireNonNull(text, "text");
locale = (locale == null) ? Locale.ENGLISH : locale;
limit = Math.max(1, limit);
}
}
@@ -0,0 +1,61 @@
package mx.quest.search.spi;
import java.util.List;
/**
* The search plugin's <b>own</b> extension point (a plugin-to-plugin SPI): a pluggable full-text engine that
* answers a {@link SearchQuery} for one site with a ranked list of {@link SearchHit}s. The {@code search} plugin
* ships a built-in substring engine over the site's page metadata; a companion plugin (e.g. {@code search-lucene})
* declares {@code requires: search} and contributes a richer implementation as an ordinary bean.
*
* <p>The search plugin collects every {@code SiteSearchEngine} bean and, per request, uses the <b>available</b>
* one with the highest {@link #priority()} — so installing a better engine transparently upgrades search with no
* change to the query surface (the search box widget and the {@code /search} results endpoint).
*
* <p>Contract: an implementation is a pure query function over the site's searchable content — the
* {@link SearchCorpus} the search plugin publishes (since 2.0.0), which already applies the site's exclusions. It
* never mutates the query, never throws for a normal "no results" (return an empty list), and returns at most
* {@link SearchQuery#limit()} hits already sorted best-first.
*
* <p>This interface, {@link SearchQuery} and {@link SearchHit} are unchanged in search 2.0.0: an engine compiled
* against search 1.x links and behaves the same.
*/
public interface SiteSearchEngine {
/** A stable, unique, namespaced key for this engine (e.g. {@code "search/simple"}), for logs and the console. */
String key();
/** The ranked hits for {@code query} (best first, at most {@link SearchQuery#limit()}); empty ⇒ no matches. */
List<SearchHit> search(SearchQuery query);
/**
* Selection weight — the search surface picks the highest-priority <em>available</em> engine. The built-in
* engine is {@code 0}; a contributed engine returns a higher value to take over.
*/
default int priority() {
return 0;
}
/**
* Whether this engine can serve {@code siteId} right now (e.g. an index exists). When it can't, the search
* surface falls back to the next-highest engine — so a not-yet-built index never breaks search.
*/
default boolean available(String siteId) {
return true;
}
/**
* Rebuilds this engine's derived state for {@code siteId} from current content <b>now</b> — the operator's
* manual reindex action — and returns the number of documents the fresh index holds. An engine that caches
* or persists an index drops it and rebuilds eagerly (not lazily on the next query), so the confirmation the
* operator sees reflects a completed rebuild; a rebuild failure must not throw (log and return {@code 0},
* the same never-throw posture as {@link #search}). The default is a no-op returning {@code 0}, for an
* engine that derives nothing and so has nothing to drop.
*
* <p>Added in search 1.2.0 as a {@code default} method — the SPI's binary-compatibility rule: an engine
* compiled against an earlier SPI keeps loading unchanged and simply inherits the no-op.
*/
default int reindex(String siteId) {
return 0;
}
}
@@ -0,0 +1,114 @@
package mx.quest.search;
import java.time.Instant;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import mx.quest.runway.spi.model.CatalogEntry;
import mx.quest.runway.spi.model.ContentRef;
import mx.quest.runway.spi.model.FileEntry;
import mx.quest.runway.spi.model.LocalizedUrl;
import mx.quest.runway.spi.model.RouteRequest;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.service.PluginSiteFiles;
import mx.quest.search.spi.SearchHit;
import mx.quest.search.spi.SearchQuery;
import mx.quest.search.spi.SiteSearchEngine;
/** Shared builders for the plugin's tests: sites, catalog entries, requests and canned engines. */
final class Fixtures {
static final SiteView ACME = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null);
private Fixtures() {
}
/** A published English-only entry of {@code source} at {@code /<id>}. */
static CatalogEntry entry(String source, String id, String title, String description) {
ContentRef ref = new ContentRef(id, "/" + id, Map.of(), List.of(Locale.ENGLISH), Map.of("en", title),
Map.of("en", description), "", "tpl", true, Instant.EPOCH, false, null, null, Map.of());
return new CatalogEntry(source, ref, List.of(new LocalizedUrl(Locale.ENGLISH, "/" + id, null)), null);
}
/** A published page (source {@code pages}, id = slug). */
static CatalogEntry page(String slug, String title, String description) {
return entry("pages", slug, title, description);
}
/** A request on site acme with an optional {@code q} and the kernel-gated client IP. */
static RouteRequest request(String method, String path, String q, String clientIp) {
Map<String, List<String>> query = q == null ? Map.of() : Map.of("q", List.of(q));
return new RouteRequest(ACME, Locale.ENGLISH, method, path, query, Map.of(), new byte[0], Map.of(),
clientIp, "http://acme.test");
}
static RouteRequest request(String method, String path, String q) {
return request(method, path, q, "203.0.113.7");
}
/** An engine that returns canned hits and advertises a priority/availability. */
static SiteSearchEngine engine(String key, int priority, boolean available, SearchHit... hits) {
return new SiteSearchEngine() {
@Override
public String key() {
return key;
}
@Override
public List<SearchHit> search(SearchQuery q) {
return List.of(hits);
}
@Override
public int priority() {
return priority;
}
@Override
public boolean available(String siteId) {
return available;
}
};
}
static SearchRateLimiter unlimited() {
SearchProperties.RateLimit limits = new SearchProperties.RateLimit();
limits.setPerIpPerMinute(0);
limits.setPerIpPerHour(0);
return new SearchRateLimiter(limits);
}
/** A per-site folder that holds nothing and accepts nothing (for tests that never touch files). */
static final class NoFiles implements PluginSiteFiles {
@Override
public Optional<String> readText(String siteId, String relPath) {
return Optional.empty();
}
@Override
public void writeText(String siteId, String relPath, String text) {
throw new UnsupportedOperationException("no files in this test");
}
@Override
public boolean delete(String siteId, String relPath) {
return false;
}
@Override
public boolean deleteTree(String siteId, String relDir) {
return false;
}
@Override
public List<FileEntry> list(String siteId, String relDir) {
return List.of();
}
@Override
public Optional<FileEntry> stat(String siteId, String relPath) {
return Optional.empty();
}
}
}
@@ -0,0 +1,142 @@
package mx.quest.search;
import static mx.quest.search.Fixtures.ACME;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.List;
import java.util.Locale;
import java.util.Map;
import mx.quest.runway.spi.model.HeadContext;
import mx.quest.runway.spi.model.PageMeta;
import mx.quest.runway.spi.testkit.FakePluginSettings;
import mx.quest.search.spi.SearchHit;
import org.junit.jupiter.api.Test;
/**
* The result highlighter (2.1.0): the matched words a hit carries, the link marker that hands them to the target
* page, the head loader that brings the page script, and the agreement between the Java side and that script.
*/
class HighlightTest {
// --- SearchHit.terms -----------------------------------------------------------------------------
@Test
void theFourArgumentHitHasNoTerms() {
assertEquals(List.of(), new SearchHit("/a", "A", "", 1).terms(), "an engine built before 2.1.0 still links");
assertEquals(List.of(), new SearchHit("/a", "A", "", 1, null).terms());
}
@Test
void termsAreLowercasedDistinctTrimmedAndBounded() {
String tooLong = "x".repeat(SearchHit.MAX_TERM_LENGTH + 1);
SearchHit hit = new SearchHit("/a", "A", "", 1,
java.util.Arrays.asList(" Maestría ", "maestría", "", null, tooLong, "MBA"));
assertEquals(List.of("maestría", "mba"), hit.terms());
List<String> many = new java.util.ArrayList<>();
for (int i = 0; i < 50; i++) {
many.add("w" + i);
}
assertEquals(SearchHit.MAX_TERMS, new SearchHit("/a", "A", "", 1, many).terms().size());
}
// --- MatchedWords (the built-in engine) ------------------------------------------------------------
@Test
void theBuiltInEngineReportsTheWholeWordsAroundEachMatchTitleFirst() {
SearchDocument doc = SearchDocument.of("mba", "/mba", "Maestrías ejecutivas", "",
"La maestría (MBA) dura dos años; maestrías.");
assertEquals(List.of("maestrías", "maestría"), MatchedWords.in(doc, List.of("maestr")));
assertEquals(List.of("mba"), MatchedWords.in(doc, List.of("mba")), "punctuation ends a word");
assertEquals(List.of(), MatchedWords.in(doc, List.of("zzz")));
}
@Test
void theBuiltInEngineStopsAtTheCap() {
StringBuilder body = new StringBuilder();
for (int i = 0; i < 100; i++) {
body.append("run").append(i).append(' ');
}
SearchDocument doc = SearchDocument.of("x", "/x", "", "", body.toString());
assertEquals(SearchHit.MAX_TERMS, MatchedWords.in(doc, List.of("run")).size());
}
// --- HighlightMarker ------------------------------------------------------------------------------
@Test
void theMarkerPercentEncodesTheWordsAsOneComponent() {
SearchHit hit = new SearchHit("/es/mba", "MBA", "", 1, List.of("maestría", "a&b", "c#d"));
assertEquals("/es/mba#rw-hl=maestr%C3%ADa%20a%26b%20c%23d", HighlightMarker.link(hit));
}
@Test
void aHitWithoutWordsOrWithItsOwnFragmentLinksPlainly() {
assertEquals("/a", HighlightMarker.link(new SearchHit("/a", "A", "", 1)));
assertEquals("/a#top", HighlightMarker.link(new SearchHit("/a#top", "A", "", 1, List.of("x"))));
}
// --- SearchHighlightHead --------------------------------------------------------------------------
private static String head(FakePluginSettings settings, boolean preview) {
PageMeta page = new PageMeta("home", "Home", "", List.of(Locale.ENGLISH), Locale.ENGLISH, false, false);
HeadContext ctx = new HeadContext(ACME, page, Locale.ENGLISH, "", "", List.of(), preview, false, null);
return new SearchHighlightHead(settings).render(ctx);
}
@Test
void theLoaderIsAddedOnlyWhereSearchAndHighlightingAreOn() {
assertEquals(SearchHighlightHead.LOADER, head(new FakePluginSettings().site("acme", Map.of()), false),
"both default on");
assertEquals("", head(new FakePluginSettings().site("acme", Map.of("highlight", false)), false));
assertEquals("", head(new FakePluginSettings().site("acme", Map.of("enabled", false)), false));
assertEquals("", head(new FakePluginSettings().site("acme", Map.of()), true), "nothing in an editor preview");
}
@Test
void theLoaderIsOneSameOriginScriptThatLoadsTheHighlighterOnlyOnTheMarker() throws IOException {
assertEquals("<script src=\"/__plugin/search/static/highlight-loader.js?v=" + SearchConfig.VERSION
+ "\" defer></script>",
SearchHighlightHead.LOADER, "external and same-origin: the kernel never nonces an inline script");
String loader = Files.readString(Path.of("static/highlight-loader.js"), StandardCharsets.UTF_8);
assertTrue(loader.contains("indexOf('" + HighlightMarker.KEY + "=')<0)return"),
"it looks for the same key the links carry, and stops when it is absent");
assertTrue(loader.contains("'/__plugin/search/static/highlight.js?v=" + SearchConfig.VERSION + "'"),
"the loader asks for this release's script, so an upgrade is fetched at once");
assertTrue(loader.length() < 600, "fetched with every page, so it stays tiny: " + loader.length());
}
// --- the JSON API ---------------------------------------------------------------------------------------
@Test
void theApiGivesEachResultItsWordsAndItsMarkedLink() {
List<SearchHit> hits = List.of(new SearchHit("/mba", "MBA", "", 2, List.of("maestría")));
String on = SearchEndpoint.toJson("maestria", hits, true);
assertTrue(on.contains("\"link\":\"/mba#rw-hl=maestr%C3%ADa\""), on);
assertTrue(on.contains("\"terms\":[\"maestría\"]"), on);
assertTrue(on.contains("\"url\":\"/mba\""), "url stays the plain address");
String off = SearchEndpoint.toJson("maestria", hits, false);
assertTrue(off.contains("\"link\":\"/mba\""), off);
assertTrue(SearchEndpoint.toJson("x", List.of(new SearchHit("/a", "A", "", 1)), true)
.contains("\"terms\":[]"), "a hit without words has an empty list");
}
// --- the page script agrees with the Java side --------------------------------------------------------
@Test
void thePageScriptReadsTheSameKeyAndItsStylesheetShips() throws IOException {
String js = Files.readString(Path.of("static/highlight.js"), StandardCharsets.UTF_8);
assertTrue(js.contains("var KEY = '" + HighlightMarker.KEY + "=';"), "highlight.js reads the marker the links write");
assertTrue(js.contains("var MAX_WORDS = " + SearchHit.MAX_TERMS + ";"), "and accepts as many words as a hit carries");
assertTrue(js.contains("'/__plugin/search/static/highlight.css?v=" + SearchConfig.VERSION + "'"),
"the script asks for this release's stylesheet");
assertTrue(js.contains("history.replaceState"), "the marker is removed from the address");
String css = Files.readString(Path.of("static/highlight.css"), StandardCharsets.UTF_8);
assertTrue(css.contains("::highlight(rw-search)") && js.contains("var NAME = 'rw-search';"),
"the highlight name in the script and in the stylesheet agree");
}
}
@@ -0,0 +1,55 @@
package mx.quest.search;
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 org.junit.jupiter.api.Test;
/** The best-effort HTML-to-text extractor that feeds the built-in engine's body index. */
class HtmlTextTest {
@Test
void nullAndBlankYieldEmpty() {
assertEquals("", HtmlText.toText(null));
assertEquals("", HtmlText.toText(" "));
}
@Test
void tagsAreStrippedAndWhitespaceCollapsed() {
assertEquals("Hello world", HtmlText.toText("<p>Hello <b>world</b></p>\n"));
}
@Test
void scriptAndStyleContentIsRemoved() {
String html = "<style>.x{color:red}</style><p>visible</p><script>var a=1;</script>";
String text = HtmlText.toText(html);
assertEquals("visible", text);
assertFalse(text.contains("color"), "CSS is not indexable prose");
assertFalse(text.contains("var"), "JS is not indexable prose");
}
@Test
void commentsAreRemoved() {
assertEquals("after", HtmlText.toText("<!-- hidden note --> after"));
}
@Test
void commonEntitiesAreDecoded() {
assertEquals("a < b & c", HtmlText.toText("a &lt; b &amp; c"));
}
@Test
void anEscapedEntityRoundTripsWithoutOverDecoding() {
// "&amp;lt;" is the literal text "&lt;", not the character "<": &amp; decodes LAST so this is preserved.
assertEquals("&lt;", HtmlText.toText("&amp;lt;"));
}
@Test
void malformedHtmlStillYieldsSomeText() {
// An unclosed tag must not throw — indexing may never fail on one bad page.
String text = HtmlText.toText("<div><p>hello <b>world");
assertTrue(text.contains("hello"), "best-effort extraction yields the visible words");
assertTrue(text.contains("world"));
}
}
@@ -0,0 +1,32 @@
package mx.quest.search;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
/** A clock the test moves by hand. */
final class MutableClock extends Clock {
private Instant now = Instant.parse("2026-10-17T12:00:00Z");
void advance(Duration d) {
now = now.plus(d);
}
@Override
public ZoneId getZone() {
return ZoneOffset.UTC;
}
@Override
public Clock withZone(ZoneId zone) {
return this;
}
@Override
public Instant instant() {
return now;
}
}
@@ -0,0 +1,395 @@
package mx.quest.search;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import mx.quest.runway.spi.model.FileEntry;
import mx.quest.runway.spi.model.SettingsView;
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.TempDirSiteFiles;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.slf4j.LoggerFactory;
/**
* {@link NoResultsLog}: off by default, normalization, the personal-data filter, the repeat window, the term cap
* and its eviction order, retention, persistence to the plugin's own per-site file (through {@code PluginSiteFiles}),
* clear, tenant isolation, the wholesale-replacement reload, tolerant loading, an unreadable file never overwritten,
* and that a term never reaches a log line.
*/
class NoResultsLogTest {
@TempDir
Path root;
private PluginSiteFiles files;
private FakePluginSettings settings;
private final MutableClock clock = new MutableClock();
@BeforeEach
void setUp() throws IOException {
Files.createDirectories(root.resolve("acme"));
Files.createDirectories(root.resolve("beta"));
files = new TempDirSiteFiles(root, "search");
settings = new FakePluginSettings()
.defaults(Map.of("recordNoResults", false, "noResultsRetentionDays", 90L))
.site("acme", Map.of("recordNoResults", true))
.site("beta", Map.of("recordNoResults", true));
}
private NoResultsLog log() {
return new NoResultsLog(files, settings, clock, false);
}
/** Records {@code term} as a separate search (past the repeat window). */
private void search(NoResultsLog log, String site, String term) {
clock.advance(Duration.ofSeconds(2));
log.record(site, term);
}
private Path file(String site) {
return root.resolve(site).resolve("plugins/search").resolve(NoResultsLog.FILE);
}
@Test
void recordingIsOffUnlessTheSiteOptsIn() {
settings.site("acme", Map.of());
NoResultsLog log = log();
search(log, "acme", "pricing");
log.flush();
assertTrue(log.list("acme").isEmpty());
assertFalse(Files.exists(file("acme")), "nothing is written for a site that did not opt in");
assertFalse(log.enabled("acme"));
settings.site("acme", Map.of("recordNoResults", false));
search(log, "acme", "pricing");
assertTrue(log.list("acme").isEmpty());
}
@Test
void variantsOfOneTermAreCountedTogether() {
NoResultsLog log = log();
search(log, "acme", " Opening Hours ");
search(log, "acme", "opening hours");
search(log, "acme", "OPENING\tHOURS\n");
search(log, "acme", "opening hours");
List<NoResultsLog.Entry> list = log.list("acme");
assertEquals(1, list.size());
assertEquals("opening hours", list.get(0).term());
assertEquals(4, list.get(0).count());
assertEquals(clock.instant(), list.get(0).lastSeen());
}
@Test
void normalizationRulesAndLengthCap() {
assertNull(NoResultsLog.normalize(null));
assertNull(NoResultsLog.normalize(" \t\n "));
assertNull(NoResultsLog.normalize("\u0000​"), "control and format characters only — nothing left");
assertEquals("café", NoResultsLog.normalize("Café"), "NFC folds the combining accent");
assertEquals("a b", NoResultsLog.normalize("a\u0007 \u0000b"));
String longTerm = NoResultsLog.normalize("x".repeat(300));
assertEquals(NoResultsLog.MAX_TERM_CHARS, longTerm.length());
String surrogate = NoResultsLog.normalize("y".repeat(NoResultsLog.MAX_TERM_CHARS - 1) + "😀");
assertEquals("y".repeat(NoResultsLog.MAX_TERM_CHARS - 1), surrogate, "never half a code point");
}
@Test
void termsThatLookLikePersonalDataAreNeverStored() {
NoResultsLog log = log();
search(log, "acme", "maria.lopez@example.com");
search(log, "acme", "call +52 (55) 1234-5678");
search(log, "acme", "5512345678");
search(log, "acme", "iphone 15 pro");
search(log, "acme", "order 2024");
search(log, "acme", "user@localhost");
assertEquals(List.of("iphone 15 pro", "order 2024", "user@localhost"),
log.list("acme").stream().map(NoResultsLog.Entry::term).sorted().toList());
assertTrue(NoResultsLog.looksPersonal("12 34 56 7"), "separators between digits do not hide a number");
assertFalse(NoResultsLog.looksPersonal("123 abc 4567"), "letters break the run");
}
@Test
void theSameTermWithinTheRepeatWindowCountsOnce() {
NoResultsLog log = log();
log.record("acme", "faq");
log.record("acme", "faq"); // the second search box on the same page render
assertEquals(1, log.list("acme").get(0).count());
clock.advance(NoResultsLog.REPEAT_WINDOW);
log.record("acme", "faq");
assertEquals(2, log.list("acme").get(0).count(), "past the window it is a new search");
log.record("acme", "other");
log.record("acme", "faq"); // a different term in between: counted
assertEquals(3, log.list("acme").stream().filter(e -> e.term().equals("faq")).findFirst()
.orElseThrow().count());
}
@Test
void theListIsCappedAndEvictsTheLeastFrequentOldestTerm() {
NoResultsLog log = log();
search(log, "acme", "popular");
search(log, "acme", "popular");
search(log, "acme", "oldest-single");
for (int i = 0; i < NoResultsLog.MAX_TERMS - 2; i++) {
search(log, "acme", "t" + i);
}
assertEquals(NoResultsLog.MAX_TERMS, log.list("acme").size());
search(log, "acme", "newcomer");
List<String> terms = log.list("acme").stream().map(NoResultsLog.Entry::term).toList();
assertEquals(NoResultsLog.MAX_TERMS, terms.size(), "never more than the cap");
assertTrue(terms.contains("newcomer"));
assertTrue(terms.contains("popular"), "a frequent term survives a flood of one-offs");
assertFalse(terms.contains("oldest-single"), "the least frequent, longest-unseen term goes first");
assertEquals("popular", terms.get(0), "listed most frequent first");
}
@Test
void termsUnseenLongerThanTheRetentionDropOff() throws IOException {
settings.site("acme", Map.of("recordNoResults", true, "noResultsRetentionDays", 10));
NoResultsLog log = log();
search(log, "acme", "stale");
clock.advance(Duration.ofDays(9));
search(log, "acme", "fresh");
assertEquals(2, log.list("acme").size());
clock.advance(Duration.ofDays(2)); // "stale" is now 11 days old, "fresh" 2
assertEquals(List.of("fresh"), log.list("acme").stream().map(NoResultsLog.Entry::term).toList());
search(log, "acme", "fresh");
log.flush();
String stored = Files.readString(file("acme"), StandardCharsets.UTF_8);
assertFalse(stored.contains("stale"), "an expired term is not written back");
assertEquals(10, log.retentionDays("acme"));
}
@Test
void theRetentionSettingIsClampedAndDefaulted() {
assertEquals(NoResultsLog.DEFAULT_RETENTION_DAYS, log().retentionDays("acme"));
settings.site("acme", Map.of("noResultsRetentionDays", 100_000));
assertEquals(NoResultsLog.MAX_RETENTION_DAYS, log().retentionDays("acme"));
settings.site("acme", Map.of("noResultsRetentionDays", 0));
assertEquals(1, log().retentionDays("acme"));
}
@Test
void theListSurvivesARestartThroughThePluginsOwnFile() throws IOException {
NoResultsLog first = log();
search(first, "acme", "gift cards");
search(first, "acme", "gift cards");
search(first, "acme", "returns");
assertFalse(Files.exists(file("acme")), "nothing touches disk on the search path");
first.close();
assertTrue(Files.exists(root.resolve("acme/plugins/search/no-results.tsv")),
"stored only in the plugin's own per-site subtree — the same file as search 1.x");
String stored = Files.readString(file("acme"), StandardCharsets.UTF_8);
assertFalse(stored.matches("(?s).*\\d+\\.\\d+\\.\\d+\\.\\d+.*"), "no IP-shaped data in the file");
NoResultsLog second = log();
List<NoResultsLog.Entry> list = second.list("acme");
assertEquals(List.of("gift cards", "returns"), list.stream().map(NoResultsLog.Entry::term).toList());
assertEquals(2, list.get(0).count());
}
@Test
void clearForgetsTheListInMemoryAndOnDisk() throws IOException {
NoResultsLog log = log();
search(log, "acme", "careers");
log.flush();
assertTrue(Files.exists(file("acme")));
log.clear("acme");
assertTrue(log.list("acme").isEmpty());
assertFalse(Files.exists(file("acme")));
log.flush();
assertFalse(Files.exists(file("acme")), "a clear leaves nothing pending to write back");
assertTrue(log().list("acme").isEmpty(), "a fresh instance finds nothing either");
}
@Test
void eachSiteHasItsOwnList() {
NoResultsLog log = log();
search(log, "acme", "acme-only");
search(log, "beta", "beta-only");
assertEquals(List.of("acme-only"), log.list("acme").stream().map(NoResultsLog.Entry::term).toList());
assertEquals(List.of("beta-only"), log.list("beta").stream().map(NoResultsLog.Entry::term).toList());
settings.site("beta", Map.of());
search(log, "beta", "ignored");
assertEquals(1, log.list("beta").size(), "beta's own opt-out applies to beta only");
}
@Test
void aRestoredSiteIsReadFromItsFilesNotFromStaleMemory() throws IOException {
NoResultsLog log = log();
search(log, "acme", "before-restore");
Files.createDirectories(file("acme").getParent());
Files.writeString(file("acme"), "from-backup\t7\t" + clock.millis() + "\n", StandardCharsets.UTF_8);
log.forget("acme");
log.flush();
assertEquals(List.of("from-backup"), log.list("acme").stream().map(NoResultsLog.Entry::term).toList());
assertEquals(7, log.list("acme").get(0).count());
assertTrue(Files.readString(file("acme"), StandardCharsets.UTF_8).startsWith("from-backup\t7\t"),
"the forgotten list was never written over the restored file");
}
@Test
void aGarbledFileLoadsWhatItCanAndAnOversizedOneIsIgnored() throws IOException {
Files.createDirectories(file("acme").getParent());
long now = clock.millis();
Files.writeString(file("acme"), String.join("\n",
"good\t3\t" + now,
"bad count\tx\t" + now,
"too\tmany\tfields\there",
"zero\t0\t" + now,
" GOOD \t2\t" + (now - 5), // re-normalizes into "good" and merges
"") , StandardCharsets.UTF_8);
List<NoResultsLog.Entry> list = log().list("acme");
assertEquals(1, list.size());
assertEquals("good", list.get(0).term());
assertEquals(5, list.get(0).count());
Files.createDirectories(file("beta").getParent());
Files.writeString(file("beta"), ("t\t1\t" + now + "\n").repeat(50_000), StandardCharsets.UTF_8);
assertTrue(log().list("beta").isEmpty(), "a file over the size bound is not read");
}
@Test
void aTermNeverReachesALogLine() {
Logger logger = (Logger) LoggerFactory.getLogger(NoResultsLog.class);
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
logger.addAppender(appender);
try {
PluginSettings broken = new PluginSettings() {
@Override
public SettingsView site(String siteId) {
throw new IllegalStateException("boom");
}
@Override
public Optional<String> secret(String siteId, String key) {
return Optional.empty();
}
};
NoResultsLog log = new NoResultsLog(files, broken, clock, false);
log.record("acme", "secret-term-xyz"); // must not throw on the public search path
assertFalse(appender.list.isEmpty(), "the failure is logged");
assertTrue(appender.list.stream().noneMatch(e -> e.getFormattedMessage().contains("secret-term-xyz")));
} finally {
logger.detachAppender(appender);
}
}
@Test
void anUnreadableFileIsNeverOverwrittenWithAPartialList() throws IOException {
Files.createDirectories(file("acme").getParent());
String stored = "precious\t40\t" + clock.millis() + "\n";
Files.writeString(file("acme"), stored, StandardCharsets.UTF_8);
boolean[] readable = {false};
PluginSiteFiles flaky = new DelegatingFiles(files) {
@Override
public Optional<String> readText(String siteId, String relPath) throws IOException {
if (!readable[0]) {
throw new IOException("disk hiccup");
}
return super.readText(siteId, relPath);
}
};
NoResultsLog log = new NoResultsLog(flaky, settings, clock, false);
search(log, "acme", "new-term");
log.flush();
assertTrue(log.list("acme").isEmpty(), "nothing could be read, and nothing is pretended");
assertEquals(stored, Files.readString(file("acme"), StandardCharsets.UTF_8),
"the unreadable file is left exactly as it was");
readable[0] = true;
search(log, "acme", "new-term");
assertEquals(List.of("precious", "new-term"),
log.list("acme").stream().map(NoResultsLog.Entry::term).toList(),
"once the file reads again, the stored list is loaded and new searches add to it");
}
@Test
void aMissingSiteFolderMeansAFailedWriteNotACreatedSite() {
NoResultsLog log = log();
search(log, "gone", "x");
assertTrue(log.list("gone").isEmpty(), "a site with no folder has no settings opt-in here");
settings.site("gone", Map.of("recordNoResults", true));
search(log, "gone", "late");
log.flush();
assertFalse(Files.exists(root.resolve("gone")), "a late flush never creates a deleted site's folder");
}
@Test
void anUnsafeSiteIdIsRefusedBeforeAnyIo() {
NoResultsLog log = log();
log.record("../acme", "x"); // the public path never throws
assertThrows(IllegalArgumentException.class, () -> log.clear("../acme"));
}
/** A {@link PluginSiteFiles} that forwards every call; tests override the one they break. */
private static class DelegatingFiles implements PluginSiteFiles {
private final PluginSiteFiles d;
DelegatingFiles(PluginSiteFiles d) {
this.d = d;
}
@Override
public Optional<String> readText(String siteId, String relPath) throws IOException {
return d.readText(siteId, relPath);
}
@Override
public void writeText(String siteId, String relPath, String text) throws IOException {
d.writeText(siteId, relPath, text);
}
@Override
public boolean delete(String siteId, String relPath) throws IOException {
return d.delete(siteId, relPath);
}
@Override
public boolean deleteTree(String siteId, String relDir) throws IOException {
return d.deleteTree(siteId, relDir);
}
@Override
public List<FileEntry> list(String siteId, String relDir) throws IOException {
return d.list(siteId, relDir);
}
@Override
public Optional<FileEntry> stat(String siteId, String relPath) throws IOException {
return d.stat(siteId, relPath);
}
}
}
@@ -0,0 +1,194 @@
package mx.quest.search;
import static mx.quest.search.Fixtures.ACME;
import static mx.quest.search.Fixtures.request;
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.file.Files;
import java.nio.file.Path;
import java.time.Clock;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import mx.quest.runway.spi.model.PageMeta;
import mx.quest.runway.spi.model.Route;
import mx.quest.runway.spi.model.RouteResponse;
import mx.quest.runway.spi.model.SiteLifecycleEvent;
import mx.quest.runway.spi.model.WidgetView;
import mx.quest.runway.spi.testkit.EventDispatch;
import mx.quest.runway.spi.testkit.FakeContentCatalog;
import mx.quest.runway.spi.testkit.FakePluginSettings;
import mx.quest.runway.spi.testkit.FakeSiteServices;
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
import mx.quest.search.spi.SearchHit;
import mx.quest.search.spi.SiteSearchEngine;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* Where no-result searches get recorded and cleared: the box widget and the JSON API record a query that found
* nothing (and only that), the gated {@code POST /search/no-results/clear} empties the list and redirects back to
* the settings page, the admin model exposes the list, and a wholesale site event makes the list reload from disk.
*/
class NoResultsRecordingTest {
@TempDir
Path root;
private final Map<String, Object> cfg = new HashMap<>(Map.of("enabled", true, "recordNoResults", true));
private FakePluginSettings settings;
private FakeSiteServices kernel;
private NoResultsLog noResults;
@BeforeEach
void setUp() throws IOException {
Files.createDirectories(root.resolve("acme"));
settings = new FakePluginSettings();
refreshSettings();
kernel = new FakeSiteServices().site(ACME);
noResults = new NoResultsLog(new TempDirSiteFiles(root, "search"), settings, Clock.systemUTC(), false);
}
private void refreshSettings() {
settings.site("acme", cfg);
}
private SearchEndpoint endpoint(SiteSearchEngine engine) {
return new SearchEndpoint(List.of(engine), settings, kernel, Fixtures.unlimited(), kernel, kernel, noResults);
}
private static SiteSearchEngine engine(SearchHit... hits) {
return Fixtures.engine("search/simple", 0, true, hits);
}
private void renderWidget(SiteSearchEngine engine, String q) {
SearchBoxWidget widget = new SearchBoxWidget(List.of(engine), settings, kernel, noResults);
PageMeta page = new PageMeta("search", "Search", "", List.of(Locale.ENGLISH), Locale.ENGLISH, false, false);
widget.render(new WidgetView(ACME, page, Locale.ENGLISH, "search-box", false, Map.of(),
q == null ? Map.of() : Map.of("q", q)));
}
private List<String> terms() {
return noResults.list("acme").stream().map(NoResultsLog.Entry::term).toList();
}
@Test
void theWidgetRecordsAQueryThatFoundNothing() {
renderWidget(engine(), "Gift Cards");
assertEquals(List.of("gift cards"), terms());
}
@Test
void theWidgetDoesNotRecordAQueryWithResultsOrABareRender() {
renderWidget(engine(new SearchHit("/g", "Guide", "", 1)), "guide");
renderWidget(engine(), null);
renderWidget(engine(), " ");
assertTrue(terms().isEmpty());
}
@Test
void theWidgetRecordsNothingWhenSearchIsDisabled() {
cfg.put("enabled", false);
refreshSettings();
renderWidget(engine(), "anything");
assertTrue(terms().isEmpty());
}
@Test
void theJsonApiRecordsAQueryThatFoundNothingAndOnlyThat() {
endpoint(engine()).handle(request("GET", "/search/api", "warranty"));
endpoint(engine(new SearchHit("/a", "A", "", 1))).handle(request("GET", "/search/api", "found"));
endpoint(engine()).handle(request("GET", "/search/api", null));
assertEquals(List.of("warranty"), terms());
}
@Test
void theClearActionIsANonAnonymousPostRoute() {
Route clear = endpoint(engine()).routes().stream()
.filter(r -> r.pathPattern().equals(SearchEndpoint.CLEAR_NO_RESULTS_PATH)).findFirst().orElseThrow();
assertEquals("POST", clear.method());
assertFalse(clear.anonymous(), "the kernel's CSRF check must apply");
assertFalse(clear.posture().indexable());
}
@Test
void clearWithThePermissionEmptiesTheListAndRedirectsToSettings() {
endpoint(engine()).handle(request("GET", "/search/api", "returns"));
noResults.flush();
assertEquals(1, terms().size());
assertTrue(Files.exists(root.resolve("acme/plugins/search/" + NoResultsLog.FILE)));
kernel.grant("search|settings");
RouteResponse response = endpoint(engine()).handle(request("POST", SearchEndpoint.CLEAR_NO_RESULTS_PATH, null));
assertEquals(303, response.status());
assertEquals("/__admin/plugins/search/settings", response.headers().get("Location"));
assertTrue(terms().isEmpty());
assertFalse(Files.exists(root.resolve("acme/plugins/search/" + NoResultsLog.FILE)));
}
@Test
void clearWithoutThePermissionFailsClosedAndKeepsTheList() {
endpoint(engine()).handle(request("GET", "/search/api", "returns"));
RouteResponse response = endpoint(engine()).handle(request("POST", SearchEndpoint.CLEAR_NO_RESULTS_PATH, null));
assertEquals(404, response.status());
assertEquals(List.of("returns"), terms());
}
@Test
void clearByGetIsRefused() {
endpoint(engine()).handle(request("GET", "/search/api", "returns"));
kernel.grant("search|settings");
assertEquals(404, endpoint(engine()).handle(request("GET", SearchEndpoint.CLEAR_NO_RESULTS_PATH, null))
.status());
assertEquals(List.of("returns"), terms());
}
@Test
void theAdminModelExposesTheListAndTheSetting() {
endpoint(engine()).handle(request("GET", "/search/api", "Shipping"));
SiteSearchCorpus corpus = new SiteSearchCorpus(new FakeContentCatalog().site("acme"), settings);
SearchAdminModel model = new SearchAdminModel(List.of(engine()), corpus, kernel, settings, noResults);
assertTrue(model.noResultsRecording("acme"));
assertEquals(List.of("shipping"), model.noResults("acme").stream().map(NoResultsLog.Entry::term).toList());
assertEquals(NoResultsLog.DEFAULT_RETENTION_DAYS, model.noResultsRetentionDays("acme"));
assertEquals(NoResultsLog.MAX_TERMS, model.noResultsMaxTerms());
assertTrue(model.lastSeen(model.noResults("acme").get(0)).matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}"));
cfg.put("recordNoResults", false);
refreshSettings();
assertFalse(model.noResultsRecording("acme"));
assertFalse(model.noResultsRecording(null), "no bound site (the application console): nothing");
assertTrue(model.noResults(null).isEmpty());
}
@Test
void aWholesaleSiteEventReloadsTheListFromTheSiteFolderAndOthersKeepIt() throws IOException {
SimpleSearchEngine simple = new SimpleSearchEngine(
new SiteSearchCorpus(new FakeContentCatalog().site("acme"), settings), kernel, settings,
new SearchProperties());
EventDispatch events = new EventDispatch("search", Set.of())
.listener(new SearchSiteEvents(simple, noResults));
endpoint(engine()).handle(request("GET", "/search/api", "in-memory"));
Path file = root.resolve("acme/plugins/search/" + NoResultsLog.FILE);
Files.createDirectories(file.getParent());
Files.writeString(file, "from-backup\t3\t" + System.currentTimeMillis() + "\n");
events.lifecycle("acme", SiteLifecycleEvent.Kind.SUSPENDED, false);
assertEquals(List.of("in-memory"), terms(), "a metadata-only lifecycle change keeps the in-memory list");
events.lifecycle("acme", SiteLifecycleEvent.Kind.DELETED, false);
assertEquals(List.of("from-backup"), terms(), "a wholesale event drops the unwritten memory; the file is read");
endpoint(engine()).handle(request("GET", "/search/api", "after"));
events.lifecycle("acme", SiteLifecycleEvent.Kind.RESTORED, true);
assertEquals(List.of("from-backup"), terms(), "a restore reloads the restored file, unwritten memory dropped");
assertTrue(events.failures().isEmpty(), "no callback failed: " + events.failures());
}
}
@@ -0,0 +1,71 @@
package mx.quest.search;
import static mx.quest.search.Fixtures.ACME;
import static mx.quest.search.Fixtures.engine;
import static mx.quest.search.Fixtures.entry;
import static mx.quest.search.Fixtures.page;
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.time.Clock;
import java.util.List;
import java.util.Map;
import mx.quest.runway.spi.testkit.FakeContentCatalog;
import mx.quest.runway.spi.testkit.FakePluginSettings;
import mx.quest.runway.spi.testkit.FakeSiteServices;
import org.junit.jupiter.api.Test;
/**
* The console status model: the searchable-items count is the corpus (published items minus exclusions), the
* installed-page status and path come from {@code SitePages} (any state, following a move), the active engine, and
* a neutral answer for a {@code null} site (the application console has none).
*/
class SearchAdminModelTest {
private final FakePluginSettings settings = new FakePluginSettings();
private final FakeSiteServices kernel = new FakeSiteServices().site(ACME);
private final FakeContentCatalog catalog = new FakeContentCatalog()
.entry("acme", page("home", "Home", "")).entry("acme", page("privacy", "Privacy", ""))
.entry("acme", entry("blog", "first", "First", ""));
private SearchAdminModel model() {
return new SearchAdminModel(List.of(engine("search/simple", 0, true), engine("search/lucene", 10, false)),
new SiteSearchCorpus(catalog, settings), kernel, settings,
new NoResultsLog(new Fixtures.NoFiles(), settings, Clock.systemUTC(), false));
}
@Test
void searchableItemsCountsTheCorpusPagesAndSourceItemsMinusExclusions() {
assertEquals(3, model().searchableItems("acme"), "pages and content-source items alike");
settings.site("acme", Map.of("exclude", List.of("privacy")));
assertEquals(2, model().searchableItems("acme"), "what the index holds, so excluded items do not count");
assertEquals(0, model().searchableItems(null));
}
@Test
void theInstalledPageIsFoundBySlugWhereverItLives() {
assertFalse(model().pageInstalled("acme"));
assertEquals("", model().pagePath("acme"));
kernel.page("acme", "search", "/buscar");
assertTrue(model().pageInstalled("acme"));
assertEquals("/buscar", model().pagePath("acme"), "the live path, after the operator moved it");
assertFalse(model().pageInstalled(null));
assertEquals("", model().pagePath(null));
}
@Test
void theActiveEngineIsTheHighestPriorityAvailableOne() {
assertEquals("search/simple", model().activeEngineKey("acme"), "lucene is installed but not available");
assertEquals(2, model().engineCount());
assertEquals("none", model().activeEngineKey(null));
}
@Test
void enabledFollowsTheSetting() {
assertTrue(model().enabled("acme"), "default on");
settings.site("acme", Map.of("enabled", false));
assertFalse(model().enabled("acme"));
assertTrue(model().enabled(null));
}
}
@@ -0,0 +1,114 @@
package mx.quest.search;
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.time.Clock;
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 {@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 SearchAdminTemplateTest {
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() {
FakePluginSettings settings = new FakePluginSettings();
FakeSiteServices kernel = new FakeSiteServices();
SearchEndpoint endpoint = new SearchEndpoint(List.of(), settings, kernel, Fixtures.unlimited(), kernel,
kernel, new NoResultsLog(new Fixtures.NoFiles(), settings, Clock.systemUTC(), false));
List<String> paths = new ArrayList<>();
for (Route r : endpoint.routes()) {
if (r.method().equals("POST")) {
paths.add(r.pathPattern());
}
}
return paths;
}
@Test
void theOperatorActionsAreReindexInstallAndClear() {
assertEquals(List.of("/search/reindex", "/search/install-page", "/search/no-results/clear"), 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 {
for (String file : List.of("admin.html", "dashboard.html")) {
String html = read(file);
for (String action : operatorActions()) {
assertFalse(html.contains("href=\"" + action), file + ": a link is a GET and carries no 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));
}
}
@Test
void everySelectorInTheLogicMatchesAnIdInTheMarkup() throws IOException {
for (String name : List.of("admin", "dashboard")) {
String html = read(name + ".html");
Matcher sel = Pattern.compile("sel=\"#([\\w-]+)").matcher(read(name + ".th.xml"));
while (sel.find()) {
assertTrue(html.contains("id=\"" + sel.group(1) + "\""), name + ": #" + sel.group(1) + " has no element");
}
}
}
}
@@ -0,0 +1,190 @@
package mx.quest.search;
import static mx.quest.search.Fixtures.ACME;
import static mx.quest.search.Fixtures.engine;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Clock;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import mx.quest.runway.spi.model.PageMeta;
import mx.quest.runway.spi.model.WidgetView;
import mx.quest.runway.spi.testkit.FakePluginSettings;
import mx.quest.runway.spi.testkit.FakeSiteServices;
import mx.quest.search.spi.SearchHit;
import mx.quest.search.spi.SiteSearchEngine;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* The query-aware {@code search} box widget: it renders the box, and when its page is opened with {@code ?q=…}
* renders the results inline. Covers box rendering + form action, engine selection, the RAW snippet render, query
* escaping, the site's own words, and the disabled/blank cases.
*/
class SearchBoxWidgetTest {
private FakePluginSettings settings;
private FakeSiteServices kernel;
@BeforeEach
void setUp() {
settings = new FakePluginSettings().site("acme", Map.of("enabled", true));
kernel = new FakeSiteServices().site(ACME);
}
private String render(Map<String, String> query, SiteSearchEngine... engines) {
return render(false, Map.of(), query, engines);
}
private String render(boolean chrome, Map<String, Object> config, Map<String, String> query,
SiteSearchEngine... engines) {
SearchBoxWidget widget = new SearchBoxWidget(List.of(engines), settings, kernel,
new NoResultsLog(new Fixtures.NoFiles(), settings, Clock.systemUTC(), false));
PageMeta page = new PageMeta("search", "Search", "", List.of(Locale.ENGLISH), Locale.ENGLISH, false, false);
return widget.render(new WidgetView(ACME, page, Locale.ENGLISH, "search-box", chrome, config, query)).html();
}
private static SiteSearchEngine oneHit() {
return engine("search/simple", 0, true,
new SearchHit("/mba", "MBA", "the <mark>maestría</mark>", 3, List.of("maestría", "maestrías")));
}
@Test
void aBoxSubmitsToTheResultsPageInItsPagesLanguage() {
Locale es = Locale.of("es");
mx.quest.runway.spi.testkit.FakeContentCatalog catalog = new mx.quest.runway.spi.testkit.FakeContentCatalog()
.site("acme");
mx.quest.runway.spi.model.ContentRef ref = new mx.quest.runway.spi.model.ContentRef("search", "/search",
Map.of("es", "/buscar"), List.of(Locale.ENGLISH, es), Map.of("en", "Search"), Map.of(), "", "tpl",
true, java.time.Instant.EPOCH, false, null, null, Map.of());
catalog.entry("acme", new mx.quest.runway.spi.model.CatalogEntry("pages", ref, List.of(
new mx.quest.runway.spi.model.LocalizedUrl(Locale.ENGLISH, "/search", null),
new mx.quest.runway.spi.model.LocalizedUrl(es, "/es/buscar", null)), "/search"));
SearchBoxWidget widget = new SearchBoxWidget(List.of(oneHit()), settings, kernel,
new NoResultsLog(new Fixtures.NoFiles(), settings, Clock.systemUTC(), false),
new ResultsPageLinks(catalog));
PageMeta page = new PageMeta("about", "About", "", List.of(Locale.ENGLISH, es), Locale.ENGLISH, false, false);
String spanish = widget.render(new WidgetView(ACME, page, es, "search-box", true, Map.of(), Map.of())).html();
assertTrue(spanish.contains("action=\"/es/buscar\""), "a box on a Spanish page submits to /es/buscar: "
+ spanish);
String english = widget.render(new WidgetView(ACME, page, Locale.ENGLISH, "search-box", true, Map.of(),
Map.of())).html();
assertTrue(english.contains("action=\"/search\""), english);
String french = widget.render(new WidgetView(ACME, page, Locale.FRENCH, "search-box", true, Map.of(),
Map.of())).html();
assertTrue(french.contains("action=\"/search\""),
"the results page has no French address: the setting as written: " + french);
settings.site("acme", Map.of("enabled", true, "resultsPath", "/nowhere"));
String unknown = widget.render(new WidgetView(ACME, page, es, "search-box", true, Map.of(), Map.of())).html();
assertTrue(unknown.contains("action=\"/nowhere\""), "no page at the path: the setting as written: " + unknown);
}
@Test
void aResultLinkCarriesTheMatchedWordsForTheTargetPage() {
String html = render(Map.of("q", "maestría"), oneHit());
assertTrue(html.contains("href=\"/mba#rw-hl=maestr%C3%ADa%20maestr%C3%ADas\""),
"the link carries the matched words, percent-encoded, space as %20: " + html);
}
@Test
void withHighlightOffTheLinkIsPlain() {
settings.site("acme", Map.of("enabled", true, "highlight", false));
String html = render(Map.of("q", "maestría"), oneHit());
assertTrue(html.contains("href=\"/mba\""), html);
assertFalse(html.contains("rw-hl"), "no marker anywhere when the site turned highlighting off");
}
@Test
void aBoxInTheMasterChromeShowsOnlyTheBoxByDefault() {
String html = render(true, Map.of(), Map.of("q", "maestría"), oneHit());
assertTrue(html.contains("name=\"q\""), "the box itself is shown");
assertFalse(html.contains("rw-search-hits"), "a header/footer box does not repeat the results page's list");
assertFalse(html.contains("rw-search-empty"), "…nor a 'no results' line");
}
@Test
void thePlacementSettingOverridesWhereResultsAreListed() {
assertTrue(render(true, Map.of("results", "always"), Map.of("q", "x"), oneHit()).contains("rw-search-hits"),
"always: a chrome box lists the results");
assertFalse(render(false, Map.of("results", "never"), Map.of("q", "x"), oneHit()).contains("rw-search-hits"),
"never: a content box shows only the box");
assertTrue(render(false, Map.of("results", "auto"), Map.of("q", "x"), oneHit()).contains("rw-search-hits"),
"auto: a content box lists them");
assertTrue(render(false, Map.of("results", "bogus"), Map.of("q", "x"), oneHit()).contains("rw-search-hits"),
"an unknown value behaves as auto");
}
@Test
void aBareRenderShowsTheBoxButNoResults() {
String html = render(Map.of(), engine("search/simple", 0, true));
assertTrue(html.contains("name=\"q\""), "the search box is shown");
assertTrue(html.contains("action=\"/search\""), "the box submits to the results page (default /search)");
assertTrue(html.contains("placeholder=\"Search…\""), "the default placeholder");
assertFalse(html.contains("rw-search-hits"), "no results list without a query");
}
@Test
void resultsRenderInlineWhenTheQueryIsPresent() {
String html = render(Map.of("q", "runway"),
engine("search/simple", 0, true, new SearchHit("/guide", "Runway Guide", "How to deploy.", 3)));
assertTrue(html.contains("Runway Guide"), "the hit title is rendered");
assertTrue(html.contains("href=\"/guide\""), "the hit links to the page");
assertTrue(html.contains("/__plugin/search/static/search.css"), "the widget references the plugin CSS");
assertTrue(html.contains("value=\"runway\""), "the box keeps the current query");
assertTrue(html.contains("1 result(s) for"), "the count line");
}
@Test
void theSnippetIsRenderedAsRawHtmlSoTheHighlightShows() {
String snippet = "deploy <mark>runway</mark> now &amp; later";
String html = render(Map.of("q", "runway"),
engine("search/simple", 0, true, new SearchHit("/g", "Guide", snippet, 3)));
assertTrue(html.contains("<mark>runway</mark>"), "the engine's <mark> is emitted raw (highlight shows)");
assertFalse(html.contains("&lt;mark&gt;"), "the snippet is NOT double-escaped");
assertTrue(html.contains("&amp; later"), "…while the engine's own escaping is preserved verbatim");
}
@Test
void aCraftedQueryIsEscaped() {
String html = render(Map.of("q", "<script>x</script>"), engine("search/simple", 0, true));
assertFalse(html.contains("<script>x</script>"), "the query is HTML-escaped, never reflected as markup");
assertTrue(html.contains("&lt;script&gt;"), "…it appears escaped");
}
@Test
void theHighestPriorityAvailableEngineServesTheResults() {
String html = render(Map.of("q", "x"),
engine("search/simple", 0, true, new SearchHit("/a", "FromSimple", "", 1)),
engine("search/lucene", 100, true, new SearchHit("/b", "FromLucene", "", 1)),
engine("search/broken", 200, false, new SearchHit("/c", "FromBroken", "", 1)));
assertTrue(html.contains("FromLucene"), "the highest-priority AVAILABLE engine serves");
assertFalse(html.contains("FromBroken"), "an unavailable higher-priority engine is skipped");
}
@Test
void theResultsPathAndPlaceholderSettingsShapeTheBox() {
settings.site("acme", Map.of("enabled", true, "resultsPath", " /find ", "placeholder", "Look up"));
String html = render(Map.of(), engine("search/simple", 0, true));
assertTrue(html.contains("action=\"/find\""), "the box submits to the configured results page");
assertTrue(html.contains("placeholder=\"Look up\""), "the configured placeholder");
}
@Test
void theSitesOwnWordsAreUsed() {
kernel.message("acme", "search.box.submit", "Buscar").message("acme", "search.results.none", "Nada para");
String html = render(Map.of("q", "zzz"), engine("search/simple", 0, true));
assertTrue(html.contains(">Buscar</button>"), "the submit label comes from Messages.site");
assertTrue(html.contains("Nada para “zzz”."), "the empty-result line too");
}
@Test
void aDisabledSearchRendersNothing() {
settings.site("acme", Map.of("enabled", false));
assertTrue(render(Map.of("q", "runway"), engine("search/simple", 0, true)).isEmpty(),
"a disabled search widget renders an empty fragment");
}
}
@@ -0,0 +1,281 @@
package mx.quest.search;
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.ContentWidget;
import mx.quest.runway.spi.EndpointContributor;
import mx.quest.runway.spi.model.SettingsView;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.service.ContentCatalogView;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.spi.service.PluginSiteFiles;
import mx.quest.runway.spi.service.SiteEventListener;
import mx.quest.runway.spi.testkit.FakeContentCatalog;
import mx.quest.runway.spi.testkit.FakePluginSettings;
import mx.quest.runway.spi.testkit.FakeSiteServices;
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
import mx.quest.search.spi.SearchCorpus;
import mx.quest.search.spi.SiteSearchEngine;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.MapPropertySource;
import org.yaml.snakeyaml.Yaml;
/**
* The plugin's contract with the host, checked at build time: the wiring over SPI services only (including the
* app-level properties bound under {@code runway.plugin.search}), the bean-name rule, the bean names the templates
* reference, the descriptor (SPI floor, release version, the personal-data declaration matching the file the log
* writes), the code fallbacks equal to the descriptor defaults, 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 SearchConfigTest {
private static final String PREFIX = "search";
/** Stands in for the host's Spring Boot auto-configuration: the binder behind {@code @ConfigurationProperties}. */
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
static class HostBinding {
}
private static Set<String> beanMethodNames() {
return Arrays.stream(SearchConfig.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);
}
}
@SuppressWarnings("unchecked")
private static Map<String, Object> declaredDefaults(String section) throws IOException {
Map<String, Object> out = new java.util.LinkedHashMap<>();
for (Map<String, Object> s : (List<Map<String, Object>>) descriptor().get(section)) {
if (s.containsKey("default")) {
out.put((String) s.get("key"), s.get("default"));
}
}
return out;
}
@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", "search", "/buscar");
FakeContentCatalog catalog = new FakeContentCatalog()
.entry("acme", Fixtures.page("home", "Runway home", ""))
.entry("acme", Fixtures.page("privacy", "Runway privacy", ""));
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource("plugin-settings", Map.of(
"runway.plugin.search.refresh-minutes", "5",
"runway.plugin.search.rate-limit.per-ip-per-minute", "7",
"runway.plugin.search.rate-limit.per-ip-per-hour", "70")));
ctx.registerBean(PluginSettings.class, () -> new FakePluginSettings()
.site("acme", Map.of("exclude", List.of("privacy"))));
ctx.registerBean(PluginSiteFiles.class, () -> new TempDirSiteFiles(sites, "search"));
ctx.registerBean(FakeSiteServices.class, () -> kernel);
ctx.registerBean(ContentCatalogView.class, () -> catalog);
ctx.register(HostBinding.class, SearchConfig.class);
ctx.refresh();
SearchProperties props = ctx.getBean("searchProperties", SearchProperties.class);
assertEquals(5, props.getRefreshMinutes(), "the app-level settings bind under runway.plugin.search");
assertEquals(7, props.getRateLimit().getPerIpPerMinute());
assertEquals(70, props.getRateLimit().getPerIpPerHour());
assertInstanceOf(SiteSearchCorpus.class, ctx.getBean("searchCorpus", SearchCorpus.class));
assertEquals(List.of(ctx.getBean("searchSimpleEngine")),
List.copyOf(ctx.getBeansOfType(SiteSearchEngine.class).values()));
Map<String, SiteEventListener> listeners = ctx.getBeansOfType(SiteEventListener.class);
assertEquals(Set.of("searchSiteEvents"), listeners.keySet(), "one listener, collected by type");
assertEquals(SiteEventListener.Phase.CONSUMER, listeners.get("searchSiteEvents").phase());
assertInstanceOf(SearchEndpoint.class, ctx.getBean("searchResultsEndpoint", EndpointContributor.class));
assertInstanceOf(SearchBoxWidget.class, ctx.getBean("searchBoxWidget", ContentWidget.class));
SearchAdminModel model = ctx.getBean("searchAdminModel", SearchAdminModel.class);
assertEquals(1, model.searchableItems("acme"), "the corpus reads the catalog and the injected settings");
assertEquals("/buscar", model.pagePath("acme"), "…and the page through SitePages");
assertEquals("search/simple", model.activeEngineKey("acme"));
for (String name : ctx.getBeanDefinitionNames()) {
Class<?> type = ctx.getType(name);
if (type != null && type.getPackageName().startsWith("mx.quest.search")) {
assertTrue(name.startsWith(PREFIX), "every plugin bean name starts with 'search': " + name);
}
}
}
}
@Test
void everyBeanNameStartsWithThePluginIdInLowerCamelCase() {
assertEquals(Set.of("searchProperties", "searchCorpus", "searchSimpleEngine", "searchRateLimiter",
"searchNoResultsLog", "searchSiteEvents", "searchResultsEndpoint", "searchBoxWidget",
"searchHighlightHead", "searchAdminModel"), beanMethodNames());
for (Method m : SearchConfig.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);
}
}
}
assertFalse(SearchConfig.class.isAnnotationPresent(EnableConfigurationProperties.class),
"@EnableConfigurationProperties names its bean '<prefix>-<class>', which breaks the bean-name rule");
}
@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()) {
String live = Files.readString(file, StandardCharsets.UTF_8).replaceAll("(?s)<!--.*?-->", "");
Matcher m = Pattern.compile("@(\\w+)\\.").matcher(live);
while (m.find()) {
referenced.add(m.group(1));
}
}
}
assertEquals(Set.of("searchAdminModel"), 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-search</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");
assertEquals("2.3.0", version.group(1));
assertEquals(version.group(1), SearchConfig.VERSION, "the ?v= on the plugin's file URLs is this release");
assertFalse(pom.contains("<artifactId>runway-app</artifactId>"), "no runway-app dependency in any scope");
assertTrue(pom.contains("<project.build.outputTimestamp>2026-10-21T17:23:00Z</project.build.outputTimestamp>"));
}
@Test
@SuppressWarnings("unchecked")
void theNoResultsFileIsDeclaredPersonalDataSoTransferCopiesLeaveItOut() throws IOException {
Map<String, Object> siteData = (Map<String, Object>) descriptor().get("siteData");
assertTrue(siteData != null, "plugin.yml declares siteData");
assertEquals(List.of(NoResultsLog.FILE), siteData.get("personal"),
"exactly the file the no-result log writes (search terms visitors typed) is personal data");
}
@Test
void theCodeFallbacksEqualTheDescriptorDefaults() throws IOException {
Map<String, Object> site = declaredDefaults("siteSettings");
SearchSiteConfig code = SearchSiteConfig.of(SettingsView.empty());
assertEquals(site.get("enabled"), code.enabled());
assertEquals(site.get("resultLimit"), code.resultLimit());
assertEquals(site.get("resultsPath"), code.resultsPath());
assertEquals(site.get("snippetLength"), code.snippetLength());
assertEquals(site.get("highlight"), code.highlight());
assertEquals(site.get("titleWeight"), code.titleWeight());
assertEquals(site.get("descriptionWeight"), code.descriptionWeight());
assertEquals(site.get("bodyWeight"), code.bodyWeight());
assertEquals(site.get("allTermsBonus"), code.allTermsBonus());
assertEquals(site.get("phraseTitleBonus"), code.phraseTitleBonus());
assertEquals(site.get("phraseBodyBonus"), code.phraseBodyBonus());
assertEquals(site.get(NoResultsLog.ENABLED_KEY), false, "recording is off by default");
assertEquals(site.get(NoResultsLog.RETENTION_KEY), NoResultsLog.DEFAULT_RETENTION_DAYS);
assertEquals(13, site.size(), "every declared default is checked above (exclude/placeholder have none)");
Map<String, Object> app = declaredDefaults("settings");
SearchProperties props = new SearchProperties();
assertEquals(app.get("refresh-minutes"), props.getRefreshMinutes());
assertEquals(app.get("rate-limit.per-ip-per-minute"), props.getRateLimit().getPerIpPerMinute());
assertEquals(app.get("rate-limit.per-ip-per-hour"), props.getRateLimit().getPerIpPerHour());
}
@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("search.page.installed", "search.page.pending", "search.page.blocked",
"search.page.exists", "search.page.failed", "search.page.other", "search.reindex.done",
"search.reindex.button", "search.reindex.tip", "search.reindex.desc")) {
assertTrue(en.contains(key), "every operator 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 >= 18, "the compiled classes were found (" + scanned + ")");
assertTrue(problems.isEmpty(), "host linkage: " + problems);
}
@Test
void theCompiledClassesLinkNoCaffeine() throws IOException {
// Caffeine is a kernel implementation detail, not one of the platform libraries the kernel promises
// (Spring, Spring Boot, Spring Security, Thymeleaf, Jackson, Jakarta EE): a plugin must not link it.
Path classes = Path.of("target", "classes");
try (Stream<Path> files = Files.walk(classes)) {
for (Path file : files.filter(p -> p.toString().endsWith(".class")).toList()) {
String pool = new String(Files.readAllBytes(file), StandardCharsets.ISO_8859_1);
assertFalse(pool.contains("com/github/benmanes"), file + " links Caffeine");
}
}
}
}
@@ -0,0 +1,348 @@
package mx.quest.search;
import static mx.quest.search.Fixtures.ACME;
import static mx.quest.search.Fixtures.engine;
import static mx.quest.search.Fixtures.request;
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.nio.charset.StandardCharsets;
import java.time.Clock;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
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 mx.quest.search.spi.SearchHit;
import mx.quest.search.spi.SearchQuery;
import mx.quest.search.spi.SiteSearchEngine;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* The search plugin's request surface — it owns no visible page (the box + inline results are the query-aware
* {@link SearchBoxWidget}). Covered here: the routes (one GET read, three non-anonymous POST actions), the JSON API
* (engine pick, escaping, the per-client rate limit keyed on the kernel-gated client IP), the gated reindex, and the
* gated {@code /search/install-page} through {@code SitePages} with each install outcome reported.
*/
class SearchEndpointTest {
private FakePluginSettings settings;
private FakeSiteServices kernel;
@BeforeEach
void setUp() {
settings = new FakePluginSettings().site("acme", Map.of("enabled", true));
kernel = new FakeSiteServices().site(ACME);
}
private SearchEndpoint endpoint(SiteSearchEngine... engines) {
return endpoint(Fixtures.unlimited(), engines);
}
private SearchEndpoint endpoint(SearchRateLimiter limiter, SiteSearchEngine... engines) {
return new SearchEndpoint(List.of(engines), settings, kernel, limiter, kernel, kernel,
new NoResultsLog(new Fixtures.NoFiles(), settings, Clock.systemUTC(), false));
}
private static SearchRateLimiter rateLimiter(int perMinute, int perHour) {
SearchProperties.RateLimit cfg = new SearchProperties.RateLimit();
cfg.setPerIpPerMinute(perMinute);
cfg.setPerIpPerHour(perHour);
return new SearchRateLimiter(cfg);
}
private static String body(RouteResponse res) {
return new String(res.body(), StandardCharsets.UTF_8);
}
// --- routes ------------------------------------------------------------------------------------
@Test
void theApiIsTheOnlyGetAndEveryOperatorActionIsANonAnonymousPost() {
List<Route> routes = endpoint(engine("search/simple", 0, true)).routes();
assertEquals(List.of("GET /search/api", "POST /search/reindex", "POST /search/install-page",
"POST /search/no-results/clear"),
routes.stream().map(r -> r.method() + " " + r.pathPattern()).toList());
assertTrue(routes.stream().noneMatch(Route::anonymous),
"no route is CSRF-exempt: the operator actions need the console session's token");
assertTrue(routes.stream().noneMatch(r -> r.posture().indexable()), "never advertised or crawled");
}
@Test
void theRetiredSearchPageRouteIsNotHandled() {
assertEquals(404, endpoint(engine("search/simple", 0, true)).handle(request("GET", "/search", "x")).status());
}
@Test
void theHighestPriorityAvailableEngineIsPicked() {
SearchEndpoint ep = endpoint(
engine("search/simple", 0, true),
engine("search/lucene", 100, true),
engine("search/broken", 200, false)); // higher priority but unavailable
assertEquals("search/lucene", ep.pick("acme").key(),
"the highest-priority AVAILABLE engine wins; an unavailable one is skipped");
}
// --- JSON API ----------------------------------------------------------------------------------
@Test
void theJsonApiReturnsResults() {
SearchEndpoint ep = endpoint(engine("search/simple", 0, true,
new SearchHit("/guide", "Runway Guide", "deploy <mark>runway</mark>", 3.5)));
RouteResponse res = ep.handle(request("GET", "/search/api", "runway"));
assertEquals(200, res.status());
assertEquals("application/json; charset=utf-8", res.headers().get("Content-Type"));
String json = body(res);
assertTrue(json.contains("\"count\":1"), "the count is reported");
assertTrue(json.contains("\"url\":\"/guide\""), "the hit url is present");
assertTrue(json.contains("\"title\":\"Runway Guide\""), "the hit title is present");
assertTrue(json.contains("\"query\":\"runway\""), "the query echoes back");
}
@Test
void theJsonApiPassesTheResultLimitAndLocaleToTheEngine() {
List<SearchQuery> seen = new ArrayList<>();
SiteSearchEngine recording = new SiteSearchEngine() {
@Override
public String key() {
return "rec";
}
@Override
public List<SearchHit> search(SearchQuery q) {
seen.add(q);
return List.of();
}
};
settings.site("acme", Map.of("resultLimit", 7));
RouteRequest es = new RouteRequest(ACME, Locale.of("es"), "GET", "/search/api", Map.of("q", List.of(" x ")),
Map.of(), new byte[0]);
endpoint(recording).handle(es);
assertEquals(1, seen.size());
assertEquals(new SearchQuery("acme", "x", Locale.of("es"), 7), seen.get(0), "trimmed text, limit, locale");
}
@Test
void theJsonApiEscapesAngleBracketsInStrings() {
SearchEndpoint ep = endpoint(engine("search/simple", 0, true, new SearchHit("/g", "T", "<mark>hi</mark>", 1)));
String json = body(ep.handle(request("GET", "/search/api", "hi")));
assertFalse(json.contains("<mark>"), "angle brackets are unicode-escaped in JSON output");
assertTrue(json.contains("\\u003cmark\\u003e"), "…as \\u003c / \\u003e");
}
@Test
void theJsonApiDisabledReturns404() {
settings.site("acme", Map.of("enabled", false));
assertEquals(404, endpoint(engine("search/simple", 0, true)).handle(request("GET", "/search/api", "x")).status());
}
@Test
void theJsonApiIsReadOnlyByGet() {
assertEquals(404, endpoint(engine("search/simple", 0, true)).handle(request("POST", "/search/api", "x"))
.status());
}
@Test
void theJsonApiIsRateLimitedPerTrustedClientIp() {
SearchEndpoint ep = endpoint(rateLimiter(1, 1000), engine("search/simple", 0, true));
assertEquals(200, ep.handle(request("GET", "/search/api", "x", "198.51.100.1")).status());
assertEquals(429, ep.handle(request("GET", "/search/api", "x", "198.51.100.1")).status(),
"the second query from the same client is over the per-minute budget");
assertEquals(200, ep.handle(request("GET", "/search/api", "x", "198.51.100.2")).status(),
"another client has its own budget");
}
@Test
void aForwardedHeaderCannotPickANewRateLimitKey() {
// 1.x keyed on the first X-Forwarded-For hop, so a visitor evaded the limit with a made-up header per
// request. The key is now the kernel's gated client IP; the header (which the kernel only applies for a
// trusted proxy) plays no part.
SearchEndpoint ep = endpoint(rateLimiter(1, 1000), engine("search/simple", 0, true));
for (int i = 0; i < 3; i++) {
RouteRequest spoofed = new RouteRequest(ACME, Locale.ENGLISH, "GET", "/search/api",
Map.of("q", List.of("x")), Map.of("X-Forwarded-For", "10.0.0." + i), new byte[0], Map.of(),
"198.51.100.9", "");
assertEquals(i == 0 ? 200 : 429, ep.handle(spoofed).status(), "query " + i);
}
}
@Test
void requestsWithoutAClientIpShareOneBucket() {
SearchEndpoint ep = endpoint(rateLimiter(1, 1000), engine("search/simple", 0, true));
assertEquals(200, ep.handle(request("GET", "/search/api", "x", null)).status());
assertEquals(429, ep.handle(request("GET", "/search/api", "x", null)).status(),
"no client IP never escapes the limit");
}
@Test
void aBlankQueryIsNotCountedAgainstTheLimit() {
SearchEndpoint ep = endpoint(rateLimiter(1, 1000), engine("search/simple", 0, true));
assertEquals(200, ep.handle(request("GET", "/search/api", " ")).status());
assertEquals(200, ep.handle(request("GET", "/search/api", "x")).status());
}
// --- reindex (gated POST) ----------------------------------------------------------------------
@Test
void reindexFailsClosedWithoutPermission() {
int[] rebuilt = {0};
RouteResponse res = endpoint(reindexing("search/simple", 0, 3, rebuilt))
.handle(request("POST", "/search/reindex", null));
assertEquals(404, res.status(), "no permission ⇒ 404 (the action is not even revealed)");
assertEquals(0, rebuilt[0], "and nothing was rebuilt");
}
@Test
void reindexByGetChangesNothingEvenWithPermission() {
kernel.grant("search|settings");
int[] rebuilt = {0};
RouteResponse res = endpoint(reindexing("search/simple", 0, 3, rebuilt))
.handle(request("GET", "/search/reindex", null));
assertEquals(404, res.status(), "a link or an <img> cannot trigger it");
assertEquals(0, rebuilt[0]);
}
@Test
void reindexRebuildsEveryEngineAndReportsTheServingOnesCount() {
kernel.grant("search|settings");
kernel.message(null, "search.reindex.done", "Index rebuilt.");
int[] rebuilt = {0};
RouteResponse res = endpoint(reindexing("search/simple", 0, 3, rebuilt),
reindexing("search/lucene", 100, 7, rebuilt)).handle(request("POST", "/search/reindex", null));
assertEquals(200, res.status());
assertEquals(2, rebuilt[0], "EVERY registered engine is rebuilt — not only the built-in one");
assertEquals("Index rebuilt. (7)", body(res),
"console wording; the count is the serving (highest-priority available) engine's");
}
private static SiteSearchEngine reindexing(String key, int priority, int documents, int[] counter) {
return new SiteSearchEngine() {
@Override
public String key() {
return key;
}
@Override
public List<SearchHit> search(SearchQuery q) {
return List.of();
}
@Override
public int priority() {
return priority;
}
@Override
public int reindex(String siteId) {
counter[0]++;
return documents;
}
};
}
// --- install-page (gated POST, through SitePages) ----------------------------------------------
@Test
void installPageFailsClosedWithoutPermission() {
RouteResponse res = endpoint(engine("search/simple", 0, true)).handle(request("POST", "/search/install-page", null));
assertEquals(404, res.status());
assertTrue(kernel.installs().isEmpty(), "nothing was installed");
}
@Test
void installPageByGetChangesNothingEvenWithPermission() {
kernel.grant("search|settings");
assertEquals(404, endpoint(engine("search/simple", 0, true))
.handle(request("GET", "/search/install-page", null)).status());
assertTrue(kernel.installs().isEmpty());
}
@Test
void installPageHandsSitePagesAnEditableNoindexPageCarryingTheWidget() {
kernel.grant("search|settings");
kernel.message("acme", "search.page.title", "Find");
RouteResponse res = endpoint(engine("search/simple", 0, true)).handle(request("POST", "/search/install-page", null));
assertEquals(200, res.status());
assertEquals("Search page installed at /search", body(res));
StarterPage page = kernel.installs().get(0);
assertEquals("search", page.slug());
assertEquals("/search", page.path());
assertTrue(page.noindex(), "the results page installs noindex — the canonical index opt-out for search results");
assertEquals(Map.of("en", "Find"), page.titles(), "titled in the site's default language, from Messages.site");
assertTrue(page.html().contains("<div id=\"search-box\" data-widget=\"search/box\"></div>"),
"the page carries the search-box widget anchor (id and data-widget on one element)");
assertTrue(page.html().contains("<title>Find</title>"));
assertTrue(page.logic().contains("~{${master} :: head}"), "the logic pulls the master chrome");
}
@Test
void installPageEscapesTheTitleInTheMarkup() {
kernel.grant("search|settings");
kernel.message("acme", "search.page.title", "<b>Find</b>");
endpoint(engine("search/simple", 0, true)).handle(request("POST", "/search/install-page", null));
assertTrue(kernel.installs().get(0).html().contains("&lt;b&gt;Find&lt;/b&gt;"));
}
@Test
void installPageReportsEveryOutcomeInTheOperatorsWords() {
kernel.grant("search|settings");
kernel.nextInstall(InstallResult.Outcome.PENDING_REVIEW);
assertEquals("The search page was created and is waiting in the review queue: /search", installAt("a"));
kernel.nextInstall(InstallResult.Outcome.DRAFT_BLOCKED,
new Finding(Severity.ERROR, "seo.title", "Title missing"));
assertEquals("The search page was created as a draft because the quality checks blocked publishing; "
+ "fix it in the page editor: /search\n- seo.title: Title missing", installAt("b"));
kernel.page("c", "search", "/buscar");
assertEquals("A search page already exists at /buscar", installAt("c"),
"an existing page is reported where it lives now, never overwritten");
}
private String installAt(String siteId) {
SiteView site = new SiteView(siteId, siteId, Locale.ENGLISH, List.of(Locale.ENGLISH), null);
kernel.site(site);
RouteRequest req = new RouteRequest(site, Locale.ENGLISH, "POST", "/search/install-page", Map.of(), Map.of(),
new byte[0]);
RouteResponse res = endpoint(engine("search/simple", 0, true)).handle(req);
assertEquals(200, res.status());
return body(res);
}
@Test
void aFailedInstallIsA500WithoutDetail() {
kernel.grant("search|settings");
SearchEndpoint failing = new SearchEndpoint(List.of(engine("search/simple", 0, true)), settings, kernel,
Fixtures.unlimited(), kernel, new ThrowingPages(),
new NoResultsLog(new Fixtures.NoFiles(), settings, Clock.systemUTC(), false));
RouteResponse res = failing.handle(request("POST", "/search/install-page", null));
assertEquals(500, res.status());
assertEquals("Could not install the search page.", body(res), "no internal detail reaches the operator");
}
/** {@code SitePages} whose install fails the way the kernel's does for a taken path or a failed write. */
private static final class ThrowingPages implements SitePages {
@Override
public Optional<String> pathOf(String siteId, String slug) {
return Optional.empty();
}
@Override
public InstallResult install(String siteId, StarterPage page) {
throw new IllegalStateException("another page serves /search");
}
}
}
@@ -0,0 +1,121 @@
package mx.quest.search;
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.time.Duration;
import org.junit.jupiter.api.Test;
/**
* The per-client courtesy limiter: a flood from one key is rejected; a disabled window never rejects; each window
* restarts once it has passed; the table of clients is bounded.
*/
class SearchRateLimiterTest {
private static SearchRateLimiter limiter(int perMinute, int perHour) {
SearchProperties.RateLimit cfg = new SearchProperties.RateLimit();
cfg.setPerIpPerMinute(perMinute);
cfg.setPerIpPerHour(perHour);
return new SearchRateLimiter(cfg);
}
@Test
void aFloodFromOneIpIsRejectedOncePastTheCeiling() {
SearchRateLimiter limiter = limiter(3, 1000);
assertTrue(limiter.tryAcquire("1.2.3.4"), "1st query allowed");
assertTrue(limiter.tryAcquire("1.2.3.4"), "2nd query allowed");
assertTrue(limiter.tryAcquire("1.2.3.4"), "3rd query allowed (at the ceiling)");
assertFalse(limiter.tryAcquire("1.2.3.4"), "4th query rejected — over the per-minute ceiling");
assertFalse(limiter.tryAcquire("1.2.3.4"), "…and stays rejected");
}
@Test
void limitsArePerKeyNotGlobal() {
SearchRateLimiter limiter = limiter(1, 1000);
assertTrue(limiter.tryAcquire("10.0.0.1"), "first IP's single allowance");
assertFalse(limiter.tryAcquire("10.0.0.1"), "first IP is now over its limit");
assertTrue(limiter.tryAcquire("10.0.0.2"), "a DIFFERENT IP has its own independent bucket");
}
@Test
void theHourWindowAlsoRejects() {
SearchRateLimiter limiter = limiter(1000, 2);
assertTrue(limiter.tryAcquire("9.9.9.9"));
assertTrue(limiter.tryAcquire("9.9.9.9"));
assertFalse(limiter.tryAcquire("9.9.9.9"), "the per-hour ceiling rejects even under the minute ceiling");
}
@Test
void aZeroCeilingDisablesTheWindow() {
SearchRateLimiter limiter = limiter(0, 0); // both windows off
for (int i = 0; i < 1000; i++) {
assertTrue(limiter.tryAcquire("5.5.5.5"), "a 0 ceiling means 'no limit' — never rejects");
}
}
@Test
void aBlankKeyAlwaysPasses() {
SearchRateLimiter limiter = limiter(1, 1);
assertTrue(limiter.tryAcquire(""), "a blank id has no bucket to count against");
assertTrue(limiter.tryAcquire(null));
assertTrue(limiter.tryAcquire(""), "…and still passes");
}
private static SearchRateLimiter limiter(int perMinute, int perHour, MutableClock clock, int maxKeys) {
SearchProperties.RateLimit cfg = new SearchProperties.RateLimit();
cfg.setPerIpPerMinute(perMinute);
cfg.setPerIpPerHour(perHour);
return new SearchRateLimiter(cfg, clock, maxKeys);
}
@Test
void theMinuteWindowRestartsAfterAMinute() {
MutableClock clock = new MutableClock();
SearchRateLimiter limiter = limiter(2, 1000, clock, 100);
assertTrue(limiter.tryAcquire("1.1.1.1"));
assertTrue(limiter.tryAcquire("1.1.1.1"));
assertFalse(limiter.tryAcquire("1.1.1.1"), "over the minute ceiling");
clock.advance(Duration.ofSeconds(59));
assertFalse(limiter.tryAcquire("1.1.1.1"), "still the same minute window");
clock.advance(Duration.ofSeconds(1));
assertTrue(limiter.tryAcquire("1.1.1.1"), "a minute after the window opened it restarts");
}
@Test
void theHourWindowRestartsAfterAnHourButNotAfterAMinute() {
MutableClock clock = new MutableClock();
SearchRateLimiter limiter = limiter(1000, 2, clock, 100);
assertTrue(limiter.tryAcquire("2.2.2.2"));
assertTrue(limiter.tryAcquire("2.2.2.2"));
clock.advance(Duration.ofMinutes(5));
assertFalse(limiter.tryAcquire("2.2.2.2"), "the minute window restarted, the hour window did not");
clock.advance(Duration.ofMinutes(55));
assertTrue(limiter.tryAcquire("2.2.2.2"), "an hour after the window opened it restarts");
}
@Test
void theClientTableIsBoundedDroppingExpiredClientsFirst() {
MutableClock clock = new MutableClock();
SearchRateLimiter limiter = limiter(1, 1000, clock, 3);
assertTrue(limiter.tryAcquire("a"));
assertTrue(limiter.tryAcquire("b"));
clock.advance(Duration.ofHours(1));
assertTrue(limiter.tryAcquire("c"));
assertFalse(limiter.tryAcquire("c"), "c is limited");
assertTrue(limiter.tryAcquire("d"), "a fourth client makes room by dropping the expired a and b");
assertEquals(2, limiter.trackedClients(), "only the active clients c and d are kept");
assertFalse(limiter.tryAcquire("c"), "an active client's window survives the clean-up");
}
@Test
void aFullTableOfActiveClientsIsEmptiedRatherThanGrown() {
MutableClock clock = new MutableClock();
SearchRateLimiter limiter = limiter(1, 1000, clock, 2);
assertTrue(limiter.tryAcquire("a"));
assertTrue(limiter.tryAcquire("b"));
assertTrue(limiter.tryAcquire("c"), "no client expired: the table restarts (fails open), it never grows");
assertEquals(1, limiter.trackedClients());
assertTrue(limiter.tryAcquire("a"), "a's window restarted with the table");
}
}
@@ -0,0 +1,96 @@
package mx.quest.search;
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.util.List;
import org.junit.jupiter.api.Test;
/**
* The snippet builder — the security-critical class. It must honour the frozen {@link mx.quest.search.spi.SearchHit}
* snippet contract: escape EVERY source character and leave {@code <mark>…</mark>} — and nothing else — as raw
* markup. These tests prove the highlight works AND that adversarial page text cannot forge a tag (XSS-safe).
*/
class SearchSnippetTest {
@Test
void blankInputYieldsEmpty() {
assertEquals("", SearchSnippet.build("", List.of("x"), 160));
assertEquals("", SearchSnippet.build(null, List.of("x"), 160));
assertEquals("", SearchSnippet.build(" ", List.of("x"), 160));
}
@Test
void aHitIsWrappedInMarkAndTheGapIsPlainEscapedText() {
String out = SearchSnippet.build("the quick brown fox", List.of("brown"), 160);
assertTrue(out.contains("<mark>brown</mark>"), "the matched term is wrapped in <mark>");
assertTrue(out.contains("quick"), "surrounding text is preserved");
assertFalse(out.contains("<mark>quick</mark>"), "only the matched term is marked");
}
@Test
void matchingIsCaseInsensitiveButPreservesSourceCase() {
String out = SearchSnippet.build("The Runway Platform", List.of("runway"), 160);
assertTrue(out.contains("<mark>Runway</mark>"),
"the hit matches case-insensitively but the highlight preserves the source's casing");
}
@Test
void noHitFallsBackToAnEscapedLeadingSliceWithNoMark() {
String out = SearchSnippet.build("nothing relevant here", List.of("absent"), 160);
assertFalse(out.contains("<mark>"), "no term present ⇒ no highlight");
assertTrue(out.contains("nothing"), "…but the leading text is still shown");
}
@Test
void theWindowIsBoundedByLength() {
String text = "x ".repeat(200) + "needle " + "y ".repeat(200);
String out = SearchSnippet.build(text, List.of("needle"), 50);
assertTrue(out.contains("<mark>needle</mark>"), "the window is centred on the hit");
// The raw source is ~1200 chars; the snippet is a ~50-char window plus ellipses/markup.
assertTrue(out.length() < 120, "the snippet is a small window, not the whole document: " + out.length());
}
// --- XSS-safety proof: adversarial page text --------------------------------------------------
@Test
void adversarialSourceIsFullyEscapedAndCannotForgeATag() {
// The page body is hostile: a script tag, quotes, and a FORGED <mark> the attacker planted, all around
// the real query term. The engine's escape-then-mark must neutralize every one of these. The term leads
// so the whole payload sits inside the snippet window (windowing is centred on the first hit).
String hostile = "runway <script>alert('xss')</script> \"quoted\" <mark>forged</mark> tail";
String out = SearchSnippet.build(hostile, List.of("runway"), 400);
// 1. The engine's OWN highlight is present and raw (this is the only allowed raw markup).
assertTrue(out.contains("<mark>runway</mark>"), "the real hit is highlighted");
// 2. Every hostile construct from the SOURCE is escaped — no live tag survives.
assertFalse(out.contains("<script>"), "the source <script> is escaped, never emitted raw");
assertTrue(out.contains("&lt;script&gt;"), "…it appears as escaped text");
assertFalse(out.contains("</script>"), "the closing script tag is escaped too");
assertTrue(out.contains("&quot;") || out.contains("&#39;"), "quotes from the source are escaped");
// 3. The attacker's FORGED <mark> is escaped — it must NOT become a real tag. Only the ENGINE's own
// <mark> around the query term is raw. So the only raw "<mark>" in the output is the highlighted hit.
assertFalse(out.contains("<mark>forged</mark>"), "a <mark> planted in the source is escaped, not honoured");
assertTrue(out.contains("&lt;mark&gt;forged&lt;/mark&gt;"), "the forged mark appears as escaped text");
assertEquals(1, countOccurrences(out, "<mark>"), "exactly one RAW <mark> — the engine's own highlight");
assertEquals(1, countOccurrences(out, "</mark>"), "and its matching raw close tag");
}
@Test
void anAmpersandInTheSourceIsEscaped() {
String out = SearchSnippet.build("Tom & Jerry meet the runway", List.of("runway"), 160);
assertTrue(out.contains("Tom &amp; Jerry"), "a literal & becomes &amp; so it can't start an entity");
assertFalse(out.contains("Tom & Jerry"), "no raw ampersand survives");
}
private static int countOccurrences(String haystack, String needle) {
int n = 0;
for (int i = haystack.indexOf(needle); i >= 0; i = haystack.indexOf(needle, i + needle.length())) {
n++;
}
return n;
}
}
@@ -0,0 +1,537 @@
package mx.quest.search;
import static mx.quest.search.Fixtures.ACME;
import static mx.quest.search.Fixtures.entry;
import static mx.quest.search.Fixtures.page;
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.time.Clock;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import mx.quest.runway.spi.model.CatalogChange;
import mx.quest.runway.spi.model.CatalogEntry;
import mx.quest.runway.spi.model.ContentRef;
import mx.quest.runway.spi.model.LocalizedUrl;
import mx.quest.runway.spi.model.SiteLifecycleEvent;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.testkit.EventDispatch;
import mx.quest.runway.spi.testkit.FakeContentCatalog;
import mx.quest.runway.spi.testkit.FakePluginSettings;
import mx.quest.runway.spi.testkit.FakeSiteServices;
import mx.quest.search.spi.SearchCorpus;
import mx.quest.search.spi.SearchHit;
import mx.quest.search.spi.SearchQuery;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* The built-in full-text engine over the {@link SearchCorpus}: title/description/body matching, configurable
* ranking weights, the per-site exclude list (applied by the corpus), limiting, highlighted snippets that honour the
* frozen {@link SearchHit} snippet contract, the item's real URL in its primary locale, and freshness — every change
* the kernel delivers to the plugin's listener drops the index, and a build that raced an invalidation is not kept.
*/
class SimpleSearchEngineTest {
private FakeContentCatalog catalog;
private FakePluginSettings settings;
private final Map<String, Object> config = new HashMap<>();
private SimpleSearchEngine engine;
private EventDispatch events;
@BeforeEach
void setUp() {
catalog = new FakeContentCatalog().site("acme");
settings = new FakePluginSettings();
applySettings();
FakeSiteServices kernel = new FakeSiteServices().site(ACME);
engine = new SimpleSearchEngine(new SiteSearchCorpus(catalog, settings), kernel, settings,
new SearchProperties());
events = new EventDispatch("search", Set.of())
.listener(new SearchSiteEvents(engine, new NoResultsLog(new Fixtures.NoFiles(), settings,
Clock.systemUTC(), false)));
}
private void applySettings() {
settings.site("acme", config);
}
private void corpus(CatalogEntry... entries) {
catalog.clear("acme");
for (CatalogEntry e : entries) {
catalog.entry("acme", e);
}
}
private List<SearchHit> search(String q, int limit) {
return engine.search(new SearchQuery("acme", q, Locale.ENGLISH, limit));
}
@Test
void keyAndPriorityAndAvailability() {
assertEquals("search/simple", engine.key());
assertEquals(0, engine.priority());
assertTrue(engine.available("acme"), "the built-in engine is always available (no external index)");
}
@Test
void matchesTitleAndDescriptionAndLinksToThePage() {
corpus(page("guide", "Runway Guide", "How to deploy Runway."), page("about", "About Us", "Our team."));
List<SearchHit> hits = search("runway", 20);
assertEquals(1, hits.size());
assertEquals("Runway Guide", hits.get(0).title());
assertEquals("/guide", hits.get(0).url(), "the hit links to the entry's host-computed URL");
assertFalse(hits.get(0).snippet().isBlank(), "the description becomes the snippet");
}
@Test
void aBodyOnlyTermIsFound() {
// Neither title nor description carry "kestrel"; only the indexable material does — fetched through
// the corpus (the catalog's capability-gated seam) and stripped of markup before indexing.
CatalogEntry post = page("post", "Blog", "Latest news.");
corpus(post);
catalog.text("acme", post.compositeId(), "<p>The <b>kestrel</b> is a small falcon seen over the runway.</p>");
List<SearchHit> hits = search("kestrel", 20);
assertEquals(1, hits.size(), "a term present only in the body is found");
assertEquals("Blog", hits.get(0).title());
}
@Test
void bodyScriptAndStyleAreNotIndexed() {
CatalogEntry p = page("p", "Page", "");
corpus(p);
catalog.text("acme", p.compositeId(),
"<style>.x{color:secretword}</style><script>var secretword=1;</script><p>hello</p>");
assertTrue(search("secretword", 20).isEmpty(), "text inside <script>/<style> is code, not indexable prose");
assertEquals(1, search("hello", 20).size(), "visible prose is indexed");
}
@Test
void aContentSourceItemIsIndexedAlongsidePages() {
CatalogEntry blogEntry = entry("blog", "hello-world", "Hello World", "The first entry.");
corpus(page("guide", "Runway Guide", "Deploy runway."), blogEntry);
catalog.text("acme", blogEntry.compositeId(), "Runway makes multi-tenant hosting simple.");
List<SearchHit> hits = search("runway", 20);
assertEquals(2, hits.size(), "the blog entry and the page are both indexed");
assertTrue(hits.stream().anyMatch(h -> h.url().equals("/hello-world")),
"the entry's hit links to the entry's own URL");
}
@Test
void anItemMissingFromTheDefaultLanguageLinksToItsRealUrlAndIndexesThatLanguage() {
// n6: an item that exists only in Spanish on an English-default site. 1.x linked "/solo" (the unprefixed
// default-language path, a 404); 2.0 links the item's real Spanish URL and reads its Spanish text.
SiteView bilingual = new SiteView("acme", "Acme", Locale.ENGLISH,
List.of(Locale.ENGLISH, Locale.of("es")), null);
FakeSiteServices kernel = new FakeSiteServices().site(bilingual);
SearchCorpus base = new SiteSearchCorpus(catalog, settings);
SearchCorpus spanishText = new SearchCorpus() { // the source only has a body in the item's own language
@Override
public List<CatalogEntry> corpus(String siteId) {
return base.corpus(siteId);
}
@Override
public String indexableText(String siteId, CatalogEntry entry, Locale locale) {
return locale.getLanguage().equals("es") ? base.indexableText(siteId, entry, locale) : "";
}
@Override
public void refresh(String siteId) {
base.refresh(siteId);
}
};
engine = new SimpleSearchEngine(spanishText, kernel, settings, new SearchProperties());
// A stray English title in the map must not win: the item is not available in English.
ContentRef ref = new ContentRef("solo", "/solo", Map.of("es", "/solo-es"), List.of(Locale.of("es")),
Map.of("en", "Stray English", "es", "Guía de pista"), Map.of("es", "Solo en español."), "", "tpl",
true, Instant.EPOCH, false, null, null, Map.of());
CatalogEntry solo = new CatalogEntry("pages", ref,
List.of(new LocalizedUrl(Locale.of("es"), "/es/solo-es", null)), "/es/solo-es");
corpus(solo);
catalog.text("acme", solo.compositeId(), "<p>contenido mariposa</p>");
List<SearchHit> hits = search("mariposa", 20);
assertEquals(1, hits.size(), "the Spanish body is indexed");
assertEquals("/es/solo-es", hits.get(0).url(), "the hit links the item's real (Spanish) URL, not /solo");
assertEquals("Guía de pista", hits.get(0).title());
}
// --- one document per item and language (2.2.0) ----------------------------------------------------------
private static final Locale ES = Locale.of("es");
private static final Locale FR = Locale.FRENCH;
/**
* A trilingual site (English default) whose corpus returns each language's own body — what the kernel's rendered
* pages give since 1.0.0-rc6, where a page's copy comes from the site's bundles in the requested language.
*/
private void trilingual(Map<String, Map<String, String>> bodiesById) {
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH, ES, FR), null);
SearchCorpus base = new SiteSearchCorpus(catalog, settings);
SearchCorpus perLanguage = new SearchCorpus() {
@Override
public List<CatalogEntry> corpus(String siteId) {
return base.corpus(siteId);
}
@Override
public String indexableText(String siteId, CatalogEntry entry, Locale locale) {
return bodiesById.getOrDefault(entry.ref().id(), Map.of()).getOrDefault(locale.getLanguage(), "");
}
@Override
public void refresh(String siteId) {
base.refresh(siteId);
}
};
engine = new SimpleSearchEngine(perLanguage, new FakeSiteServices().site(site), settings,
new SearchProperties());
}
private static CatalogEntry about() {
ContentRef ref = new ContentRef("about", "/about", Map.of("es", "/acerca", "fr", "/a-propos"),
List.of(Locale.ENGLISH, ES, FR), Map.of("en", "About", "es", "Acerca", "fr", "À propos"),
Map.of(), "", "tpl", true, Instant.EPOCH, false, null, null, Map.of());
return new CatalogEntry("pages", ref, List.of(new LocalizedUrl(Locale.ENGLISH, "/about", null),
new LocalizedUrl(ES, "/es/acerca", null), new LocalizedUrl(FR, "/fr/a-propos", null)), "/about");
}
private static CatalogEntry englishOnly() {
ContentRef ref = new ContentRef("news", "/news", Map.of(), List.of(Locale.ENGLISH), Map.of("en", "News"),
Map.of(), "", "tpl", true, Instant.EPOCH, false, null, null, Map.of());
return new CatalogEntry("pages", ref, List.of(new LocalizedUrl(Locale.ENGLISH, "/news", null)), "/news");
}
private List<SearchHit> search(String q, Locale locale) {
return engine.search(new SearchQuery("acme", q, locale, 20));
}
@Test
void eachLanguageSearchesItsOwnDocuments() {
trilingual(Map.of("about", Map.of("en", "<p>A roastery that stays up late.</p>",
"es", "<p>Una tostaduría que trasnocha.</p>", "fr", "<p>Une torréfaction nocturne.</p>")));
corpus(about());
List<SearchHit> es = search("trasnocha", ES);
assertEquals(1, es.size(), "the Spanish text is searchable from a Spanish results page");
assertEquals("/es/acerca", es.get(0).url(), "the hit links the Spanish address");
assertEquals("Acerca", es.get(0).title(), "the Spanish title");
assertTrue(es.get(0).snippet().contains("<mark>trasnocha</mark>"), es.get(0).snippet());
List<SearchHit> fr = search("torréfaction", FR);
assertEquals(1, fr.size());
assertEquals("/fr/a-propos", fr.get(0).url());
assertTrue(search("trasnocha", Locale.ENGLISH).isEmpty(), "English searches the English document only");
assertTrue(search("roastery", ES).isEmpty(), "Spanish searches the Spanish document only");
assertEquals("/about", search("roastery", Locale.ENGLISH).get(0).url());
}
@Test
void anItemMissingFromTheQueryLanguageIsFoundInItsPrimaryLanguage() {
trilingual(Map.of("about", Map.of("es", "<p>tostaduría</p>"), "news", Map.of("en", "<p>harvest report</p>")));
corpus(about(), englishOnly());
List<SearchHit> hits = search("harvest", ES);
assertEquals(1, hits.size(), "a page the site publishes in English only is still found from Spanish");
assertEquals("/news", hits.get(0).url(), "…at its English address, the only one it has");
assertEquals(1, search("tostaduría", ES).size(), "the view also holds the Spanish documents");
}
@Test
void aLanguageTheSiteDoesNotSpeakSearchesTheDefaultLanguage() {
trilingual(Map.of("about", Map.of("en", "<p>roastery</p>", "es", "<p>tostaduría</p>")));
corpus(about());
List<SearchHit> hits = search("roastery", Locale.GERMAN);
assertEquals(1, hits.size());
assertEquals("/about", hits.get(0).url());
}
@Test
void aSearchFromInsideTheSitesOwnIndexBuildAnswersNothingInsteadOfRecursing() {
SearchCorpus base = new SiteSearchCorpus(catalog, settings);
SimpleSearchEngine[] self = new SimpleSearchEngine[1];
java.util.concurrent.atomic.AtomicInteger inner = new java.util.concurrent.atomic.AtomicInteger(-1);
SearchCorpus reentrant = new SearchCorpus() { // a page whose widget searches while it is being rendered
@Override
public List<CatalogEntry> corpus(String siteId) {
return base.corpus(siteId);
}
@Override
public String indexableText(String siteId, CatalogEntry entry, Locale locale) {
inner.set(self[0].search(new SearchQuery("acme", "kestrel", locale, 5)).size());
return "<p>kestrel</p>";
}
@Override
public void refresh(String siteId) {
base.refresh(siteId);
}
};
engine = new SimpleSearchEngine(reentrant, new FakeSiteServices().site(ACME), settings, new SearchProperties());
self[0] = engine;
corpus(page("p", "Page", ""));
assertEquals(1, search("kestrel", 20).size(), "the outer search is answered");
assertEquals(0, inner.get(), "the search from inside the build answered nothing (and did not recurse)");
}
@Test
void theDocumentCountCountsItemsNotLanguages() {
trilingual(Map.of());
corpus(about(), englishOnly());
assertEquals(2, engine.documentCount("acme"));
assertEquals(2, engine.reindex("acme"));
}
@Test
void aTitleMatchOutranksADescriptionOnlyMatch() {
corpus(page("mention", "Pricing", "We also mention runway here."), page("titled", "Runway", "Nothing."));
List<SearchHit> hits = search("runway", 20);
assertEquals(2, hits.size());
assertEquals("Runway", hits.get(0).title(), "the title match ranks first (higher weight)");
}
@Test
void rankingWeightsChangeTheOrder() {
corpus(page("t", "Runway", "plain."), // term in TITLE only
page("d", "Plain", "runway runway runway.")); // term x3 in DESCRIPTION only
assertEquals("Runway", search("runway", 20).get(0).title(), "with defaults the title match leads");
// Flip the weights so a description match is worth far more than a title match: the order reverses.
// Zero the phrase bonuses so this isolates the title-vs-description WEIGHT.
config.put("titleWeight", 1);
config.put("descriptionWeight", 100);
config.put("phraseTitleBonus", 0);
config.put("phraseBodyBonus", 0);
applySettings();
assertEquals("Plain", search("runway", 20).get(0).title(),
"raising descriptionWeight above titleWeight makes the description-only match rank first");
}
@Test
void theAllTermsBonusRewardsAPageWithEveryTerm() {
corpus(page("both", "Alpha", "beta"), page("one", "Alpha alpha", ""));
config.put("titleWeight", 10);
config.put("descriptionWeight", 1);
config.put("phraseTitleBonus", 0);
config.put("allTermsBonus", 0);
applySettings();
// Without the bonus both score 10 (alpha in the title) + 1 for "both" (beta in the description): "both" leads
// by a hair; with a big bonus it leads by far — and a page missing a term never gets it.
List<SearchHit> plain = search("alpha beta", 20);
config.put("allTermsBonus", 1000);
applySettings();
List<SearchHit> bonus = search("alpha beta", 20);
assertEquals("Alpha", bonus.get(0).title());
assertEquals(plain.get(0).score() + 1000, bonus.get(0).score(), 0.0001, "the bonus is added once");
assertEquals(plain.get(1).score(), bonus.get(1).score(), 0.0001, "a page missing a term gets no bonus");
}
@Test
void anExcludedIdIsAbsentFromResults() {
corpus(page("privacy", "Privacy", "Runway privacy policy."), page("guide", "Runway Guide", "Deploy runway."));
config.put("exclude", List.of("/Privacy")); // leading slash and case tolerated
applySettings();
List<SearchHit> hits = search("runway", 20);
assertEquals(1, hits.size(), "the excluded item is dropped from the index");
assertEquals("Runway Guide", hits.get(0).title());
assertEquals(1, engine.documentCount("acme"));
}
@Test
void theExcludeListMatchesASourceItemsOwnId() {
CatalogEntry blogEntry = entry("blog", "hello-world", "Runway Hello", "About runway.");
corpus(page("guide", "Runway Guide", "Deploy runway."), blogEntry);
config.put("exclude", "hello-world"); // a comma/newline string works as well as a list
applySettings();
List<SearchHit> hits = search("runway", 20);
assertEquals(1, hits.size(), "the excluded blog entry is dropped");
assertEquals("Runway Guide", hits.get(0).title());
}
@Test
void nonMatchesReturnNothing() {
corpus(page("live", "Contact", "Reach us."));
assertTrue(search("runway", 20).isEmpty(), "'contact' has no 'runway'");
}
@Test
void theResultLimitIsHonored() {
corpus(page("a", "Runway A", ""), page("b", "Runway B", ""), page("c", "Runway C", ""));
assertEquals(2, search("runway", 2).size());
}
@Test
void aBlankQueryFindsNothing() {
corpus(page("a", "Runway", ""));
assertTrue(search(" ", 20).isEmpty());
}
@Test
void anUnknownSiteHasAnEmptyIndex() {
catalog.entry("other", page("a", "Runway", ""));
assertTrue(engine.search(new SearchQuery("other", "runway", Locale.ENGLISH, 20)).isEmpty(),
"a site Sites does not know has nothing to search");
}
@Test
void eachHitCarriesTheWholeWordsItsTermsMatched() {
corpus(page("mba", "Maestrías", "La maestría ejecutiva"), page("other", "Contacto", "Escríbenos"));
List<SearchHit> hits = search("maestr", 20);
assertEquals(1, hits.size());
assertEquals(List.of("maestrías", "maestría"), hits.get(0).terms(),
"the words around the match, title first, so the target page can highlight them");
}
@Test
void theSnippetHonoursLengthAndWrapsHitsInMark() {
String longDescription = "Alpha ".repeat(30) + "runway tail " + "omega ".repeat(30);
corpus(page("p", "Page", longDescription));
config.put("snippetLength", 60);
applySettings();
List<SearchHit> hits = search("runway", 20);
assertEquals(1, hits.size());
String snippet = hits.get(0).snippet();
assertTrue(snippet.contains("<mark>runway</mark>"), "the matched term is wrapped in <mark>");
assertTrue(snippet.length() < longDescription.length(), "the snippet is a bounded window, not the whole text");
assertTrue(snippet.contains("…"), "a windowed snippet shows an ellipsis");
}
@Test
void reindexRebuildsFromCurrentContentAndRefreshesTheListing() {
corpus(page("a", "Runway", ""));
assertEquals(1, engine.documentCount("acme"));
corpus(page("a", "Runway", ""), page("b", "Runway Two", ""));
assertEquals(1, engine.documentCount("acme"), "the cached index still serves until something drops it");
assertEquals(2, engine.reindex("acme"), "reindex rebuilds from the now-larger corpus");
assertEquals(List.of("acme"), catalog.refreshed(),
"reindex refreshes the kernel's listing first: it exists for changes no event announced");
}
@Test
void aPageChangeDropsTheSiteIndexImmediately() {
corpus(page("a", "Runway", ""));
assertEquals(1, search("runway", 20).size());
corpus(page("a", "Runway", ""), page("b", "Runway Two", ""));
assertEquals(1, search("runway", 20).size(), "before any event the cached index still serves");
events.page("acme", "b", List.of(), List.of());
assertEquals(2, search("runway", 20).size(), "the change drops the index; the next query rebuilds");
}
@Test
void aContentChangeDropsTheSiteIndexImmediately() {
corpus(entry("blog", "hello-world", "Runway Hello", ""));
assertEquals(1, search("runway", 20).size());
corpus(entry("blog", "hello-world", "Runway Hello", ""), entry("blog", "second", "Runway Second", ""));
events.catalog(new CatalogChange("acme", CatalogChange.Cause.CONTENT, "blog", "second", "blog",
List.of(), List.of(), true));
assertEquals(2, search("runway", 20).size(), "a content source's change drops the index too");
}
@Test
void anyPluginsSettingsSaveDropsTheSiteIndex() {
// A content source reshapes its corpus from its own settings (disable the blog, change its URL prefix);
// the engine must drop its index on any plugin's settings save, not only its own.
corpus(entry("blog", "hello-world", "Runway Hello", ""));
assertEquals(1, search("runway", 20).size());
corpus();
events.settings("acme", "blog");
assertTrue(search("runway", 20).isEmpty(), "the blog's settings change dropped the index");
}
@Test
void theExcludeListTakesEffectOnTheSettingsSave() {
corpus(page("privacy", "Runway Privacy", ""), page("guide", "Runway Guide", ""));
assertEquals(2, search("runway", 20).size());
config.put("exclude", List.of("privacy"));
applySettings();
events.settings("acme", "search");
assertEquals(1, search("runway", 20).size(), "this plugin's own save drops the index; exclusion applies");
}
@Test
void aSiteLifecycleChangeDropsTheSiteIndex() {
corpus(page("a", "Runway", ""));
assertEquals(1, search("runway", 20).size());
corpus(page("a", "Runway", ""), page("b", "Runway Two", ""));
events.lifecycle("acme", SiteLifecycleEvent.Kind.RESTORED, true);
assertEquals(2, search("runway", 20).size(), "a backup restore replaced content — the index rebuilt");
assertTrue(events.failures().isEmpty(), "no callback failed: " + events.failures());
}
@Test
void anIndexBuiltWhileAChangeArrivedIsServedButNotKept() {
// A query builds the index; while it reads the corpus, a change is delivered (another thread in production).
// The build may have read the old state, so it must not be cached: the next query rebuilds.
SearchCorpus base = new SiteSearchCorpus(catalog, settings);
int[] builds = {0};
SimpleSearchEngine[] self = new SimpleSearchEngine[1];
SearchCorpus racing = new SearchCorpus() {
@Override
public List<CatalogEntry> corpus(String siteId) {
builds[0]++;
List<CatalogEntry> read = base.corpus(siteId);
if (builds[0] == 1) {
self[0].invalidate(siteId); // the change lands mid-build
}
return read;
}
@Override
public String indexableText(String siteId, CatalogEntry entry, Locale locale) {
return base.indexableText(siteId, entry, locale);
}
@Override
public void refresh(String siteId) {
base.refresh(siteId);
}
};
self[0] = new SimpleSearchEngine(racing, new FakeSiteServices().site(ACME), settings, new SearchProperties());
corpus(page("a", "Runway", ""));
assertEquals(1, self[0].documentCount("acme"), "the raced build still answers its own caller");
assertEquals(1, self[0].documentCount("acme"));
assertEquals(1, self[0].documentCount("acme"));
assertEquals(2, builds[0], "the raced build was not cached; the next one was, and is then served from cache");
}
@Test
void theIndexCacheIsBounded() {
FakeSiteServices kernel = new FakeSiteServices();
int[] reads = {0};
SearchCorpus counting = new SearchCorpus() {
@Override
public List<CatalogEntry> corpus(String siteId) {
reads[0]++;
return List.of();
}
@Override
public String indexableText(String siteId, CatalogEntry entry, Locale locale) {
return "";
}
@Override
public void refresh(String siteId) {
}
};
for (int i = 0; i <= SimpleSearchEngine.MAX_SITE_INDEXES; i++) {
kernel.site(new SiteView("s" + i, "S", Locale.ENGLISH, List.of(Locale.ENGLISH), null));
}
SimpleSearchEngine bounded = new SimpleSearchEngine(counting, kernel, settings, new SearchProperties());
for (int i = 0; i <= SimpleSearchEngine.MAX_SITE_INDEXES; i++) {
bounded.documentCount("s" + i);
}
int afterFill = reads[0];
bounded.documentCount("s" + SimpleSearchEngine.MAX_SITE_INDEXES);
assertEquals(afterFill, reads[0], "the most recent site is cached");
bounded.documentCount("s0");
assertEquals(afterFill + 1, reads[0], "the least recently used site was dropped past the bound");
}
}
@@ -0,0 +1,152 @@
package mx.quest.search;
import static mx.quest.search.Fixtures.entry;
import static mx.quest.search.Fixtures.page;
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.time.Instant;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import mx.quest.runway.spi.model.CatalogEntry;
import mx.quest.runway.spi.model.ContentRef;
import mx.quest.runway.spi.model.LocalizedUrl;
import mx.quest.runway.spi.testkit.FakeContentCatalog;
import mx.quest.runway.spi.testkit.FakePluginSettings;
import mx.quest.search.spi.SearchCorpus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* The published {@link SearchCorpus}: the kernel's listing minus the site's {@code exclude} list, matched on the
* item's own id (case and a leading slash ignored), read fresh on every call; indexable text withheld for an excluded
* entry; {@code refresh} reaching the kernel's listing; and the input rules of the service tier.
*/
class SiteSearchCorpusTest {
private FakeContentCatalog catalog;
private FakePluginSettings settings;
private SearchCorpus corpus;
private final CatalogEntry guide = page("guide", "Guide", "");
private final CatalogEntry privacy = page("legal/privacy", "Privacy", "");
private final CatalogEntry post = entry("blog", "Hello-World", "Hello", "");
@BeforeEach
void setUp() {
catalog = new FakeContentCatalog().entry("acme", guide).entry("acme", privacy).entry("acme", post)
.text("acme", guide.compositeId(), "guide body").text("acme", privacy.compositeId(), "secret body");
settings = new FakePluginSettings();
corpus = new SiteSearchCorpus(catalog, settings);
}
@Test
void withNoExclusionsTheCorpusIsTheListingInItsOrder() {
assertEquals(List.of(guide, privacy, post), corpus.corpus("acme"));
}
@Test
void anExcludedIdIsLeftOutIgnoringCaseAndALeadingSlash() {
settings.site("acme", Map.of("exclude", List.of(" /Legal/Privacy ", "hello-world")));
assertEquals(List.of(guide), corpus.corpus("acme"),
"a page by its slug and a source item by its own id; never the composite form");
}
// --- the results page (2.1.1) -----------------------------------------------------------------------------
private static CatalogEntry localizedPage(String slug, String enPath, String esPath) {
ContentRef ref = new ContentRef(slug, enPath, Map.of(), List.of(Locale.ENGLISH, Locale.forLanguageTag("es")),
Map.of("en", "Search", "es", "Buscar"), Map.of("en", "", "es", ""), "", "tpl", true, Instant.EPOCH,
false, null, null, Map.of());
return new CatalogEntry("pages", ref, List.of(new LocalizedUrl(Locale.ENGLISH, enPath, null),
new LocalizedUrl(Locale.forLanguageTag("es"), esPath, null)), enPath);
}
@Test
void theSitesResultsPageIsNeverInItsOwnResults() {
CatalogEntry results = page("search", "Search", "Search our programs: maestrías, MBA");
catalog.entry("acme", results);
assertEquals(List.of(guide, privacy, post), corpus.corpus("acme"), "the default resultsPath is /search");
assertEquals("", corpus.indexableText("acme", results, Locale.ENGLISH), "and none of its text is offered");
}
@Test
void theResultsPageFollowsTheSettingInAnyCaseAndWithATrailingSlash() {
CatalogEntry results = page("search-results", "Results", "");
CatalogEntry search = page("search", "Search", "");
catalog.entry("acme", results).entry("acme", search);
settings.site("acme", Map.of("resultsPath", " /Search-Results/ "));
assertEquals(List.of(guide, privacy, post, search), corpus.corpus("acme"),
"the configured page leaves; a page that merely sits at /search stays");
}
@Test
void aResultsPageLeavesWithAllItsLanguages() {
CatalogEntry results = localizedPage("search", "/search", "/es/buscar");
catalog.entry("acme", results);
settings.site("acme", Map.of("resultsPath", "/es/buscar"));
assertEquals(List.of(guide, privacy, post), corpus.corpus("acme"),
"one of its addresses is the results path, so the page leaves in every language");
}
@Test
void aRootResultsPathNeverExcludesTheHomePageAndOnlyPagesCanBeTheResultsPage() {
CatalogEntry home = localizedPage("home", "/", "/es");
CatalogEntry item = entry("blog", "search", "A post called search", "");
catalog.entry("acme", home).entry("acme", item);
settings.site("acme", Map.of("resultsPath", "/"));
assertEquals(5, corpus.corpus("acme").size(), "resultsPath / leaves the home page in");
settings.site("acme", Map.of());
assertTrue(corpus.corpus("acme").contains(item), "a content-source item at /search is not the results page");
}
@Test
void theCompositeFormDoesNotMatch() {
settings.site("acme", Map.of("exclude", List.of("pages:guide")));
assertEquals(3, corpus.corpus("acme").size(), "only the item's own id is matched");
}
@Test
void aCommaOrNewlineSeparatedStringWorksToo() {
settings.site("acme", Map.of("exclude", "guide,\nlegal/privacy"));
assertEquals(List.of(post), corpus.corpus("acme"));
}
@Test
void theSettingIsReadOnEveryCall() {
assertEquals(3, corpus.corpus("acme").size());
settings.site("acme", Map.of("exclude", List.of("guide")));
assertEquals(2, corpus.corpus("acme").size(), "nothing is cached on the plugin side");
}
@Test
void indexableTextIsWithheldForAnExcludedEntry() {
assertEquals("guide body", corpus.indexableText("acme", guide, Locale.ENGLISH));
settings.site("acme", Map.of("exclude", List.of("legal/privacy")));
assertEquals("", corpus.indexableText("acme", privacy, Locale.ENGLISH),
"a consumer holding a stale entry cannot read an excluded item's text");
assertEquals("guide body", corpus.indexableText("acme", guide, Locale.ENGLISH));
}
@Test
void refreshDropsTheKernelsListing() {
corpus.refresh("acme");
assertEquals(List.of("acme"), catalog.refreshed());
}
@Test
void anUnknownSiteIsEmptyAndAnUnsafeIdIsRefused() {
assertTrue(corpus.corpus("nobody").isEmpty());
assertThrows(IllegalArgumentException.class, () -> corpus.corpus("../acme"));
assertThrows(IllegalArgumentException.class, () -> corpus.refresh("a/b"));
assertThrows(NullPointerException.class, () -> corpus.indexableText("acme", null, Locale.ENGLISH));
}
@Test
void theCorpusIsUnmodifiable() {
settings.site("acme", Map.of("exclude", List.of("guide")));
List<CatalogEntry> list = corpus.corpus("acme");
assertThrows(UnsupportedOperationException.class, () -> list.add(guide));
}
}
@@ -0,0 +1,22 @@
// The page script's word pattern (static/highlight.js) on the cases Java and the browser fold differently.
// Run: node src/test/js/highlight-pattern.js static/highlight.js (verify-against-host.sh runs it when node is present)
const fs = require('fs');
const src = fs.readFileSync(process.argv[2], 'utf8');
const esc = src.match(/function escapeRegExp[\s\S]*?\n }\n/)[0];
const pat = src.match(/function pattern[\s\S]*?\n }\n/)[0];
const pattern = new Function(esc + pat + 'return pattern;')();
const javaLower = 'İstanbul'.toLowerCase(); // JS gives i̇stanbul too
const cases = [
[[javaLower], 'Visit İstanbul and istanbul.', 2],
[['istanbul'], 'İstanbul', 1],
[['maestría'], 'MAESTRÍA y maestrías', 1],
[["c++"], "learn c++ now", 1], // a word ending in symbols still matches whole
[['a.b'], 'a.b axb', 1],
];
let ok = true;
for (const [w, text, want] of cases) {
const got = (text.match(pattern(w)) || []).length;
console.log(JSON.stringify(w), JSON.stringify(text), got, got === want ? 'ok' : 'WANT ' + want);
if (got !== want) ok = false;
}
process.exit(ok ? 0 : 1);
@@ -0,0 +1,2 @@
/* Runway Search plugin: added to every page of a site with search highlighting on. Loads highlight.js only when the address carries the #rw-hl= marker of a search result link, now or after a hashchange. Kept tiny on purpose: it is fetched with every page. */
(function(){function l(){if(window.__rwHl||location.hash.indexOf('rw-hl=')<0)return;window.__rwHl=1;var s=document.createElement('script');s.src='/__plugin/search/static/highlight.js?v=2.3.0';document.head.appendChild(s)}l();addEventListener('hashchange',l)})();
+9
View File
@@ -0,0 +1,9 @@
/* Runway Search plugin — how the page a search result opened shows the matched words (search 2.1.0+).
Added by highlight.js before the site's own stylesheets, only when the visitor came from a result, so a site
restyles it with its own rule, e.g. ::highlight(rw-search) { background-color: #cfe2ff; }
Only colour, background and text decoration apply to a highlight; layout properties are ignored. */
/* Dark text on the yellow, set explicitly: a dark theme's light text would be unreadable on it. */
::highlight(rw-search) {
background-color: #ffe066;
color: #1a1a1a;
}
+192
View File
@@ -0,0 +1,192 @@
/* Runway Search plugin — highlights, on the page a search result opened, the words the search matched there.
Served at /__plugin/search/static/highlight.js and loaded only by highlight-loader.js (which every page of a site
with highlighting on carries), and only when the address carries the marker #rw-hl=<words> that a result link
adds (search 2.1.0+).
What it does:
- reads the words from the marker (percent-encoded, separated by spaces) on load and on every hashchange;
- highlights each whole-word occurrence, ignoring case, with the CSS Custom Highlight API: no element is added
or changed, so a site script holding references to the page's nodes is unaffected;
- looks inside the page's content slot (<main id="content">, else <main>, else <body> without its <header>,
<nav>, <footer> and <aside>), skipping scripts, styles, form fields and the search box's own results; at
most 200 occurrences;
- scrolls to the first occurrence a visitor can see (a match inside a closed tab or <details> stays highlighted
and shows when it opens);
- removes the marker from the address with history.replaceState, so a reload or a bookmark gets the plain URL.
The style is the ::highlight(rw-search) rule in highlight.css, added before the site's own stylesheets so a
site rule for ::highlight(rw-search) wins. A browser without the API (Firefox before 140, Safari before 17.2)
highlights nothing; the marker is still removed. */
(function () {
'use strict';
var KEY = 'rw-hl=';
var NAME = 'rw-search';
var MAX_RANGES = 200;
var MAX_WORDS = 20;
var SKIP = { SCRIPT: 1, STYLE: 1, NOSCRIPT: 1, TEMPLATE: 1, TEXTAREA: 1, INPUT: 1, SELECT: 1, OPTION: 1, svg: 1 };
function wordsFromHash() {
var hash = location.hash;
var at = hash.indexOf(KEY);
if (at < 0) {
return null;
}
var raw = hash.substring(at + KEY.length);
var amp = raw.indexOf('&');
if (amp >= 0) {
raw = raw.substring(0, amp);
}
var text;
try {
text = decodeURIComponent(raw);
} catch (e) {
return [];
}
var seen = {};
var words = [];
text.split(/\s+/).forEach(function (w) {
var word = w.trim().toLowerCase();
if (word && word.length <= 64 && !seen[word] && words.length < MAX_WORDS) {
seen[word] = 1;
words.push(word);
}
});
return words;
}
/** Drops the marker from the address, keeping any other fragment, without adding a history entry. */
function clearMarker() {
var hash = location.hash;
var at = hash.indexOf(KEY);
if (at < 0 || !history.replaceState) {
return;
}
var rest = hash.substring(at + KEY.length);
var amp = rest.indexOf('&');
var before = hash.substring(1, at).replace(/&$/, '');
var after = amp >= 0 ? rest.substring(amp + 1) : '';
var kept = [before, after].filter(Boolean).join('&');
try {
history.replaceState(history.state, '', location.pathname + location.search + (kept ? '#' + kept : ''));
} catch (e) {
// A document that cannot rewrite its address (about:srcdoc, blob:) still gets the highlight.
}
}
function escapeRegExp(s) {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/**
* One pattern for all words, longest first, matching only whole words (letters, digits and marks). The server
* lowercases with Java's rules, which turn the Turkish capital I with a dot into "i" plus a combining dot; the
* browser's case-insensitive match never folds that capital to anything, so every "i" also accepts it.
*/
function pattern(words) {
var alternatives = words.slice().sort(function (a, b) { return b.length - a.length; }).map(function (w) {
return escapeRegExp(w.replace(/i\u0307/g, 'i')).replace(/i/g, '[i\u0130]');
});
return new RegExp('(?<![\\p{L}\\p{N}\\p{M}])(?:' + alternatives.join('|') + ')(?![\\p{L}\\p{N}\\p{M}])', 'giu');
}
function root() {
return document.getElementById('content') || document.querySelector('main') || document.body;
}
/** Page chrome, skipped when the page has no content slot and the whole <body> is searched. */
var CHROME = { HEADER: 1, NAV: 1, FOOTER: 1, ASIDE: 1 };
function rejectNode(node, wholeBody) {
for (var el = node.parentElement; el; el = el.parentElement) {
if (SKIP[el.tagName] || SKIP[el.nodeName] || (wholeBody && CHROME[el.tagName]) || el.isContentEditable
|| (el.classList && el.classList.contains('rw-search-hits'))) {
return true;
}
}
return false;
}
function ranges(words) {
var re = pattern(words);
var found = [];
var start = root();
var wholeBody = start === document.body;
var walker = document.createTreeWalker(start, NodeFilter.SHOW_TEXT, {
acceptNode: function (node) {
return node.nodeValue.trim() && !rejectNode(node, wholeBody)
? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
}
});
var node;
while (found.length < MAX_RANGES && (node = walker.nextNode())) {
re.lastIndex = 0;
var m;
while (found.length < MAX_RANGES && (m = re.exec(node.nodeValue))) {
var range = document.createRange();
range.setStart(node, m.index);
range.setEnd(node, m.index + m[0].length);
found.push(range);
}
}
return found;
}
function visible(range) {
var el = range.startContainer.parentElement;
if (!el) {
return false;
}
if (el.checkVisibility) {
return el.checkVisibility({ visibilityProperty: true, opacityProperty: false });
}
return range.getClientRects().length > 0;
}
function addStyle() {
if (document.getElementById('rw-search-highlight-css')) {
return;
}
var link = document.createElement('link');
link.id = 'rw-search-highlight-css';
link.rel = 'stylesheet';
link.href = '/__plugin/search/static/highlight.css?v=2.3.0';
// First in <head>, so any ::highlight(rw-search) rule of the site comes later and wins.
document.head.insertBefore(link, document.head.firstChild);
}
function run() {
var words = wordsFromHash();
if (words === null) {
return;
}
clearMarker();
if (!window.CSS || !CSS.highlights || typeof Highlight === 'undefined' || !words.length) {
return;
}
addStyle();
var found = ranges(words);
CSS.highlights.delete(NAME);
if (!found.length) {
return;
}
CSS.highlights.set(NAME, new Highlight(...found));
for (var i = 0; i < found.length; i++) {
if (visible(found[i])) {
found[i].startContainer.parentElement.scrollIntoView({ block: 'center' });
break;
}
}
}
function start() {
run();
addEventListener('hashchange', run);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', start);
} else {
start();
}
})();
+82
View File
@@ -0,0 +1,82 @@
<!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>Search plugin — help &amp; reference</title>
<link rel="stylesheet" href="/__plugin/search/static/search.css">
<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>Search — help &amp; reference</h1>
<p>The Search plugin adds on-site search to your site: an embeddable, query-aware <strong>search box</strong>
(a content widget) backed by a pluggable engine. The built-in engine searches the titles, descriptions and text
of your published pages and content (entries other plugins publish, …) and needs no setup — search works the moment the plugin
is installed and enabled. A change you make in the console (a page saved, an entry published, a setting
changed) is searchable at once.</p>
<h2>Install a ready-made search results page</h2>
<p>On the Search settings page, the <strong>Search page</strong> card installs a ready-made results page (at
<code>/search</code>) carrying the box. 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
never overwrites an existing page, and it follows your site's editorial rules: on a site whose pages need
review, the page waits in the review queue; when the quality checks block publishing, it is created as a draft
for you to fix in the page editor. The button tells you which happened.</p>
<h2>Or put a search box on any page</h2>
<p>In any page (or your master chrome), add an anchor where the box should appear:</p>
<pre>&lt;div id="site-search" data-widget="search/box"&gt;&lt;/div&gt;</pre>
<p>The <code>id</code> and <code>data-widget</code> must be on the <em>same</em> element. The box submits
<code>?q=</code> to your results page (the <strong>Results page path</strong> setting, default
<code>/search</code>). The widget is query-aware: when a page carrying it is opened with a non-blank
<code>q</code>, it renders the ranked results <em>inline below the box</em>. Everything is styled by this
plugin's stylesheet (<code>/__plugin/search/static/search.css</code>) — override any <code>.rw-search*</code>
rule from your own CSS to match your theme.</p>
<h2>Settings (per site)</h2>
<ul>
<li><strong>Enable search</strong> — turn the box (and its inline results) on or off.</li>
<li><strong>Maximum results</strong> — how many hits the results show (1–100).</li>
<li><strong>Results page path</strong> — where the box submits <code>?q=</code> (default <code>/search</code>);
change it if you move or rename the results page.</li>
<li><strong>Search box placeholder</strong> — the greyed-out prompt text in the box.</li>
<li><strong>Excluded content</strong> — pages (by their slug) and entries (by their id) that search leaves out,
one per line.</li>
<li><strong>Record searches with no results</strong> — off by default; see below.</li>
<li><strong>Keep unrepeated terms for (days)</strong> — how long a term nobody searches for again stays on
the list (default 90).</li>
</ul>
<h2>Searches with no results</h2>
<p>Turn on <strong>Record searches with no results</strong> and the settings page lists what visitors searched for
on your site and did not find — most frequent first, with how often and when it was last searched. Each entry
is a hint: a page you could add, a title or description that should mention the word visitors use, or a
redirect from an old name.</p>
<p>It is <strong>off by default</strong> because a search term is whatever a visitor typed, and people sometimes type
names, email addresses or numbers. When it is on, only the term, a count and the last time are kept — never an
IP address, a user or a session. Terms that look like an email address or a phone number are not kept at all.
Letter case and extra spaces are ignored, so "Opening&nbsp;&nbsp;Hours" and "opening hours" count together.
The list keeps at most 500 terms (the rarest make room for new ones) and forgets a term nobody has searched
for in the number of days you set. <strong>Clear list</strong> forgets everything at once; it cannot be
undone. If you turn recording off, the list stays until you clear it or its terms age out.</p>
<p>The list is kept in your site's folder, so a full backup carries it. A <strong>transfer copy</strong> of the site
(the download meant for someone outside your organisation) leaves it out, because it is what visitors typed.</p>
<h2>Rebuild the index</h2>
<p>Search notices every change made through the console by itself. If files were changed some other way (copied in
by hand), <strong>Rebuild index</strong> on the Search settings page re-reads everything now and tells you how
many items the index holds.</p>
<h2>A better engine</h2>
<p>Search is backed by a <code>SiteSearchEngine</code> extension point. Installing a companion plugin such as
<strong>search-lucene</strong> (which builds a full-text index over your page bodies) transparently upgrades
the engine — the box and the inline results are unchanged. The <em>Active engine</em> line on the Search
settings page shows which engine is serving your site.</p>
</body>
</html>
+88
View File
@@ -0,0 +1,88 @@
/* Runway Search plugin — styles for the embeddable search box and the /search results page.
Served at /__plugin/search/static/search.css. Deliberately minimal and neutral so it inherits the site's
look; a site can override any .rw-search* rule from its own stylesheet. */
.rw-search-box,
.rw-search-form {
display: flex;
gap: .5rem;
align-items: center;
max-width: 40rem;
}
.rw-search-box-input,
.rw-search-input {
flex: 1 1 auto;
padding: .5rem .75rem;
border: 1px solid #ccc;
border-radius: .375rem;
font-size: 1rem;
min-width: 0;
}
.rw-search-box-submit,
.rw-search-submit {
padding: .5rem 1rem;
border: 1px solid transparent;
border-radius: .375rem;
background: #0d6efd;
color: #fff;
cursor: pointer;
white-space: nowrap;
}
.rw-search-box-submit:hover,
.rw-search-submit:hover {
filter: brightness(.95);
}
/* Results page */
.rw-search-main {
max-width: 46rem;
margin: 2rem auto;
padding: 0 1rem;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
color: #1a1a1a;
}
.rw-search-title {
font-size: 1.5rem;
margin: 0 0 1rem;
}
.rw-search-form {
margin-bottom: 1.5rem;
}
.rw-search-count,
.rw-search-empty {
color: #555;
margin: 0 0 1rem;
}
.rw-search-hits {
list-style: none;
padding: 0;
margin: 0;
}
.rw-search-hit {
padding: .75rem 0;
border-top: 1px solid #eee;
}
.rw-search-hit-link {
font-size: 1.125rem;
text-decoration: none;
color: #0d6efd;
}
.rw-search-hit-link:hover {
text-decoration: underline;
}
.rw-search-hit-snippet {
margin: .25rem 0 0;
color: #555;
font-size: .95rem;
}
+95
View File
@@ -0,0 +1,95 @@
<!-- Admin status fragment — the filename `admin` makes the host render it below this plugin's per-tenant
settings form. Bare fragment; binding in admin.th.xml. -->
<div class="card mt-3">
<div class="card-header"><h3 class="card-title" id="sa-title">Search status</h3></div>
<div class="card-body">
<div class="datagrid">
<div class="datagrid-item">
<div class="datagrid-title" id="sa-l-status">Enabled</div>
<div class="datagrid-content"><span id="sa-status">on</span></div>
</div>
<div class="datagrid-item">
<div class="datagrid-title" id="sa-l-engine">Active engine</div>
<div class="datagrid-content"><span id="sa-engine">search/simple</span>
(<span id="sa-engines">1</span>)</div>
</div>
<div class="datagrid-item">
<div class="datagrid-title" id="sa-l-pages">Searchable items</div>
<div class="datagrid-content" id="sa-pages">0</div>
</div>
</div>
<p class="text-secondary small mt-2 mb-0" id="sa-note">
Add a search box to any page with a data-widget anchor; when a page is opened with ?q= it shows the
results inline.</p>
<!-- Rebuild the index now (every engine): a POST carrying the console's CSRF token (it changes state, so a
cross-site link must not be able to trigger it); the plain-text result opens in a new tab. -->
<div class="d-flex flex-wrap align-items-center gap-2 mt-2" id="sr-reindex">
<span class="text-secondary small" id="sr-desc">Edited files by hand? Rebuild the index now.</span>
<form id="sr-reindex-form" method="post" action="/search/reindex" target="_blank" rel="noopener"
class="m-0 ms-auto">
<input id="sr-csrf" type="hidden" name="_csrf" value="">
<button id="sr-reindex-btn" type="submit" class="btn btn-sm btn-outline-secondary">
<i class="fa-solid fa-rotate me-1"></i><span id="sr-reindex-label">Rebuild index</span></button>
</form>
</div>
<hr>
<!-- "Search page" — install a ready-made, editable results page, or show its live path (follows a move).
The install is a POST carrying the console's CSRF token (it creates a page); the plain-text result
opens in a new tab. -->
<div id="sp-install">
<p class="text-secondary" id="sp-desc">Install a ready-made search results page carrying the box. It
becomes a normal site page — edit, restyle, move or rename it from Pages.</p>
<form id="sp-install-form" method="post" action="/search/install-page" target="_blank" rel="noopener"
class="m-0">
<input id="sp-csrf" type="hidden" name="_csrf" value="">
<button id="sp-install-btn" type="submit" class="btn btn-primary">
<i class="fa-solid fa-file-circle-plus me-1"></i><span id="sp-install-label">Install search page</span></button>
</form>
</div>
<div id="sp-installed" class="d-flex align-items-center">
<span class="badge bg-success-lt me-2" id="sp-badge">Installed</span>
<span id="sp-at">Installed at</span>&nbsp;<code id="sp-path" class="ms-1">/search</code>
<span class="text-secondary ms-2" id="sp-edit">— edit it under Pages.</span>
</div>
</div>
<div class="card-footer">
<a id="sa-help" href="/__plugin/search/static/search-help.html" target="_blank" rel="noopener">
<i class="fa-solid fa-circle-question me-1"></i><span id="sa-help-label">Search help &amp; reference</span></a>
</div>
</div>
<!-- "Searches with no results" — the content-gap list (opt-in per site). Terms are VISITOR TEXT: bound with th:text
only. Clearing is a POST carrying the console session's CSRF token, so no cross-site link can trigger it. -->
<div class="card mt-3" id="nr-card">
<div class="card-header"><h3 class="card-title" id="nr-title">Searches with no results</h3></div>
<div class="card-body">
<p class="text-secondary" id="nr-intro">What visitors searched for and did not find.</p>
<div class="alert alert-info" role="alert" id="nr-off">Recording is off for this site.</div>
</div>
<div class="table-responsive">
<table class="table table-vcenter card-table" data-listing-table="search.admin.noresults">
<thead>
<tr>
<th data-col-key="term" id="nr-h-term">Search term</th>
<th data-col-key="count" id="nr-h-count" class="w-1">Searches</th>
<th data-col-key="last" id="nr-h-last" class="w-1">Last searched</th>
</tr>
</thead>
<tbody>
<tr id="nr-empty"><td colspan="3" class="text-secondary text-center" id="nr-empty-text">None yet.</td></tr>
<tr id="nr-row">
<td class="nr-term text-break">term</td>
<td class="nr-count text-end">0</td>
<td class="nr-last text-secondary text-nowrap">-</td>
</tr>
</tbody>
</table>
</div>
<div class="card-footer d-flex flex-wrap align-items-center justify-content-between gap-2">
<small class="text-secondary" id="nr-retention">Retention.</small>
<form id="nr-clear-form" method="post" action="/search/no-results/clear" class="m-0">
<input id="nr-csrf" type="hidden" name="_csrf" value="">
<button id="nr-clear" type="submit" class="btn btn-sm btn-outline-danger">
<i class="fa-solid fa-eraser me-1"></i><span id="nr-clear-label">Clear list</span></button>
</form>
</div>
</div>
+64
View File
@@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Admin fragment logic. Values from ${@searchAdminModel...(tenantSiteId)}; the on/off ternary keeps the
condition in ${} and each branch a standalone #{} (pitfall #12). -->
<thlogic>
<attr sel="#sa-title" th:text="#{search.admin.title}"/>
<attr sel="#sa-l-status" th:text="#{search.admin.enabled}"/>
<attr sel="#sa-status" th:text="${@searchAdminModel.enabled(tenantSiteId)} ? #{search.on} : #{search.off}"/>
<attr sel="#sa-l-engine" th:text="#{search.admin.engine}"/>
<attr sel="#sa-engine" th:text="${@searchAdminModel.activeEngineKey(tenantSiteId)}"/>
<attr sel="#sa-engines" th:text="${@searchAdminModel.engineCount()}"/>
<attr sel="#sa-l-pages" th:text="#{search.admin.pages}"/>
<attr sel="#sa-pages" th:text="${@searchAdminModel.searchableItems(tenantSiteId)}"/>
<attr sel="#sa-note" th:text="#{search.admin.note}"/>
<!-- Rebuild index: the form's action is the constant /search/reindex in the static markup (no th:action: the
restricted URL/attr context forbids ${@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 POST. -->
<attr sel="#sr-desc" th:text="#{search.reindex.desc}"/>
<attr sel="#sr-csrf"
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
<attr sel="#sr-reindex-btn" th:title="#{search.reindex.tip}"/>
<attr sel="#sr-reindex-label" th:text="#{search.reindex.button}"/>
<!-- "Search page" install card: exactly one block shows, gated on the live install status. The install form's
action is the constant /search/install-page in the static markup; the live path is bound with th:text
(which permits @bean). The hidden field carries the console session's CSRF token, as above. -->
<attr sel="#sp-install" th:if="${!@searchAdminModel.pageInstalled(tenantSiteId)}"/>
<attr sel="#sp-desc" th:text="#{search.page.card.desc}"/>
<attr sel="#sp-csrf"
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
<attr sel="#sp-install-btn" th:title="#{search.page.card.install.tip}"/>
<attr sel="#sp-install-label" th:text="#{search.page.card.install}"/>
<attr sel="#sp-installed" th:if="${@searchAdminModel.pageInstalled(tenantSiteId)}"/>
<attr sel="#sp-badge" th:text="#{search.page.card.badge}"/>
<attr sel="#sp-at" th:text="#{search.page.card.at}"/>
<attr sel="#sp-path" th:text="${@searchAdminModel.pagePath(tenantSiteId)}"/>
<attr sel="#sp-edit" th:text="#{search.page.card.edit}"/>
<attr sel="#sa-help-label" th:text="#{search.admin.help}"/>
<!-- "Searches with no results": the list is read ONCE into ${nr} (th:with on the card) and every row binds
visitor text with th:text only. The clear form carries the console page's CSRF token (the tenant chain
rejects the POST without it) and shows only when there is something to clear. -->
<attr sel="#nr-card" th:with="nr=${@searchAdminModel.noResults(tenantSiteId)}"/>
<attr sel="#nr-title" th:text="#{search.noresults.title}"/>
<attr sel="#nr-intro" th:text="#{search.noresults.intro}"/>
<attr sel="#nr-off" th:if="${!@searchAdminModel.noResultsRecording(tenantSiteId)}" th:text="#{search.noresults.off}"/>
<attr sel="#nr-h-term" th:text="#{search.noresults.col.term}"/>
<attr sel="#nr-h-count" th:text="#{search.noresults.col.count}"/>
<attr sel="#nr-h-last" th:text="#{search.noresults.col.lastSeen}"/>
<attr sel="#nr-card//#nr-empty" th:if="${nr.isEmpty()}"/>
<attr sel="#nr-empty-text" th:text="#{search.noresults.empty}"/>
<attr sel="#nr-card//#nr-row" th:each="e : ${nr}"/>
<attr sel="#nr-card//#nr-row//.nr-term" th:text="${e.term()}"/>
<attr sel="#nr-card//#nr-row//.nr-count" th:text="${e.count()}" th:attr="data-sort=${e.count()}"/>
<attr sel="#nr-card//#nr-row//.nr-last" th:text="${@searchAdminModel.lastSeen(e)}"/>
<attr sel="#nr-retention"
th:text="#{search.noresults.retention(${@searchAdminModel.noResultsRetentionDays(tenantSiteId)},${@searchAdminModel.noResultsMaxTerms()})}"/>
<attr sel="#nr-card//#nr-clear-form" th:if="${!nr.isEmpty()}"/>
<attr sel="#nr-csrf"
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
<attr sel="#nr-clear" th:title="#{search.noresults.clear.tip}"/>
<attr sel="#nr-clear-label" th:text="#{search.noresults.clear}"/>
</thlogic>
+18
View File
@@ -0,0 +1,18 @@
<!-- Tenant dashboard card fragment — resolved as __plugin__/search/dashboard. Bare fragment
(no <html>/<body>); all binding lives in the paired dashboard.th.xml. -->
<div class="card">
<div class="card-status-start bg-azure"></div>
<div class="card-body">
<div class="d-flex align-items-center">
<span class="bg-azure-lt avatar"><i class="fa-solid fa-magnifying-glass"></i></span>
<div class="ms-3">
<div class="fw-bold" id="sc-title">Search</div>
<div class="text-secondary small">
<span id="sc-pages">0</span> <span id="sc-pages-lbl">searchable items</span>
· <span id="sc-status">on</span>
· <span id="sc-engine">engine</span>
</div>
</div>
</div>
</div>
</div>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Dashboard card logic. Values from ${@searchAdminModel...(tenantSiteId)}; the on/off ternary keeps the
condition in ${} and each branch a standalone #{} message expression (pitfall #12 — never nest #{} in ${}). -->
<thlogic>
<attr sel="#sc-title" th:text="#{search.card.title}"/>
<attr sel="#sc-pages" th:text="${@searchAdminModel.searchableItems(tenantSiteId)}"/>
<attr sel="#sc-pages-lbl" th:text="#{search.card.pages}"/>
<attr sel="#sc-status" th:text="${@searchAdminModel.enabled(tenantSiteId)} ? #{search.on} : #{search.off}"/>
<attr sel="#sc-engine" th:text="${@searchAdminModel.activeEngineKey(tenantSiteId)}"/>
</thlogic>