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

+33
View File
@@ -0,0 +1,33 @@
# Build output
target/
*.class
# Runtime / operator-editable state (seeded into a deployment, not source)
/external/
/uploads/
/logs/
/backups/
# Safety net: surefire runs with CWD = the module dir, where the deployment-root-relative
# logs/ and backups/ defaults would otherwise land if a test forgets to redirect them.
/runway-app/logs/
/runway-app/backups/
*.pid
# Local release artifacts
*.bin
# IDE / editor
.idea/
*.iml
.vscode/
nbproject/private/
.settings/
.project
.classpath
# OS
.DS_Store
Thumbs.db
# Scratch (never commit)
tmp_do_not_commit/
+1
View File
@@ -0,0 +1 @@
-Duser.timezone=UTC
+22
View File
@@ -0,0 +1,22 @@
# Changelog
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
## [1.0.0] — 2026-10-21
The first public release of Runway: a multi-site web platform built as a small multi-tenant kernel, with every
domain feature delivered as a plugin.
- **Kernel**: sites with their own hosts, pages, templates, messages and static files; the operator console
(application and per-site realms) with the setup wizard, the page editor, roles and permissions, per-site
backups, platform mail and password recovery; optional in-app TLS termination; Prometheus metrics; an
optional cluster mode. The essential `protection` plugin (rate limiting and login protection) is bundled.
- **Plugin contract**: SPI `1.0.0`, frozen for the `1.x` line — it changes only additively
([docs/SPI-STABILITY.md](docs/SPI-STABILITY.md)). Plugin authors build against the `runway-spi` and
`runway-spi-testkit` jars attached to each release ([docs/PLUGIN-DEVELOPMENT.md](docs/PLUGIN-DEVELOPMENT.md)).
- **Public plugins** in `plugins/`, attached to this release: `runway-demo` 2.1.0 (the reference plugin, Apache-2.0),
`search` 2.3.0, `search-lucene` 3.3.0 and `lucene-provider` 10.4.0.
- **Install**: `runway-1.0.0.bin` (self-extracting installer) or `runway-1.0.0-dist.zip`, verified against
`SHA256SUMS` ([docs/ADMINISTRATION.md](docs/ADMINISTRATION.md) §3).
- **License**: GNU AGPL v3.0 with an additional permission for plugins (`LICENSE`, `LICENSE-EXCEPTION`);
third-party components are listed in `THIRD-PARTY-NOTICES`.
+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.
+149
View File
@@ -0,0 +1,149 @@
# Runway
**Runway** is a multi-site web platform — a **kernel + plugins** server: a small,
multi-tenant content/website core that ships only the essential bytes, with every domain
feature delivered as a plugin or a first-class SPI implementation.
| | |
|---|---|
| Coordinates | `mx.quest:runway` |
| Version | `1.0.0` (plugin contract: SPI `1.0.0`) — the exact version is in the root `pom.xml` and each release in [CHANGELOG.md](CHANGELOG.md) |
| Java | 25+ |
| Framework | Spring Boot 4 on embedded Jetty |
| Storage | Filesystem / YAML (no database) |
| Status | **Stable.** Semantic Versioning from `1.0.0`. The kernel, both realms, the setup wizard (with a catch-all default site), the page editor, per-site backups and optional in-app TLS termination run today; open items are in [docs/KNOWN-LIMITATIONS.md](docs/KNOWN-LIMITATIONS.md). |
## Modules
```
runway/ reactor (this pom)
├── runway-spi/ dependency-free extension API (interfaces + immutable model records)
├── runway-spi-testkit/ in-memory fakes of the SPI services, for plugins' unit tests (test scope)
├── runway-app/ the Spring Boot kernel (Jetty) — collects SPI impls + plugin contributions
├── runway-plugin-protection/ the essential protection plugin (rate-limit edge guard, login gate, CAPTCHA;
│ shipped inside the installer and seeded on a fresh install)
├── runway-dist/ packaging only: the dist zip, the self-extracting .bin installer, checksums
└── plugins/ the plugins demo, search, search-lucene, lucene-provider (not reactor modules)
```
The plugins under `plugins/` are **standalone** projects, each with its own build; one with code is built
against `runway-spi` alone as a `provided` dependency (with `runway-spi-testkit` for its tests). A plugin that links `runway-app` classes is refused at
load time — the 1.0 plugin contract is the SPI ([SPI-STABILITY.md](docs/SPI-STABILITY.md)).
## Quick start
Two audiences: **operators** install the packaged release and finish setup in the browser;
**developers** build the reactor and run the jar. Both end at the same first-run wizard.
### Operator — install the release
The Linux release is a single self-extracting `.bin` (a shell stub with the deployment
bundle appended — no `makeself`, only stock `bash`/`tar`/`gzip`). Run it as root; it is
**idempotent**, so re-running the same or a newer `.bin` upgrades in place:
```sh
sudo ./runway-<version>.bin # interactive: prompts on a TTY
sudo ./runway-<version>.bin -y # unattended, all defaults
sudo ./runway-<version>.bin -y --no-firewall # ...and never touch the host firewall
```
Get it from the releases page (<https://g.quest.mx/quest/runway/releases>) and check it against the
release's `SHA256SUMS` before running it ([Administration §3](docs/ADMINISTRATION.md)). The stable
`…/releases/latest` page and `runway-latest.bin` link serve the newest published release — install an explicit
version in production.
The installer lays the code under `/opt/runway-<version>`, points `/opt/runway` at it,
keeps editable state (`external/`, `logs/`, `backups/`) in the version-independent
`/opt/runway-data/` so upgrades never clobber it, installs a systemd unit, relabels
SELinux contexts (required on enforcing RHEL-family hosts), and starts the service.
There is **no database to configure** — Runway is filesystem/YAML-backed; first-run
configuration happens in the app's own wizard (below).
Confirm it is up:
```sh
systemctl status runway # active (running)
journalctl -u runway -f # startup log; also /opt/runway-data/logs/
```
### Developer — build and run from source
**Prerequisites:** a JDK 25+ (with `javac`) and Maven.
```sh
# build the reactor (spi + spi-testkit + app + protection plugin + dist) and run the tests
JAVA_HOME=/path/to/jdk-25 mvn -e install
# run the packaged app (the -exec jar is the runnable one; the plain jar is the
# thin library other modules compile against)
java -jar runway-app/target/runway-app-<version>-exec.jar
```
The app listens on **:8080** by default and expects its `external/`, `logs/` (and
`backups/`) folders in the working directory — run it from the deployment root, or use
the launcher `scripts/runway.sh` which `cd`s there for you.
To produce the deployment artifacts — the dist zip (`runway-<version>-dist.zip`), the `.bin`
installer (`runway-<version>.bin`), stable-named `runway-latest.*` aliases of both, the plugin author's
`runway-spi` / `runway-spi-testkit` jars with their sources jars and poms, and a `SHA256SUMS` over all of
them, landing in `runway-dist/target/`:
```sh
JAVA_HOME=/path/to/jdk-25 mvn -P dist package
```
### First access — the setup wizard
On first boot Runway comes up in **wizard mode**: it has no accounts yet, so **every URL
redirects to `/setup`**. Open the site in a browser (e.g. `http://<host>:8080/`) and you
land on the setup form. Because the surface is open before setup completes, reach it only
over localhost or behind your reverse proxy until it is done.
The wizard collects **two administrators, one per realm** — the two realms never cross
(authenticating in one never grants the other), which is why setup creates both up front:
- **Application superadmin** — runs the *platform*: creates and manages sites, plugins, and
application users. It cannot operate inside a site. This account is pinned and can never be
deleted or demoted, so there is always a way back in.
- **Default site administrator** — manages the seeded default site (a separate identity in
the *site* realm). Unbound hosts resolve to this default site.
Submit the form; Runway writes the external `application.yml` (the superadmin pin, `chmod 600`)
and **restarts into normal mode**, after which the whole wizard layer is gone. The restart is a supervised
relaunch (the JVM exits with code 42): under systemd or the launcher `scripts/runway.sh` (detached mode) it comes
back by itself; a bare `java -jar` simply exits, so start it again. Then sign in:
- **Operator console** — [`/app/login`](http://localhost:8080/app/login) (application superadmin)
- **Site management** — [`/login`](http://localhost:8080/login) (default site administrator)
To confirm setup took: once it is back up, requesting `/` no longer redirects to `/setup`,
`/opt/runway-data/external/application.yml` exists with a `runway.security.app-master-id`
line, and both login pages authenticate their respective account.
## Versioning & release cycle
Runway follows [Semantic Versioning](https://semver.org/) with a `SNAPSHOT → beta → rc →
release` lifecycle. `1.0.0` is the first stable release, with the plugin contract frozen at SPI `1.0.0`.
From `1.0.0` a breaking change costs a MAJOR. What stays compatible within a MAJOR line is in [SPI-STABILITY.md](docs/SPI-STABILITY.md) and [CONFIGURATION-AND-DATA-STABILITY.md](docs/CONFIGURATION-AND-DATA-STABILITY.md).
## Documentation
The documentation delivered with Runway lives in **[`docs/`](docs/README.md)** — start at the
[documentation index](docs/README.md). It covers:
- **[Plugin Development](docs/PLUGIN-DEVELOPMENT.md)** — for plugin authors
- **[Administration](docs/ADMINISTRATION.md)** — for the operators who install and run the platform
- **[Site Manager & Designer Guide](docs/SITE-MANAGER-GUIDE.md)** — for the people who manage a site (and designers who edit pages)
- **[Operations](docs/OPERATIONS.md)** and a **[Glossary](docs/GLOSSARY.md)**
- **[SPI stability](docs/SPI-STABILITY.md)** and **[Configuration & data stability](docs/CONFIGURATION-AND-DATA-STABILITY.md)** — what stays compatible from `1.0.0`
- **[Settings reference](docs/SETTINGS-REFERENCE.md)** — every setting, its values and default, and where it is set
- **[Known limitations](docs/KNOWN-LIMITATIONS.md)** — what Runway does not do yet
## License
Copyright (C) 2026 Quest ICT SAS de CV.
Runway is licensed under the [GNU Affero General Public License, version 3](LICENSE), with an
[additional permission for plugins](LICENSE-EXCEPTION): a plugin that interacts with Runway only through the
published SPI (`runway-spi`) may carry any license, including a proprietary one. Runway itself stays under
the AGPL: if you run a modified Runway for others over a network, you must offer them its source.
+2579
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+633
View File
@@ -0,0 +1,633 @@
# Configuration and data stability commitment
This document states what Runway promises about everything **outside** the Java API that an installation,
a backup, a plugin package or a monitoring system depends on: the `runway.*` configuration keys, the files
Runway keeps on disk, the backup archive, the plugin descriptor (`plugin.yml`), and the HTTP paths, metric
names and logger names other systems are built against. It is the counterpart of
[SPI-STABILITY.md](SPI-STABILITY.md), which covers the binary extension API.
> **Status.** These rules bind from **`1.0.0`**: this document governs, and every change to a covered
> surface is called out in the CHANGELOG ([`../CHANGELOG.md`](../CHANGELOG.md)).
## Why this exists
An operator upgrading from `1.2` to `1.5` should not have to re-read every configuration key, re-test every
backup, or rebuild a Prometheus dashboard. A plugin author should know which `plugin.yml` keys an older kernel
will understand. That needs two things: a written promise per surface, and something **on disk** that says
which version of a format a file is in, so that a later Runway can tell an old file from a new one and an
older Runway can refuse a file it cannot read instead of quietly damaging it. Two markers carry that version:
`external/layout.yml` for the data folder, and `formatVersion` in a backup's `manifest.yml`.
## What "compatible" means — the common rules
Within one **major** line (`1.x`):
1. **Nothing covered is removed or changes meaning.** A configuration key keeps its meaning, its type and its
default **unit**; a file keeps its location and the meaning of its fields; a metric keeps its name and tags.
2. **Additions are free.** New keys, new optional fields, new files, new metrics and new paths may appear in any
minor release. Each has a default that reproduces the previous behaviour.
3. **Renames and removals take a deprecation cycle.** The old name keeps working for the rest of the major line,
a startup `WARN` names the replacement, the configuration metadata marks it deprecated, and the changelog
lists it under *Deprecated*. It is removed only in the next major.
4. **Defaults may be tuned** (a larger cap, a shorter cache lifetime) when the change does not alter what a
correctly configured installation does; the changelog says so. A default that changes behaviour an operator
relies on is treated like a rename.
5. **A breaking change is a new major** (`2.0`), called out in the changelog with upgrade steps.
## 1. The `runway.*` configuration namespace
**Covered:** every key below, whether set in `external/application.yml`, as an environment variable (Spring's
relaxed binding: `RUNWAY_STORAGE_EXTERNAL` sets `runway.storage.external`), or on the command line.
**Where the list comes from.** The kernel builds `META-INF/spring-configuration-metadata.json` from its 18
`@ConfigurationProperties` classes and from
`runway-app/src/main/resources/META-INF/additional-spring-configuration-metadata.json`, which describes the
keys read through `@Value` or straight from the environment (the demo installer, two size caps, the plugin
root and the node name). An IDE uses the same file for completion and type checks. A test
(`ConfigurationMetadataTest`) fails the build if a key named in the shipped `application.yml`, or one of the
`@Value`/environment keys, is missing from the metadata. Meanings are in [ADMINISTRATION.md](ADMINISTRATION.md)
§8 and the section of the manual that owns each feature; the table below is the inventory.
"Default" is the value the kernel uses when the key is absent. Where the shipped classpath `application.yml`
sets a different value, both are shown.
**`runway.app-activity.*`** — the application-realm activity log
| Key | Type | Default |
|---|---|---|
| `enabled` | boolean | `true` |
| `retention-days` | int | `90` |
**`runway.backups.*`**
| Key | Type | Default |
|---|---|---|
| `max-entry-bytes` | long (bytes) | `268435456` (256 MiB) |
| `offsite-dir` | string (path) | _(blank — off)_ |
| `retention.max-age-days` | int | `0` (no age limit) |
| `retention.max-count` | int | `30` |
| `schedule.cron` | string (6-field Spring cron) | `0 30 2 * * *` |
| `schedule.enabled` | boolean | `false` |
**`runway.bandwidth.*`**
| Key | Type | Default |
|---|---|---|
| `enabled` | boolean | `true` |
| `quota.default-monthly-bytes` | long (bytes) | `0` (no cap) |
| `quota.per-site` | map: site id → long (bytes) | empty |
| `retention-days` | int | `90` |
| `snapshot-seconds` | int | `60` |
**`runway.cluster.*`** — see *Not covered* below: clustering is opt-in and outside the 1.0 promise.
| Key | Type | Default |
|---|---|---|
| `enabled` | boolean | `false` |
| `cluster-name` | string | `runway` |
| `topology` | enum `embedded` \| `client-server` | `embedded` |
| `session-ttl` | duration | `30m` |
| `sessions-map-name` | string | `runway.sessions` |
| `events-topic-name` | string | `runway.events` |
| `embedded.discovery` | string `tcp-ip` \| `multicast` | `tcp-ip` |
| `embedded.members` | list of string | empty |
| `embedded.port` | int | `5701` |
| `embedded.port-auto-increment` | boolean | `true` |
| `client.addresses` | list of string | empty |
| `client.smart-routing` | boolean | `true` |
**`runway.compression.*`**
| Key | Type | Default |
|---|---|---|
| `enabled` | boolean | `true` |
| `max-buffer-bytes` | long (bytes) | `4194304` (4 MiB) |
| `mime-types` | list of string (replaces the default list) | `text/html`, `text/xml`, `text/plain`, `text/css`, `text/javascript`, `application/javascript`, `application/json`, `application/xml`, `image/svg+xml` |
| `gzip.enabled` | boolean | `true` |
| `gzip.min-size` | int (bytes) | `1024` |
| `brotli.enabled` | boolean | `true` |
| `brotli.min-size` | int (bytes) | `1024` |
| `brotli.quality` | int `0..11` | `5` |
**`runway.console.*`** — where the operator console answers (host only, read at startup; ADMINISTRATION §8.6)
| Key | Type | Default |
|---|---|---|
| `hosts` | list of host names (case and port ignored) | empty: the default site's host names and host names that serve no site |
**`runway.csp.*`**
| Key | Type | Default |
|---|---|---|
| `mode` | enum `report` \| `enforce` \| `off` | `report` |
| `default-src` | string | `'self'` |
| `script-src` | string | `'self'` |
| `style-src` | string | `'self' 'unsafe-inline'` |
| `img-src` | string | `'self' data:` |
| `font-src` | string | `'self'` |
| `connect-src` | string | `'self'` |
| `base-uri` | string | `'self'` |
| `form-action` | string | `'self'` |
| `frame-ancestors` | string | `'self'` |
| `report-uri` | string | `/__csp-report` |
| `upgrade-insecure-requests` | boolean | `false` |
| `strict-dynamic` | boolean | `true` — `'strict-dynamic'` on the nonced kernel surfaces (console, login, recovery, wizard) |
| `public-strict-dynamic` | boolean | `true` — public tenant pages get a nonce derived from the page's ETag plus `'strict-dynamic'`, stamped only on the scripts the `script-src` + `extra-hosts` + plugin-host allowlist would have run (never an inline script unless `script-src` has `'unsafe-inline'`); takes effect only while `strict-dynamic` is on and `mode` is not `off` |
| `extra-hosts` | list of string | empty |
The secret that keys public-page nonces is a file, not a key: `external/csp-nonce.key` (§2).
**`runway.demo.*`** — unattended demo install (read via `@Value`)
| Key | Type | Default |
|---|---|---|
| `first-run.id` | string | _(blank — nothing installed)_ |
| `first-run.host` | string | _(blank — the demo's own host)_ |
| `first-run.master-username` | string | `demo` |
| `first-run.master-password` | string (secret) | _(blank)_ |
**`runway.endpoints.*`** (read via `@Value`)
| Key | Type | Default |
|---|---|---|
| `max-body-bytes` | long (bytes) | `10485760` (10 MiB) |
| `max-form-bytes` | long (bytes) | `262144` (256 KiB) |
`max-form-bytes` is the platform's **pre-authentication body budget**: the most body a caller who is **not signed
in** can make the server read, on any path. It bounds the form (or multipart) body of a plugin route, which the
kernel reads before authentication and the CSRF check (so the check and the route both see it); it also bounds
**any** body a caller who is not signed in sends — to the sign-in, setup and password-recovery forms of both realms,
to any console path, to the CSP report endpoint, to a `PUT`/`PATCH`/`DELETE` form, and to a plugin route of any
method and type. Above it the request is answered `413`; a declared `Content-Length` above it is refused without
reading. The effective value is the smaller of the two keys. `max-body-bytes` bounds the body a **signed-in** caller
sends to a plugin route (JSON, uploads, raw text), read after security; a signed-in console form keeps the
container's limit.
Raise `max-form-bytes` only for a plugin whose anonymous forms or uploads really carry more than 256 KiB. (A
multipart upload to a kernel path is the exception: it is parsed to temporary files before security under
`spring.servlet.multipart.max-request-size`.)
**`runway.health.*`** — the per-site `/__health` probe
| Key | Type | Default |
|---|---|---|
| `enabled` | boolean | `true` |
| `token` | string (secret) | _(blank — detail off)_ |
| `content-check` | boolean | `true` |
| `content-check-ttl-seconds` | int | `10` |
**`runway.http-cache.*`**
| Key | Type | Default |
|---|---|---|
| `public-pages` | string (`Cache-Control` value) | `public, max-age=300, stale-while-revalidate=60` |
| `assets` | string | `public, max-age=86400` |
| `immutable-assets` | string | `public, max-age=31536000, immutable` |
| `immutable-extensions` | set of string | `woff2, woff, ttf, otf, eot` |
There is no `no-store` key: the editor preview and error responses are always `no-store`. A file that sets it
starts normally; the key is ignored.
**`runway.i18n.*`**
| Key | Type | Default |
|---|---|---|
| `cache-seconds` | int | `5` |
**`runway.logs.*`** — per-site log capture
| Key | Type | Default |
|---|---|---|
| `enabled` | boolean | `true` |
| `access-log-user-agent` | boolean | `false` |
| `max-retention-days` | int | `90` |
| `queue-capacity` | int | `8192` |
**`runway.metrics.*`**
| Key | Type | Default |
|---|---|---|
| `scrape-token` | string (secret) | _(unset — off; a blank console field keeps a stored token)_ |
**`runway.node.*`** (read from the environment)
| Key | Type | Default |
|---|---|---|
| `name` | string | _(blank — the OS host name)_ |
**`runway.operator.*`**
| Key | Type | Default |
|---|---|---|
| `ui-languages` | list of BCP-47 codes | `[en, es]` |
| `default-language` | string | `en` |
**`runway.plugins.*`**
| Key | Type | Default |
|---|---|---|
| `root` | path (read from the environment before startup) | _(blank — `<external>/plugins`)_; the loader and the console's install/uninstall/enable/disable resolve it by one shared rule, so both always use the same folder |
| `max-entry-bytes` | long (bytes, `@Value`) | `134217728` (128 MiB) |
| `site-files.max-write-bytes` | long (bytes, `@Value`) | `16777216` (16 MiB): the largest single write (and whole-file read) a plugin makes in its per-site subtree through `PluginSiteFiles` |
**`runway.protect.*`** — the kernel's edge-rejection logging
| Key | Type | Default |
|---|---|---|
| `log-rejections` | boolean | `true` |
| `log-rejection-window-seconds` | int | `60` |
**`runway.proxy.*`**
| Key | Type | Default |
|---|---|---|
| `forwarded-headers` | boolean | `true` |
| `trusted-cidrs` | list of CIDR | empty (trust nothing); the shipped `application.yml` sets `127.0.0.1/32`, `::1/128` |
**`runway.reload.*`** — `/__reload/**`
| Key | Type | Default |
|---|---|---|
| `enabled` | boolean | `true` |
| `token` | string (secret) | _(blank — the endpoint is absent)_ |
**`runway.security.*`**
| Key | Type | Default |
|---|---|---|
| `app-master-id` | string | _(blank — WIZARD mode)_; written by the first-run wizard |
| `password-strength` | enum `standard` \| `high` | `standard` |
| `max-concurrent-hashes` | int | `8` |
| `acquire-timeout-millis` | long (ms) | `2000` |
| `secret-key` | string (secret) | _(blank)_; set by the installer as `RUNWAY_SECURITY_SECRET_KEY` |
**`runway.storage.*`**
| Key | Type | Default |
|---|---|---|
| `external` | path | `external` (relative to the working directory, which the launcher sets to the release dir) |
| `sites` | path | `<external>/sites` |
| `backups` | path | `backups` (relative to the working directory) |
`runway.storage.stats` (never read) and `runway.storage.logs` (display-only; the kernel writes nothing there) are
not keys, so they never enter the promise. A configuration that sets one starts normally and logs one startup
`WARN` naming the key; the metadata marks both as removed (deprecation level `error`).
**`runway.tls.*`**
| Key | Type | Default |
|---|---|---|
| `enabled` | boolean | `false` |
| `keystore` | string (path) | _(blank)_ |
| `keystore-password` | string (secret) | _(blank)_ |
| `keystore-type` | string | `PKCS12` |
| `key-alias` | string | `runway` |
| `watch-keystore` | boolean | `true` |
| `sni-host-check` | boolean | `true` |
| `redirect-http.enabled` | boolean | `false` |
| `redirect-http.port` | int | `80` |
| `redirect-http.status` | int `301` \| `302` \| `307` \| `308` (any other value stops startup while the redirect is on) | `301` |
| `redirect-http.acme-challenges-dir` | string (path) | `./external/acme-challenges` |
**Plugin keys: `runway.plugin.<id>.*`.** Each plugin owns the prefix `runway.plugin.<its id>.`; its app-level
settings are stored as `external/plugin-settings/<id>.yml` and bound by the plugin's own properties class. The
kernel promises the **prefix and the file**; the keys under it are the plugin's contract with its operators and
follow that plugin's own versioning. The bundled essential plugin documents its keys in
[ADMINISTRATION.md](ADMINISTRATION.md) §12 (`runway.plugin.protection.*`: `rate-limit.*`, `allowlist` and
`remember-device.*` on its settings form; `login.*` including `login.captcha.*`, which only seed a fresh
install's Login protection panel), and its jar carries its own
`META-INF/spring-configuration-metadata.json` for them (`ProtectionConfigurationMetadataTest` fails its build if
the file is not generated).
**Framework keys** (`server.*`, `spring.*`, `management.*`) belong to Spring Boot and are not covered here.
The ones Runway pins on purpose are listed, with the reason for each, in [ADMINISTRATION.md](ADMINISTRATION.md)
§8; a change to a pinned value is a changelog entry.
## 2. The data folder: `external/` and `sites/<id>/`
**Covered:** the location and meaning of every file below. Its *contents* are covered as far as its owner's
format goes: YAML stores keep their field names and meanings, properties files keep their keys, and templates
are the site's own content.
### The layout marker — `external/layout.yml`
```yaml
# Runway data-layout marker. Written by Runway on first start; do not edit or delete it.
# ...
version: 1
```
Owner: `mx.quest.runway.storage.DataLayout`, checked by `DataLayoutInitializer` at the very start of every
boot — before the plugin loader reads `external/`, before any store, seeder or plugin bean exists.
| What is on disk | What Runway does |
|---|---|
| no `layout.yml` | Writes `version: 1`. Every folder that predates the marker is layout 1 by definition. On a first, WIZARD-mode start against a folder that does not exist yet, nothing is written (nothing to protect); the first start that has a folder writes it. |
| `version` ≤ what the build supports | Starts normally; the file is not rewritten. |
| `version` > what the build supports | **Refuses to start** ("APPLICATION FAILED TO START", naming the file and both versions). An older Runway must never write into a layout it does not understand. |
| unreadable, not a mapping, no `version`, not a whole number, or below 1 | **Refuses to start** rather than guess. |
A failure to *write* an absent marker (for example a read-only folder) is logged as a warning and retried on
the next start; it never stops a start that worked before the marker existed.
**What a layout bump means.** The layout version changes only when a release changes the folder in a way an
older release would misread or damage: moving or renaming a file, changing what a field means, or adding data
an older release would silently drop when it rewrites a store. That release migrates the folder forward on its
first start, then writes the new version. The consequence for operators is the downgrade rule: **after a
layout bump, the previous release refuses to start against the migrated folder.** To roll back past a layout
bump, restore the copy of `external/` taken before the upgrade. Adding an optional field, file or folder is
*not* a layout bump.
### How a YAML store tolerates change
Every kernel store reads through `mx.quest.runway.storage.Yaml`, whose mapper has
`FAIL_ON_UNKNOWN_PROPERTIES` and `FAIL_ON_NULL_FOR_PRIMITIVES` disabled; each record's compact constructor
supplies the default for an absent field. So:
- a **newer** file read by an **older** build loads (unknown keys are ignored); an **older** file read by a
newer build loads (absent fields take defaults that reproduce the old behaviour);
- **but an older build does not preserve keys it does not know when it rewrites a record.** That is exactly why
a field whose loss would matter needs a layout bump, and why the layout marker refuses a downgrade instead of
relying on tolerance.
### `external/` — platform state (never in a tenant backup)
| Path | Owner | Holds |
|---|---|---|
| `application.yml` | operator; the first-run wizard (`WizardService`) merges the superadmin pin into it | The operator's configuration override (loaded by `spring.config.import`). Keep it mode `600`. |
| `layout.yml` | `DataLayout` | The layout marker above. |
| `platform.yml` | `PlatformSettingsStore` | Platform settings edited on **Settings → Platform settings**: the default site, platform mail (SMTP), node name, compression and password-strength overrides; and under `settings:` the kernel settings edited on **Settings → Server settings** and the policy cards (full property name → value; `ENC(...)` for a token), loaded at startup below `external/application.yml` (`KernelSettingsInitializer`), declared in the jar's `kernel-settings.yml`. Also `siteQuotas:` (each site's own bandwidth cap in bytes, set on **Sites**, read live), `siteStorageCeilings:` (each site's own storage limit for its files in bytes, set on **Sites**, read live), `embedHosts:` (the hosts approved on **Settings → Embed hosts**: `id`, `label`, `source`, `directives`, read live) and `logLevels:` (logger name → level, set on **Activity → Logs → Log levels**; applied at once on save and again at every start; a `logging.level.*` set in `application.yml` wins over it). |
| `app-users.yml` | `AppUserStore` | Application-realm accounts (Argon2id hashes). |
| `site-users.yml` | `TenantMasterStore` | Tenant superadmins, each assigned to one or more sites (application-managed, so kept outside every site folder). |
| `app-roles.yml` | `RoleStore` | Application-realm custom roles. Validated at startup; an invalid file stops the start. |
| `app-grants.yml` | `GrantStore` | Application-realm permission grants. |
| `recovery-tokens.yml` | `RecoveryTokenStore` | Hashed, expiring password-recovery tokens (both realms). |
| `blocklist.yml` | `StorageLayout.blocklistFile()`; written by the protection plugin's `IpBlocklist` | Manual IP/CIDR blocks. |
| `activity/` | `AppActivityLog` | Application-realm activity day-files (`activity-<yyyy-mm-dd>.log`), one line per operator action in the audit journal format below. Pruned after `runway.app-activity.retention-days`. |
| `csp-nonce.key` | `PublicPageNonce` | The secret that keys public-page CSP nonces (below). |
| `plugins/<id>/` | operator / console install (`PluginAdminService`); read by `PluginLoader` | One folder per installed plugin: `plugin.yml`, jars, `static/`, `i18n/`. When `runway.plugins.root` is set, these folders live there instead — for the loader and the console alike. |
| `plugin-settings/<id>.yml` | `PluginSettingsService` | A plugin's app-level settings (`runway.plugin.<id>.*`), loaded as a property source above `application.yml` and below environment variables and command-line arguments. Only a file named for an installed plugin is loaded, and only its keys under `runway.plugin.<id>.`; any other key in the file is ignored, with a warning naming it. A save from the console rewrites the file with the keys the plugin declares, so an undeclared key is dropped. Another file in the folder (the protection plugin's `protection-app.yml`) is that plugin's own data, never configuration. |
| `plugin-quarantine/<id>.yml` | `PluginQuarantine` | The marker of a plugin that broke the platform's startup: its version, a checksum of its jars, the reason and the time. While it matches the installed plugin, the plugin stays Blocked; **Retry** on the Plugins screen removes it, and a different version or different jars make it stale, and it is deleted (ADMINISTRATION.md §11). |
| `plugin-manifests/<id>.sha256` | the installer (`scripts/install.sh`) | What the installer shipped for a bundled plugin, so an upgrade can tell an operator's edit from a stale copy. |
| `seed/site-templates/<id>/` | `SeedTemplateStore` | The site-template catalog new sites are born from (`template.yml` plus the seed files). |
| `seed/site/` | `SeedTemplateStore` (legacy) | The pre-catalog seed folder; migrated into `seed/site-templates/default` on first run. |
| `i18n/operator-messages[_xx].properties` | `OperatorMessageSource` | Optional operator re-translation of the console, above the bundled messages. |
| `tls/` | the installer | A copied PKCS12 keystore when Runway terminates TLS itself. |
| `acme-challenges/` | operator / ACME client (`runway.tls.redirect-http.acme-challenges-dir`) | Files served at `/.well-known/acme-challenge/`. |
| `sites/` | `StorageLayout.sites()` (`runway.storage.sites`) | One folder per site (below). `sites/.restore-work/` is restore scratch space, never a site. |
### The audit journal line format — `activity/*.log` and `sites/<id>/logs/audit-*.log`
Both journals (the application activity log and each site's audit log) share one format, owned by
`mx.quest.runway.log.AuditJournal`. It is **covered**: a monitoring or SIEM pipeline may parse it.
- **Files.** One UTF-8 file per **server-local** calendar day: `activity-<yyyy-MM-dd>.log` and
`audit-<yyyy-MM-dd>.log`. Lines are only ever appended.
- **Line.** Four tab-separated fields, ending in `\n`:
```
<time> TAB <actor> TAB <action> TAB <detail>
2026-10-17T08:10:03.123-06:00 admin appuser.deleted alice (id 6f1c…)
```
`actor` is the operator's username (or a system marker); `action` is a stable dotted key
(`appuser.created`, `master.suspended`, `user.password-reset`, …); `detail` is free text (the target's name, an IP
for a login). CR, LF, tab and NUL inside a field are written as a space, so a crafted value can never forge a
line or a field.
- **Time.** ISO-8601 local date-time with milliseconds **and its UTC offset** (`Z` at UTC), in the server's time
zone: `yyyy-MM-dd'T'HH:mm:ss.SSSXXX`. The offset makes every entry's instant unambiguous across a DST change or
a server time-zone move.
- **Offset-less lines.** Runway writes only the form above. The reader also accepts lines that carry
`yyyy-MM-dd HH:mm:ss` with no offset and places them in the server's **current** zone (the console shows such
times without an offset). A reader parsing these files should accept both, as Runway does.
- **Tolerance.** A line with fewer than four fields reads its missing trailing fields as empty; a line whose time
matches neither form is skipped, never an error.
The per-site **access** log (`access-*.log`) is not part of this promise: it keeps its offset-less timestamp and
its field layout may change (see *Not covered*).
### The public-page CSP nonce secret — `external/csp-nonce.key`
Public tenant pages carry a CSP nonce derived from the page version:
`base64url(HMAC-SHA256(secret, "runway-csp-nonce/v1|" + ETag))`, so every `200` and `304` of one content version
carries the same nonce and shared caches keep working. The secret is this file.
- **Created** on the first page that needs it (only while `runway.csp.public-strict-dynamic` is in effect): 32
random bytes, written owner-only (`0600`) and published atomically, so two nodes sharing the folder never
overwrite each other's key. A file shorter than 32 bytes is refused.
- **Read once** per process and held in memory.
- **Rotation:** delete the file and restart. Every nonce changes, and because a fingerprint of the secret (never
the secret) is folded into each page ETag, **every page ETag changes once** too, so no browser or CDN can pair
an old body (old nonce) with a new header. Caches simply revalidate.
- **Clustering:** give every node the same file, as with other shared secrets; otherwise each node has its own
ETags (still correct, fewer cross-node `304`s).
- **If it cannot be created or read**, the feature turns itself off for that process (logged once at `ERROR`):
public pages keep the host-allowlist policy and their ETags say so. Never a `500`.
- It is platform state under `external/`, so it never travels in a site backup.
The nonce values and the ETag values themselves remain opaque (see *Not covered*); the file's name, location,
permissions and the rotation procedure are covered.
### `sites/<id>/` — one self-contained site (travels whole in its backup)
| Path | Owner | Holds |
|---|---|---|
| `site.yml` | `SiteStore` | The site record: id, name, hosts, locales, base URL, status, and the optional `editorial:` level (`advisory` \| `enforced` \| `reviewed`; absent or unrecognised reads as `advisory`). |
| `users.yml` | `SiteUserStore` | The site's own accounts (not the tenant superadmin). |
| `roles.yml` | `RoleStore` | The site's custom roles. An invalid file quarantines that site's console, not the platform. |
| `permissions.yml` | `GrantStore` | The site's permission grants. |
| `templates/` | `PageStore`, `PageWriteService` | Pages (`<slug>.html` + decoupled `<slug>.th.xml` + `<slug>.meta.yml`) and `_master.html`. |
| `templates/.pending/<slug>/` | `PendingRevisionStore` | Pending editorial work for one page: `review.yml` (state `submitted` \| `returned`, who/when, the approver's note) and, for a change to a published page, `revision.meta.yml` + `revision.html` + optional `revision.th.xml`. Never routed or listed; carried by backups and transfer copies. |
| `i18n/messages[_xx].properties` | `SiteMessagesStore` | The site's messages; the default locale is the unsuffixed file. |
| `static/` | site manager (served by `SiteStaticController`) | The site's public assets at `/static/**`. |
| `static/doc/` | `DocumentService` | Uploaded documents. |
| `doc-state.yml` | `DocumentService` | The documents a site manager has disabled (withheld from the public without deleting them). |
| `icons/` | `SiteIconService` | `favicon.svg`, `favicon.ico`, `apple-touch-icon.png`, `icon-192.png`, `icon-512.png`. |
| `manifest.yml` | `SiteManifestService` | The web app manifest's fields (served as `/manifest.webmanifest`). |
| `seo.yml` | `SeoConfigService` | Site-wide SEO settings. |
| `csp.yml` | `SiteCspService` | `hosts:` the ids of the operator's approved embed hosts this site switched on (**Site config → Embedded content**). Only ids still approved count. |
| `contact.yml` | `SiteContactService` | The site's contact details. |
| `params.yml` | `SiteParamsService` | Template parameters: a flat key → value map exposed to every render as `${params.key}`. |
| `log.yml` | `SiteLogConfigService` | The site's own log-retention preference. |
| `logs/` | `SiteLogService` | `access-<date>.log` and `audit-<date>.log` day-files; the audit files use the audit journal format (§2, above). |
| `stats/bandwidth.csv` | `BandwidthService` | Hourly served-bytes buckets. |
| `plugins/<plugin>.yml` | `SitePluginConfigService` | A plugin's per-site settings. |
| `plugins/<plugin>/` | the plugin | Plugin-generated per-site data (for example a content source's items). |
| `widget-instances.yml` | `WidgetInstanceConfigService` | Per-instance settings of placed content widgets. |
### Outside `external/`
| Path | Key | Holds |
|---|---|---|
| `backups/<siteId>/backup-<yyyyMMdd-HHmmss-SSS>.zip` | `runway.storage.backups` | Stored backups (below). |
| `logs/runway.out` | (the launcher) | The service's stdout/stderr when run detached. |
## 3. The backup archive
**Covered:** the archive's structure and `manifest.yml`, and the restore promise.
```
manifest.yml what the archive is
site/<path inside sites/<id>/> the whole site folder (symlinks are never followed)
plugin-data/<key>/<entry> each BackupParticipant's out-of-folder data
```
`manifest.yml` (`mx.quest.runway.backup.BackupManifest`):
| Field | Meaning |
|---|---|
| `formatVersion` | The archive **format** version. Currently `1`. **Absent = `1`**. |
| `siteId` | The site the archive was taken from (informational; a restore targets the chosen site). |
| `spiVersion` | The SPI version of the writer — **diagnostic only**; restore never branches on it. |
| `createdAt` | ISO-8601 instant. |
| `participants` | The `BackupParticipant` keys whose data is under `plugin-data/`. |
| `purpose` | `RESTORE` (complete) or `TRANSFER` (accounts, secrets and hostnames removed). Absent = `RESTORE`. |
| `omitted` | What a `TRANSFER` copy left out as plugin personal data: each declared `siteData.personal` path (`plugins/<pluginId>/<path>`; a folder ends in `/`) and `plugins/<id>/` for each plugin that was not loaded. Empty for a complete backup. **Absent = empty** (an additive key, so `formatVersion` stays `1`). |
**Reading rules.** Readers do not depend on entry order (Runway writes `manifest.yml` first, and checks its
`formatVersion` the moment it reads it). Unknown manifest keys are ignored. Unknown top-level entries are
drained and ignored. A participant named in the manifest but not installed is tolerated: its data stays
unrestored. An archive without `manifest.yml` or without `site/site.yml` is not a Runway backup.
**The format gate.** Restore — on the site console, on the app console, and when creating a new site from a
backup — accepts any `formatVersion` up to the one the build supports and **refuses a higher one**, before
anything is swapped in: the operator sees "This backup was made by a newer version of Runway (backup format N;
this version restores up to format M)" and the live site is untouched. A value below 1 is not a valid backup.
**The cross-version promise.** An archive written by any `1.x` restores on the same or any later `1.x`.
`formatVersion` rises only for a change an older reader would misread (a new mandatory entry, a moved tree);
adding a manifest key or an optional entry is not a format change. Restoring an archive from a *later* `1.x`
on an earlier one works whenever the format number allows it, but is not part of the promise: the later
release may have written site files the earlier one does not use.
## 4. The plugin descriptor (`plugin.yml`)
**Covered:** every key below. The kernel reads the descriptor without loading plugin code
(`mx.quest.runway.plugin.PluginDescriptor`), with `FAIL_ON_UNKNOWN_PROPERTIES` off, so a descriptor written for
a newer kernel loads on an older one and the other way round. Within `1.x` a key keeps its meaning; new keys
are optional. A plugin that needs a newer kernel says so with `requiresSpi`, and an older kernel then blocks
it with a clear reason instead of loading it to fail later.
| Key | Type | Meaning |
|---|---|---|
| `id` | string | Stable id = install-folder name (must be a safe id). **Required.** |
| `name` | string | Display name. |
| `version` | `MAJOR.MINOR.PATCH` | The plugin's version. **Required**, strictly parsed. |
| `mainClass` | string | The `@Configuration` class; absent = a code-less library provider. |
| `enabled` | boolean | `false` excludes the plugin. Absent = enabled. |
| `essential` | boolean | Honoured only for plugins on the kernel's security-floor allowlist. |
| `requires` | list | Hard dependencies: `id`, `id >= v` or `id == v`. |
| `conflicts` | list of id | Rival plugins this one steps aside for. |
| `requiresSpi` | `>=X.Y.Z` | Minimum kernel SPI level. Malformed = the plugin is blocked, never silently ignored. |
| `permissions` | list | Declared permissions: `id`, `realm` (`tenant` \| `application`), `label`, `defaultRoles`. |
| `settings` | list of setting | App-level settings schema. |
| `siteSettings` | list of setting | Per-site settings schema. |
| `widgetSettings` | map: widget key → list of setting | Per-instance settings of a content widget. |
| `settingGroups` | list | Titled form sections: `id`, `label`, `help`, `helpAnchor`. |
| `helpUrl` | string | The plugin's help page (path or absolute URL). |
| `menu` | list | Console menu entries: `realm`, `region`, `order`, `label`, `path`, `permission`, `icon`. |
| `dashboardCards` | list | Dashboard cards: `realm`, `order`, `fragment`, `permission`. |
| `siteData` | map | `personal`: paths under `sites/<id>/plugins/<pluginId>/` holding personal data (a trailing `/` names a folder). A transfer copy leaves them out. A malformed path (absolute, a backslash, an empty, `.` or `..` segment) blocks the plugin. Absent = nothing declared. |
A **setting** (`PluginSettingDef`) has `key`, `type` (`string` \| `text` \| `secret` \| `int` \| `decimal` \|
`boolean` \| `enum` \| `list`), `default`, `label` and `range`, plus the presentation keys `help`, `group`,
`advanced`, `showWhen`, `helpAnchor`, `inheritsFrom` and `requiresPlatform`, and — on a `secret` only —
`secretBoundTo`: a list of keys in the same schema the secret belongs with (where it is sent). When a save
changes one of them and the secret field is left blank, the stored secret is **removed** rather than kept, and
the form says it must be entered again. Absent = empty = a blank secret is always kept.
**Tolerance rules.** Structural keys (`id`, `version`, `requires`, `requiresSpi`, `permissions`, `menu`, `siteData`) are
validated, and a violation blocks the plugin with an operator-readable reason on the **Plugins** screen; the
platform still starts. Presentation keys (`settingGroups`, `help`, `group`, `advanced`, `showWhen`,
`helpAnchor`, `inheritsFrom`, `requiresPlatform`, `helpUrl`) **degrade** instead: a group id nobody declared, an empty
list item, a `showWhen` naming a missing or non-boolean key, or an `inheritsFrom` that cannot be resolved
renders the form without that refinement, never a failure. An
older kernel ignores them entirely, so a plugin can adopt them without raising `requiresSpi`. `secretBoundTo`
is read just as leniently — a list, one key, or a comma-separated string; a malformed value (a map, a number)
reads as empty, and a key the schema does not declare never matches — so it never blocks a plugin; at worst a
binding is missing and the old "blank keeps the secret" applies.
## 5. HTTP paths, metrics and logger names
### Public paths a client may depend on
| Path | Realm / host | Contract |
|---|---|---|
| `GET /actuator/health` (+ `/liveness`, `/readiness`) | any | Public `UP`/`DOWN`; details only to an authenticated operator. |
| `GET /actuator/prometheus` | any | Prometheus scrape; app superadmin/admin session or `runway.metrics.scrape-token` bearer. |
| `GET /__health` | a site's host | Per-site probe: `{"status":"up\|degraded\|down","time":…}`; detail with `runway.health.token`. |
| `POST /__reload/site/<id>`, `POST /__reload/sites` | loopback only | Re-read a site (or all) without a restart; `runway.reload.token` bearer. |
| `POST /__csp-report` | any | CSP violation reports (the default `runway.csp.report-uri`). |
| `/login`, `/logout`, `/forgot-password`, `/reset` | a site's host | Site sign-in and password recovery. |
| `/app/login`, `/app/logout`, `/app/forgot-password`, `/app/reset` | the platform host | Application-realm sign-in and recovery. |
| `/static/**`, `/static/doc/**` | a site's host | The site's assets and documents. |
| `/favicon.svg`, `/favicon.ico`, `/apple-touch-icon.png`, `/icon-192.png`, `/icon-512.png`, `/manifest.webmanifest` | a site's host | Site icons and web app manifest. |
| `/__plugin/<id>/static/**` | any | A plugin's static files (the path shape; the files are the plugin's). |
**Reserved namespace.** Tenant content can never claim a path under `/__`, `/actuator`, `/app/`, or the exact
routes `/error`, `/login`, `/logout`, `/forgot-password`, `/reset` (`mx.quest.runway.web.ReservedPaths`). New
kernel paths are added only inside that reserved space, so a 1.x upgrade never shadows a site's page.
### Metric names and tags
Consumed by the bundled `monitoring/` dashboard and alert rules. Names (Micrometer form → Prometheus form) and
tag keys are covered; tag *values* listed are covered too.
| Meter | Prometheus | Tags |
|---|---|---|
| `runway.sites` | `runway_sites` | — |
| `runway.sites.suspended` | `runway_sites_suspended` | — |
| `runway.sites.maintenance` | `runway_sites_maintenance` | — |
| `runway.plugins.loaded` | `runway_plugins_loaded` | — |
| `runway.logs.dropped` | `runway_logs_dropped` | — |
| `runway.storage.free.bytes` | `runway_storage_free_bytes` | — |
| `runway.storage.total.bytes` | `runway_storage_total_bytes` | — |
| `runway.http.server.requests` (timer) | `runway_http_server_requests_seconds_*` | `site`; `outcome` = `informational` \| `success` \| `redirection` \| `client_error` \| `server_error` |
| `runway.edge.rejections` (counter) | `runway_edge_rejections_total` | `status` (HTTP code); `reason` |
The JVM, Jetty and route-level (`http_server_requests_seconds_*`) metrics are Spring Boot / Micrometer's and
are not covered here.
### Logger names
| Logger | Carries |
|---|---|
| `runway.access` | One line per served public request, platform-wide (route it to its own file or log stack). |
| `runway.protect` | Edge rejections (rate limits, blocks), de-duplicated per client and reason. |
The **names** are covered, so a logging configuration that routes them keeps working. The wording of a line is
not (see below).
## 6. Explicitly NOT covered
- **Operator console URLs and screens** under `/__app/**` and `/__admin/**`, the first-run `/setup`, the
console's vendor assets under `/__assets/**`, and `/__ui-lang`. They are a user interface, not an API, and
may move in any release.
- **The markup of internal templates** (console pages, login, error pages, the bundled seed templates as
shipped). A site's own templates are its content and are covered as files; what Runway ships as a starting
point is not.
- **Log line wording** of every logger and log file, including `runway.access`, `runway.protect` and the
per-site access log, except the audit journal format listed in §2. Within that format, the set of `action`
keys may grow; an existing key keeps its meaning.
- **ETag values and CSP nonces**: opaque; their derivation may change in any release (a change only makes
caches revalidate once).
- **Clustering**: the `runway.cluster.*` keys, the Hazelcast map and topic names (`runway.sessions`,
`runway.events`), and the wire format between nodes. Clustering is opt-in and outside the 1.0 scope; it
joins this promise when it leaves opt-in.
- **Framework keys and metrics** (`server.*`, `spring.*`, `management.*`, JVM/Jetty meters): Spring Boot's.
- **The Java classes** named here as owners. They identify who reads and writes a file; they are not API.
The binary API is `runway-spi`, covered by [SPI-STABILITY.md](SPI-STABILITY.md).
## For maintainers: changing a covered surface
- **A new configuration key**: give it a default that keeps today's behaviour; it appears in the metadata
automatically (properties class) or must be added to `additional-spring-configuration-metadata.json`
(`@Value` / environment), or `ConfigurationMetadataTest` fails.
- **A renamed key**: keep binding the old one, log a startup `WARN` naming the new one, mark the old one
deprecated in the metadata, list it under *Deprecated* in the changelog.
- **A new optional field in a store**: default it in the record's compact constructor so older files read
unchanged; check that an older build dropping it on rewrite does no harm — if it would, that is a layout bump.
- **A layout bump**: raise `DataLayout.SUPPORTED_VERSION`, write the forward migration that runs before
anything else touches the folder, rewrite the marker after it, document the downgrade consequence in the
upgrade notes.
- **A backup format bump**: raise `BackupManifest.SUPPORTED_FORMAT_VERSION`, keep reading every older format,
and say in the changelog which release first writes the new one.
+127
View File
@@ -0,0 +1,127 @@
# Runway — Glossary
> **Audience:** everyone.
> **What this is:** the shared vocabulary used across Runway's documentation, defined once
> here so the other documents can use the terms without redefining them.
> **Doc status — growing.** The core terms below are stable and defined now; entries are added
> and sharpened as the platform is built.
---
**Kernel** — Runway's core: a multi-tenant web server and plugin host. It provides the
essential machinery (HTTP serving, the request pipeline, multi-tenancy, the rendering engine,
the security framework, the plugin host, first-run setup) and ships **no domain features** of
its own.
**Plugin** — an installable folder that adds a feature to the platform. It carries its own
code and presentation assets and plugs into the kernel through declared extension points. See
[PLUGIN-DEVELOPMENT.md](PLUGIN-DEVELOPMENT.md).
**SPI (Service Provider Interface)** — the thin, dependency-free set of interfaces and
immutable data records that plugins (and the kernel's own built-in features) implement. It is
released **binary API**: it evolves only by adding, so older extensions keep working.
**Capability-driven** — the kernel decides what to do by inspecting the **capabilities a
component declares** (data), never by checking which specific component it is. A new component
lights up across the platform without any change to the kernel.
**Realm** — an isolated identity domain with its own users, login, and access rules. Runway
has two: the **application realm** (operators who run the platform) and the **tenant realm**
(users who manage an individual site). They never cross.
**Application administrator / superadmin** — an operator in the application realm who runs the
platform itself. The application superadmin is the protected top account that always exists
and cannot be removed, disabled, or demoted.
**Site (tenancy)** — one independently hosted website with its own data, presentation, users,
and configuration, fully isolated from every other site and from the platform's own
configuration.
**Site manager / site-superadmin** — a tenant-realm user who manages a site. The
site-superadmin is the protected top account of a site.
**Master account** — the protected top account of a realm or a site (the application
superadmin; a site-superadmin). It is immutable from inside its own realm and sits above the
normal permission checks.
**Wildcard admin** — a built-in full-access role within a realm. Holding it passes any access
check except operations reserved to the master.
**Permission** — a named, grantable capability declared by the kernel or a plugin (tagged with
its realm). Permissions are assigned to roles and/or directly to users; they are never created
by end users.
**Role** — a named bundle of permissions. Roles are arranged in a per-site/per-realm
**hierarchy**, and access is **additive** — a user gets the union of their roles (and
everything beneath them) plus any direct grants. There are no deny/negative grants.
**`mayAccess`** — the single, central, fail-closed access check every guarded action routes
through: master → wildcard admin (except master-only operations) → an explicit permission →
otherwise denied. An unknown permission is denied.
**Page-as-entry** — the rendering model for public sites: a page is a **complete, normal HTML
document** that is itself the render root; the platform pulls the site's chrome and live data
into it when serving. See [SITE-MANAGER-GUIDE.md](SITE-MANAGER-GUIDE.md).
**Master-as-shell** — the rendering model for the kernel-owned operator UI: a single shell
template owns the page frame and each screen's content is wrapped into it.
**Master (template)** — a site's shared layout/chrome that pages pull their header, footer,
and other shared regions from. (Distinct from a *master account*.)
**Seam** — a named region in a master that a page (or the platform) fills or replaces — for
example the header, footer, or content slot.
**Decoupled-logic templating** — the rule that **no template language appears in any HTML
file**; the dynamic-binding logic lives in a separate paired file, keeping authored HTML 100%
browser-renderable.
**Content widget** — a plugin-provided piece of page content placed via a simple `data-widget`
anchor in the markup; the platform replaces the anchor at render time.
**Head injection** — the platform adding technical `<head>` markup (e.g. SEO/GEO tags) to every
response at the response edge, without requiring any code in a site's templates.
**Filter band** — one of the fixed, ordered phases the request pipeline runs in. A plugin can
place a filter **within** a band but can never reorder the bands or get ahead of core
protection.
**Surface posture** — the per-surface declaration of whether it should be indexed, listed in
the sitemap, and cached, with safe defaults until a surface opts in. See
[PLUGIN-DEVELOPMENT.md](PLUGIN-DEVELOPMENT.md).
**Essential plugin** — a plugin on the kernel's internal security-floor allowlist. If one is
missing or broken, sites serve a maintenance page while the application realm stays reachable
to fix it. A feature plugin cannot promote itself to essential.
**External folder** — the editable directory tree outside the application jar holding
configuration, templates, static assets, translations, sites, plugins, and logs. See
[ADMINISTRATION.md](ADMINISTRATION.md).
**Editorial level** — a site's setting for how strictly publishing is governed, chosen on Site config:
**Advisory** (the default — quality findings are shown, nothing is blocked), **Enforced** (an error-level
quality finding refuses a publish) or **Reviewed** (enforced, and publishing needs a user with *Approve
pages*; everyone else submits for review). See [SITE-MANAGER-GUIDE.md](SITE-MANAGER-GUIDE.md) §10.
**Pending revision** — on a *Reviewed* site, an edit to a page that is already live, saved by someone who
cannot publish. It is kept beside the page until an approver approves it (it replaces the live page) or sends
it back; until then visitors, search and the sitemap see only the live page.
**Site insights** — a site's own report of its most-visited pages and the addresses that most often answered
"not found" (404), counted from its access log; paths and counts only, never a visitor's address.
**Audit journal** — the record of who did what: the application realm's activity log and each site's audit
log. Lines carry the time with its UTC offset, the actor and the action, never a password or a setting's
value. See [ADMINISTRATION.md](ADMINISTRATION.md) §14.
**Transfer copy** — a download of a site for handing it to someone else: the site's content and presentation
without its users, secrets or hosts. Distinct from a **backup**, which is complete so that it can restore the
site exactly. See [ADMINISTRATION.md](ADMINISTRATION.md) §13.
**Layout marker** — `external/layout.yml`, the file that records which version of the data-folder layout is in
use. A Runway build that finds a newer layout than it understands refuses to start rather than write into it.
See [CONFIGURATION-AND-DATA-STABILITY.md](CONFIGURATION-AND-DATA-STABILITY.md).
**Format version** — the `formatVersion` a backup archive records in its `manifest.yml`. Restore accepts the
same or an older format and refuses a newer one, before touching the live site.
+160
View File
@@ -0,0 +1,160 @@
# Known limitations — the state of the code now
> **What this is:** an honest, current list of what Runway does **not** do, or does only partially, in the
> code as it stands (release `1.0.0`; the exact version is in the [CHANGELOG](../CHANGELOG.md)). The plugin
> contract is frozen at SPI `1.0.0` and enforced at load time ([SPI-STABILITY.md](SPI-STABILITY.md));
> configuration, the data folder and backups are governed by
> [CONFIGURATION-AND-DATA-STABILITY.md](CONFIGURATION-AND-DATA-STABILITY.md), which binds from `1.0.0`. The data
> folder and backup archives carry the version markers that promise is built on (`external/layout.yml`, a
> backup's `formatVersion`). Read the CHANGELOG's upgrade notes and take a backup before upgrading.
This file is part of the release and is kept truthful: an item leaves the list in the same change that
closes it. Items marked **after 1.0** are decided: they are not part of the `1.0.0` scope.
## Platform
- **Clustering is single-writer.** Multi-node works and is opt-in (`runway.cluster.enabled=true`): HTTP
sessions live in a Hazelcast `IMap` and cache-invalidation events are relayed over a Hazelcast topic, so
instances behind a load balancer share sessions and evict in step. The default is **off** (no Hazelcast
member, the container's own `HttpSession`). Not built (**after 1.0**): **read-only edge/replica nodes**
and a **distributed write lock**. The filesystem/YAML stores serialize writes per site within one JVM only,
so two nodes writing the same site are last-writer-wins at file granularity: keep authoring on one node.
- **Clearing the template cache acts on one node.** *Platform settings → Clear template cache* empties the
cache of the node that answered the request. On a cluster, a site **reload** evicts that site's templates
on every node (its change event is relayed); a cluster-wide clear-all needs a relay message type that does
not exist yet (**after 1.0**).
- **Each node needs the same public-page nonce key.** `external/csp-nonce.key` is created per node; copy it
to every node so a `304` from one node matches a page cached from another (Administration §8.4). With
different keys each node has its own ETags: correct, just fewer `304`s.
- **Linux-only installer.** The self-extracting `.bin` targets Linux with systemd. A Windows installer is
**after 1.0**.
- **Backups go to folders, not to object storage.** Per-site backups, retention, the opt-in schedule and the
best-effort **off-host mirror folder** (`runway.backups.offsite-dir`) ship. Pushing backups to S3/GCS
directly is **after 1.0**, as a plugin; until then point the mirror at a mounted share or sync it with a
sidecar.
## Security
- **The public-page CSP is no stronger than the host allowlist against injected markup — and no weaker.**
Public pages carry a nonce derived from the page version plus `'strict-dynamic'`, and the response edge
stamps that nonce only on the scripts the `'self'` + host-allowlist policy would have run (same-origin or
allowlisted `src`; never an inline script). An injected inline script or foreign-host script therefore stays
blocked in `enforce` mode, but an injected `<script src>` pointing at the site itself or at an allowlisted
host runs — as it did under the allowlist policy — and, through `'strict-dynamic'`, may load further scripts
from any host. Template escaping is the defence against injection itself. What the nonce closes is the
host-allowlist bypass for parser-inserted scripts, and it blocks scripts written at runtime
(`document.write`).
- **Some responses keep the host-allowlist policy.** Responses without a page version (error pages, plugin
endpoints, the maintenance page), a page larger than the 8 MiB rewrite buffer, and a page whose markup
already contains its own nonce (copied in through an input the page version does not fold — e.g. into an
`<iframe srcdoc>`) or a foreign preload hint the edge cannot remove (below) carry `'self'` plus the host
allowlist, without a nonce.
- **Inline-SVG scripts do not run under `enforce`.** The stamp needs a `src` attribute and an empty element:
an SVG `<script href>` names its file in `href` (which an HTML `<script>` ignores, running its text), and an
SVG `<script src>` runs its text, so neither can be stamped safely without building the document tree. Load
the code with a normal `<script src>` in the page. For the same reason a `<script src>` placed inside an SVG
`<title>` or `<style>` is left unstamped: the edge reads those as text (as HTML does), while inside `<svg>` the
browser does not — under `enforce` such a script is blocked rather than guessed at.
- **Preload hints to a host outside the policy are removed from public pages.** Under `'strict-dynamic'` a browser
fetches a `<link rel="modulepreload">` or `<link rel="prefetch">` from any host (measured in Chrome 155), so the
edge removes such a link — and a `preload` with a script-class `as` — unless its URL is on the site's origin or a
host the policy names. A hint written inside an SVG `<title>`/`<style>` (or another element the edge reads as
text), or inside an `<iframe srcdoc>`, cannot be removed safely; that response then falls back to the
host-allowlist policy without a nonce and with `no-store` (the fetch is blocked; the page loses shared caching
until the hint is gone). A page that merely *shows* such a tag written literally — unescaped inside a
`<textarea>`, or in an inline script's string — falls back the same way, because the edge builds no document
tree and cannot tell which element the browser will make of it; a sample escaped as text (`&lt;link …&gt;`, what
a code block normally holds) is not affected. The same fallback covers markup the edge cannot read with certainty
the way the browser will: after an inline `<svg>`, `<math>`, `<select>` or `<template>`, a
raw-text element (`<style>`, `<title>`, `<script>` …) or `<![CDATA[` whose two possible readings disagree, a
`<noscript>` that reads differently with scripting on and off, or a `<base>` there. Well-formed pages never reach
it; the edge follows every tokenizer state that does not depend on the document tree (bogus comments, DOCTYPE,
end-tag attributes, the script escape states), checked against Chrome 155 on a corpus of crafted pages.
- **`preconnect`, `dns-prefetch` and `prerender` hints reach any host, under any policy.** CSP has no directive for
the first two, and Chrome's prerender (NoState prefetch) contacted a foreign host under the host-allowlist policy
too (measured in Chrome 155). Injected markup can therefore make a visitor's browser open a connection to (never
run code from) a host of its choosing; this is unchanged by the public nonce, and template escaping is the
defence.
- **A site's own scripts can act as that site's signed-in console users.** A site's public pages and its console
(`/__admin`) share one origin, and CSP cannot separate two documents on one origin: a script on a public page can
call the console with the session of a site user signed in in the same browser. And whoever can put a `.js` file
on a site (*Configure site*, or template editing) can run any script on its public pages, because under
`'strict-dynamic'` a same-origin script may load others from any host. The operator console is kept off site host
names for this reason (Administration §8.6); separating a site's console onto a host name of its own is a design
for after 1.0.
- **CSP is report-only out of the box.** `runway.csp.mode: enforce` is the operator's switch after reviewing
the violation log (Administration §8.4).
## Console and content
- **Accessibility: structural baseline only.** Every console screen has accessible names, `lang`,
landmarks, a skip link, `aria-current` on the active kernel menu entry and table header scopes, and a test
keeps them there. Not done yet: a **colour-contrast audit**, **live regions** for status messages that
appear without a page load, and `aria-current` on **plugin-contributed menu entries** (the kernel's own
entries carry it; a plugin's entry is marked active by nothing). The password show/hide toggle stays out
of the tab order on purpose (its name and state are exposed).
- **The page editor's live preview follows the code, not the metadata.** Unsaved edits in *Page HTML* and
*Decoupled logic* render as you type; unsaved title, path or master changes show only after **Save**, and
the popped-out preview window always shows the saved page. If a live render fails (no answer within 15
seconds), the panel returns to the saved page and stops following edits until the editor is reloaded.
- **A site's storage limit covers its uploads, not every file it has.** The limit on Sites (off by default)
counts and gates what is under the site's `static/` folder: the Static files and Documents uploads. Pages,
fragments, pending revisions and messages (each save bounded by the 16 MiB form limit, not in number), plugin
files (`sites/<id>/plugins/`, 16 MiB per write) and the site's own logs and statistics are neither counted nor
refused, and nothing bounds the **number** of files, so many tiny files can exhaust a filesystem's inodes before
its bytes. On a server whose sites are not all yours, also put the data folder on its own filesystem or mount.
The check holds a lock on one node only: on a cluster, two nodes uploading to one site at the same moment can
both pass it (authoring belongs on one node anyway, see *Clustering*).
- **No per-site bandwidth chart for the operator.** `/__app/bandwidth` lists every site's totals; the
per-site chart is on the site's own console only.
- **Site insights count crawlers.** The tenant **Insights** screen (top 404s, most-visited pages) reads the
per-site access log, which records no user agent, so a crawler's requests count like a visitor's (the
screen says so). A busy site's tallies can be approximate: each keeps at most 5,000 distinct paths and a
scan stops after two million lines, and the screen flags both.
- **Audit export is capped.** The journal viewers' CSV download carries at most 10,000 rows per request
(a capped download carries `X-Runway-Audit-Incomplete: true`); narrow the date range for more.
- **Six path advisories are not quality checks.** The page editor's checks on page paths stay in the editor
rather than in the `PageQualityCheck` set, because the checks' view of a page does not carry the raw
per-language paths; they are advisory and never block publishing on an *Enforced* or *Reviewed* site.
## Plugins
- **Only the essential protection plugin ships in the installer.** It is seeded into
`external/plugins/protection/` on a fresh install and refreshed on every upgrade (it is lockstep with the
kernel; the previous jar and descriptor are kept as `*.bak`, edited templates/i18n are backed up). Every
other plugin (such as search and search-lucene) is a deliberate operator install; there is no plugin
marketplace or auto-update path.
- **Plugins built for the pre-1.0 plugin contract do not load.** The plugin contract is frozen at SPI `1.0.0`
([SPI-STABILITY.md](SPI-STABILITY.md)). A plugin with a `mainClass` that declares no `requiresSpi` floor of at
least `0.4.0` — or any plugin that links Runway's internal classes — shows **Blocked** on **Plugins** with the
reason; the platform runs without it until you install the plugin's release made for Runway 1.0
(Administration §11).
- **A plugin cannot add servlet filters, security chains or CSP hosts.** These are outside the 1.0 contract (they
reach every request); only the essential protection plugin uses them. A plugin whose script loads from or frames
a third-party host needs the operator to add it to `runway.csp.extra-hosts`.
- **A multipart body reaches a plugin route raw.** A plugin route receives a `multipart/form-data` body as bytes
and parses it itself, and takes its CSRF token in the `X-CSRF-TOKEN` header (no first-party plugin accepts
uploads).
- **Billboard and News plugins are not built** (**after 1.0**, as plugin releases).
- **No published plugin serves `/sitemap.xml`, `/robots.txt`, `/llms.txt` or schema.org structured data.** The
kernel provides the seams (`EndpointContributor`, `HeadContributor`) and the Site-manager guide (§10) describes
what such a plugin provides, but none of the published plugins (demo, search, search-lucene, lucene-provider)
does; without one a site serves no `/robots.txt` at all (crawlers read that as everything allowed) and no sitemap.
- **The search plugin's rate limit is a courtesy limiter, not a defence.** It keys on the client address after
the kernel's trusted-proxy gate; the kernel's own edge guard is the abuse floor.
- **A search index rebuilds by rendering every page once per language.** A page is indexed as rendered in
each language it exists in (bundle strings included), so the first query after a change renders the site's
pages to rebuild the index — slower than later queries on a
large multilingual site. A change no event announces (a template edited on disk) reaches the index after the
search plugin's freshness window or the search settings' **Rebuild index** button.
## By design — not limitations
- **No database.** The kernel is filesystem/YAML-backed on purpose; there is no SQL layer to
configure. A deployment that genuinely needs one adds it as a **datasource-provider plugin** (the
first-run wizard therefore provisions the app superadmin + first site, never a DB).
- **Central seed changes do not back-propagate to existing tenants.** Each tenant owns its copy of the
seeded master/templates after creation (the self-containment law); improving the seed affects only
*new* tenants. This is the deliberate price of complete tenant isolation and portable backups.
- **No public draft-preview link.** A draft is previewed inside the console only; there is
no shareable URL that shows unpublished content to someone without a console account.
+1002
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+34
View File
@@ -0,0 +1,34 @@
# Runway Documentation
This is Runway's **delivered documentation** — the self-contained set that ships with the
product. Together with the source code, it is everything you need to install, operate,
manage, use, and extend Runway through its plugin system. Each document explains what it
needs directly.
## Find your document
| Document | For | Covers |
|---|---|---|
| [`../README.md`](../README.md) | Anyone | What Runway is, and **quick install + first access** |
| [PLUGIN-DEVELOPMENT.md](PLUGIN-DEVELOPMENT.md) | Plugin authors | Writing a Runway plugin: descriptor, contribution seams, settings, permissions, packaging |
| [SPI-STABILITY.md](SPI-STABILITY.md) | Plugin authors, maintainers | What the extension API (`runway-spi`) promises the code compiled against it, and the rules by which it may evolve from `1.0.0` |
| [ADMINISTRATION.md](ADMINISTRATION.md) | **Application administrators** | Install, configure, run; install/manage plugins; create and manage sites and application users; protection, backups, monitoring, upgrades |
| [SITE-MANAGER-GUIDE.md](SITE-MANAGER-GUIDE.md) | **Site managers & limited users (e.g. designers)** | Configure a site and its plugins; create users; roles & permissions; create/edit pages; the page-authoring contract for designers |
| [OPERATIONS.md](OPERATIONS.md) | Operators | Day-2 operations: health checks, troubleshooting, tuning, backup/restore, incident recovery |
| [GLOSSARY.md](GLOSSARY.md) | Everyone | The shared vocabulary used across these documents |
| [SETTINGS-REFERENCE.md](SETTINGS-REFERENCE.md) | Operators | Every setting: what it does, its values and default, and where it is set — which console screen, or the server only and why (generated) |
| [CONFIGURATION-AND-DATA-STABILITY.md](CONFIGURATION-AND-DATA-STABILITY.md) | Operators, plugin authors, monitoring | What stays compatible from `1.0.0` outside the Java API: every `runway.*` key, the data folder file by file, the backup format, `plugin.yml`, public paths, metric and logger names — and what is **not** covered |
| [KNOWN-LIMITATIONS.md](KNOWN-LIMITATIONS.md) | Everyone | What the code does **not** do yet (or does partially), and what is decided to come after `1.0.0` — read before evaluating a release |
The repository root also carries [`../CHANGELOG.md`](../CHANGELOG.md), and
[`../monitoring/README.md`](../monitoring/README.md) describes the bundled Prometheus and Grafana
assets: exposing `/actuator/prometheus` with a scrape token, the alert rules, the dashboard, and
the metrics they use.
## Document conventions
- **Self-contained.** Each document explains Runway directly. Cross-links point only within
this delivered set.
- **Status.** Runway is built kernel-first, and each change ships with its documentation. Every section
covering a built feature is written; the delivered set no longer carries `_Pending_` placeholders.
[KNOWN-LIMITATIONS.md](KNOWN-LIMITATIONS.md) is the honest, current list of what Runway does not yet do.
+278
View File
@@ -0,0 +1,278 @@
# Settings reference
<!-- GENERATED by scripts/dev/gen-settings-reference.py — do not edit; edit its sources and run it again. -->
Every setting the Runway kernel and its essential protection plugin read: what it does, the values it takes, and where you set it. Per-site settings are made on the site console's screens (SITE-MANAGER-GUIDE.md); optional plugins document their own settings.
## How settings are layered
- **The console** keeps what you set on its screens in `external/platform.yml` (platform) and in each site's folder (that site). Only values that differ from the default are stored. A blank field restores the default; a blank token field keeps the stored token.
- **The server** can set any key in `external/application.yml`, an environment variable (`RUNWAY_CSP_MODE` for `runway.csp.mode`) or a command-line argument. **A value set there wins**, and the console shows that field disabled with where it is set, and what removing it there would do. To move a key to the console in one restart, click **Use the file's value** on its row first (it copies the value the server runs with), then remove the line and restart: nothing changes (ADMINISTRATION.md §8).
Two exceptions. *Password strength* (`runway.security.password-strength`): the value chosen on Platform settings wins over every server source, and the field is never locked. *The protection plugin's settings* (section 2): `external/plugin-settings/protection.yml`, which its settings screen writes, wins over `external/application.yml`, and the form shows no lock; an environment variable or a command-line argument still wins over both.
- **When a change applies:** the settings in section 1 apply after the next restart (the form says which are pending). Settings on the other screens in section 2 say when they apply.
- **Kept out of the console on purpose:** the settings in section 3, each with the reason.
## 1. Console settings: Server settings and the policy cards
### Settings → Server settings
Screen: `/__app/config/server` (platform administrators). Applies after a restart.
#### Content-Security-Policy
The browser security policy every page is sent with. It limits where scripts, styles, images and frames may come from. Applies after a restart.
| Setting | Key | What it does | Values |
|---|---|---|---|
| Mode | `runway.csp.mode` | report sends the policy as report-only (violations are logged, nothing is blocked); enforce blocks what the policy does not allow; off sends no policy. | one of `report`, `enforce`, `off`; default `report` |
| Use strict-dynamic (master switch) | `runway.csp.strict-dynamic` | A script the page loaded with its nonce may load further scripts. On: console pages use it, and public pages too while the switch below is on. Off rolls every page, console and public, back to the host lists below. | `true` or `false`; default `true` |
| Use strict-dynamic on public pages | `runway.csp.public-strict-dynamic` | Public pages get a nonce and strict-dynamic too. Needs the switch above. | `true` or `false`; default `true` |
| Extra allowed hosts (all sites) | `runway.csp.extra-hosts` | Every site's pages may load from these hosts, e.g. https://www.youtube.com. They are added to scripts, styles, images, fonts, connections and frames. For a host only one site needs, use Settings → Embed hosts instead. | comma-separated list; default empty |
| Upgrade insecure requests | `runway.csp.upgrade-insecure-requests` | The browser fetches http:// resources over https:// instead. | `true` or `false`; default `false` |
| Report URI *(Advanced)* | `runway.csp.report-uri` | Where browsers send violation reports. The default is Runway's own collector, which writes them to the log. A blank field restores this default; to send no reports at all, set runway.csp.report-uri: "" in external/application.yml. | text; default `/__csp-report` |
| default-src *(Advanced)* | `runway.csp.default-src` | The source list for anything without its own directive. A blank field restores 'self'; to leave the directive out, set the key to "" in external/application.yml. | text; default `'self'` |
| script-src *(Advanced)* | `runway.csp.script-src` | Script sources. The page's nonce (and strict-dynamic, when on) is always added. | text; default `'self'` |
| style-src *(Advanced)* | `runway.csp.style-src` | Style sources. | text; default `'self' 'unsafe-inline'` |
| img-src *(Advanced)* | `runway.csp.img-src` | Image sources. | text; default `'self' data:` |
| font-src *(Advanced)* | `runway.csp.font-src` | Font sources. | text; default `'self'` |
| connect-src *(Advanced)* | `runway.csp.connect-src` | Where scripts may connect (fetch, XHR, WebSocket). | text; default `'self'` |
| base-uri *(Advanced)* | `runway.csp.base-uri` | Allowed values of a page's <base> element. | text; default `'self'` |
| form-action *(Advanced)* | `runway.csp.form-action` | Where forms may submit. | text; default `'self'` |
| frame-ancestors *(Advanced)* | `runway.csp.frame-ancestors` | Which sites may show these pages in a frame. 'none' forbids all. | text; default `'self'` |
#### Request limits
How large a request may be. Applies after a restart.
| Setting | Key | What it does | Values |
|---|---|---|---|
| Largest request before sign-in (bytes) | `runway.endpoints.max-form-bytes` | The most a visitor who is not signed in may send in one request, on any path. Default 262144 (256 KiB). | whole number from 1024 to 104857600; default `262144` |
| Largest request to a plugin (bytes) | `runway.endpoints.max-body-bytes` | The most a signed-in user may send to a plugin's route. Default 10485760 (10 MiB). | whole number from 1024 to 1073741824; default `10485760` |
| Largest uploaded file | `spring.servlet.multipart.max-file-size` | For uploads such as a backup to restore. A size like 256MB or 1GB. Default 256MB. | text; default `256MB` |
| Largest upload request | `spring.servlet.multipart.max-request-size` | All the files of one upload together. A size like 256MB. Default 256MB. | text; default `256MB` |
#### Site storage
How much each site may keep in its static files and documents. A site's own limit, set on Sites, wins over this default. Applies after a restart.
| Setting | Key | What it does | Values |
|---|---|---|---|
| Storage per site (bytes) | `runway.static-files.default-max-bytes` | The most a site's static files and documents may take on disk. An upload that would go over it is refused; nothing already stored is deleted or hidden, and a site over it can still delete. 0: no limit. Default 0. | whole number from 0 to 9223372036854775807; default `0` |
#### HTTP caching
The Cache-Control header pages and files are sent with. A page's own cache setting in the page editor wins over these. Applies after a restart.
| Setting | Key | What it does | Values |
|---|---|---|---|
| Public pages | `runway.http-cache.public-pages` | Default: browsers and caches keep a page 5 minutes and may serve it 1 more minute while refreshing. | text; default `public, max-age=300, stale-while-revalidate=60` |
| Site files | `runway.http-cache.assets` | Files under a site's /static/ (except the immutable kinds below). Default: one day. | text; default `public, max-age=86400` |
| Plugin files | `runway.http-cache.plugin-assets` | Files plugins serve under /__plugin/ (their styles and scripts). Default: one hour, then checked against the file's content. | text; default `public, max-age=3600` |
| Immutable file types | `runway.http-cache.immutable-extensions` | Extensions served as never changing (fonts by default). Give such files a new name when they change. | comma-separated list; default `woff2,woff,ttf,otf,eot` |
| Immutable files *(Advanced)* | `runway.http-cache.immutable-assets` | The header for the types above. Default: one year, immutable. | text; default `public, max-age=31536000, immutable` |
#### Response compression (tuning)
Fine-tuning for the compression switches above. Applies after a restart.
| Setting | Key | What it does | Values |
|---|---|---|---|
| Smallest body to gzip (bytes) | `runway.compression.gzip.min-size` | Default 1024. | whole number from 0 to 10485760; default `1024` |
| Smallest body to Brotli-encode (bytes) | `runway.compression.brotli.min-size` | Default 1024. | whole number from 0 to 10485760; default `1024` |
| Brotli quality | `runway.compression.brotli.quality` | 0 is fastest, 11 smallest; 4 to 6 suit compressing on the fly. Default 5. | whole number from 0 to 11; default `5` |
| Largest body to compress (bytes) *(Advanced)* | `runway.compression.max-buffer-bytes` | Larger responses are sent uncompressed. Default 4194304 (4 MiB). | whole number from 65536 to 268435456; default `4194304` |
| Compressed content types *(Advanced)* | `runway.compression.mime-types` | The whole list: what you enter replaces it. | comma-separated list; default `text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json,application/xml,image/svg+xml` |
#### Monitoring
The health probe each site answers at /__health, the metrics endpoint, and the site reload endpoint. Applies after a restart.
| Setting | Key | What it does | Values |
|---|---|---|---|
| Answer the health probe (/__health) | `runway.health.enabled` | Off: /__health is not served. | `true` or `false`; default `true` |
| Check the site's content too | `runway.health.content-check` | The probe also checks that the home page and the master template are there. | `true` or `false`; default `true` |
| Content check result kept for (seconds) *(Advanced)* | `runway.health.content-check-ttl-seconds` | Default 10. | whole number from 1 to 3600; default `10` |
| Health detail token | `runway.health.token` | A probe that sends it as a Bearer token gets the detailed body. Never set: only the public answer. A blank field keeps the stored token; type a new one to replace it. | secret (stored encrypted, never shown); default empty |
| Metrics scrape token | `runway.metrics.scrape-token` | Lets a monitoring system read /actuator/prometheus with this Bearer token. Never set: only signed-in operators can. A blank field keeps the stored token; type a new one to replace it. | secret (stored encrypted, never shown); default empty |
| Site reload endpoint | `runway.reload.enabled` | Lets a deployment script make a site re-read its files. Inactive until the token is set. | `true` or `false`; default `true` |
| Reload token | `runway.reload.token` | The Bearer token the reload endpoint requires. A blank field keeps the stored token; type a new one to replace it. | secret (stored encrypted, never shown); default empty |
#### Site logs
The access and audit log each site keeps (its Logs and Insights screens). Applies after a restart.
| Setting | Key | What it does | Values |
|---|---|---|---|
| Keep site logs | `runway.logs.enabled` | Off: no site records new access or audit lines; the Logs screen keeps the lines already written, Insights shows nothing. | `true` or `false`; default `true` |
| Longest a site may keep its logs (days) | `runway.logs.max-retention-days` | Each site chooses its own retention up to this. Default 90. | whole number from 1 to 3650; default `90` |
| Record the browser (User-Agent) | `runway.logs.access-log-user-agent` | Adds the User-Agent to each access line. | `true` or `false`; default `false` |
| Log queue size (lines) *(Advanced)* | `runway.logs.queue-capacity` | Lines waiting to be written; beyond it lines are dropped and counted. Default 8192. | whole number from 16 to 1048576; default `8192` |
#### Console languages
The languages this console's language switcher offers. Applies after a restart.
| Setting | Key | What it does | Values |
|---|---|---|---|
| Languages offered | `runway.operator.ui-languages` | Language codes in display order. Each needs a console translation: en and es ship, others go in external/i18n/. | comma-separated list; default `en,es` |
| Default language | `runway.operator.default-language` | Used when the browser asks for none of the languages offered. | text; default `en` |
#### Sessions
How long a signed-in console session lasts without activity. Applies after a restart.
| Setting | Key | What it does | Values |
|---|---|---|---|
| Idle session timeout | `server.servlet.session.timeout` | A duration such as 30m, 2h or 1d. Default 30m. | text; default `30m` |
#### Reverse proxy
Whether to trust X-Forwarded-* headers, and from which addresses. Only from your own proxy: otherwise visitors could fake their address. Applies after a restart.
| Setting | Key | What it does | Values |
|---|---|---|---|
| Read X-Forwarded-* headers | `runway.proxy.forwarded-headers` | From the trusted addresses below only. | `true` or `false`; default `true` |
| Trusted proxy addresses | `runway.proxy.trusted-cidrs` | The exact address of your reverse proxy, e.g. 10.0.0.5/32. A /0 (0.0.0.0/0, ::/0), or ranges that add up to every address (0.0.0.0/1 with 128.0.0.0/1), would trust every client to fake its address, so it is refused. | comma-separated list; default `127.0.0.1/32,::1/128` |
#### Capacity
Threads and concurrency limits. The defaults suit most servers; raise them only for measured load. Applies after a restart.
| Setting | Key | What it does | Values |
|---|---|---|---|
| Most request threads | `server.jetty.threads.max` | Default 200. | whole number from 8 to 10000; default `200` |
| Fewest request threads *(Advanced)* | `server.jetty.threads.min` | Default 8; never above the most. | whole number from 1 to 1000; default `8` |
| Message file re-check (seconds) *(Advanced)* | `runway.i18n.cache-seconds` | How often a site's message files are checked for changes made outside the console (Messages screen saves apply at once). 0: on every use. Default 5. | whole number from 0 to 3600; default `5` |
| Scheduler threads *(Advanced)* | `spring.task.scheduling.pool.size` | Threads for backups and plugin jobs. Default 4. | whole number from 1 to 64; default `4` |
| Password checks at once *(Advanced)* | `runway.security.max-concurrent-hashes` | Each takes about 19 MiB (32 MiB with the High profile). Beyond it, sign-ins wait. Default 8. | whole number from 1 to 256; default `8` |
| Longest wait for a password check (ms) *(Advanced)* | `runway.security.acquire-timeout-millis` | Then the sign-in answers "busy". Default 2000. | whole number from 100 to 60000; default `2000` |
#### Protection logging
What the request protection writes to the log when it refuses a request. Applies after a restart.
| Setting | Key | What it does | Values |
|---|---|---|---|
| Log refused requests | `runway.protect.log-rejections` | One line per refused request (403 or 429). The count in the metrics is kept either way. | `true` or `false`; default `true` |
| Repeat lines suppressed for (seconds) | `runway.protect.log-rejection-window-seconds` | For the same address and reason; the next line says how many were suppressed. Default 60. | whole number from 1 to 86400; default `60` |
### Backups → Settings (backup policy)
Screen: `/__app/config/backups` (platform administrators). Applies after a restart.
#### Backup policy
Automatic backups of every site, and how many stored backups are kept. Applies after a restart.
| Setting | Key | What it does | Values |
|---|---|---|---|
| Back up every site automatically | `runway.backups.schedule.enabled` | On the schedule below. | `true` or `false`; default `false` |
| Schedule | `runway.backups.schedule.cron` | Six fields: second minute hour day month weekday. Default 0 30 2 * * * (02:30 every day). | text; default `0 30 2 * * *` |
| Stored backups kept per site | `runway.backups.retention.max-count` | The newest this many are kept; 0 keeps all. Default 30. | whole number from 0 to 100000; default `30` |
| Delete stored backups older than (days) | `runway.backups.retention.max-age-days` | 0: no age limit. Default 0. | whole number from 0 to 36500; default `0` |
| Largest file inside a backup to restore (bytes) *(Advanced)* | `runway.backups.max-entry-bytes` | A guard against archives that expand without limit. Default 268435456 (256 MiB). | whole number from 1048576 to 17179869184; default `268435456` |
### Bandwidth → Settings (metering and quota)
Screen: `/__app/config/bandwidth` (platform administrators). Applies after a restart.
#### Metering and quota
Per-site traffic counting, its history, and the monthly cap. Applies after a restart.
| Setting | Key | What it does | Values |
|---|---|---|---|
| Count each site's traffic | `runway.bandwidth.enabled` | Off: nothing new is counted and no cap is enforced; the Bandwidth screens keep the history already recorded. | `true` or `false`; default `true` |
| Monthly cap per site (bytes) | `runway.bandwidth.quota.default-monthly-bytes` | Outbound bytes in the last 30 days; above it the site's public pages answer 503 (its console keeps working). 0: no cap. A site's own cap is set on Sites. | whole number from 0 to 9223372036854775807; default `0` |
| Keep traffic history (days) | `runway.bandwidth.retention-days` | Default 90. | whole number from 1 to 3650; default `90` |
| Counting interval (seconds) *(Advanced)* | `runway.bandwidth.snapshot-seconds` | Also how often the cap is checked. Default 60. | whole number from 1 to 3600; default `60` |
### Activity → Logs → Settings (activity log retention)
Screen: `/__app/config/activity` (platform administrators). Applies after a restart.
#### Activity log
How long the console's activity log is kept. Applies after a restart.
| Setting | Key | What it does | Values |
|---|---|---|---|
| Keep the activity log (days) | `runway.app-activity.retention-days` | Default 90. Switching the log off is set on the server only, so it cannot be done by the people it records. | whole number from 1 to 3650; default `90` |
### Plugins → Settings (plugin limits)
Screen: `/__app/config/plugins` (platform administrators). Applies after a restart.
#### Plugin limits
Size limits for installing plugins and for the files plugins keep per site. Applies after a restart.
| Setting | Key | What it does | Values |
|---|---|---|---|
| Largest file inside a plugin to install (bytes) | `runway.plugins.max-entry-bytes` | Default 134217728 (128 MiB). | whole number from 1048576 to 4294967296; default `134217728` |
| Largest file a plugin keeps per site (bytes) | `runway.plugins.site-files.max-write-bytes` | Default 16777216 (16 MiB). | whole number from 1024 to 1073741824; default `16777216` |
## 2. Settings edited on other console screens
| Key | Where |
|---|---|
| `runway.compression.enabled` | Settings → Platform settings, Response compression (applies at once) |
| `runway.compression.brotli.enabled` | Settings → Platform settings, Response compression (applies at once) |
| `runway.compression.gzip.enabled` | Settings → Platform settings, Response compression (applies at once) |
| `runway.node.name` | Settings → Platform settings, Node name (the console's value wins over this key) |
| `runway.security.password-strength` | Settings → Platform settings, Password strength (applies to new passwords after a restart; the console's value wins over this key) |
| `runway.bandwidth.quota.per-site` | Sites → Edit, Monthly bandwidth cap, per site (applies at once) |
Log levels (`logging.level.<logger>`) are set on **Activity → Logs → Log levels** (`/__app/logs/levels`): they apply at once and are kept in `platform.yml`; a level set in `application.yml` wins and shows locked.
The essential protection plugin's settings are on **Plugins → Essential Protection → Settings** (`/__app/plugins/protection/settings`). They are stored in `external/plugin-settings/protection.yml` and bound as `runway.plugin.protection.<key>`; they apply after a restart. Its login protection (honeypot, lockout, CAPTCHA) is the panel below that form and applies at once; each site has its own on `/__admin/protection`.
#### Rate limit
| Setting | Key | What it does | Values |
|---|---|---|---|
| Rate-limit burst capacity | `runway.plugin.protection.rate-limit.capacity` | How many requests one address may make back to back before it is slowed down. Default 120. | whole number from 1 to 100000; default `120` |
| Rate-limit refill per second | `runway.plugin.protection.rate-limit.refill-per-second` | How many requests per second an address gets back after a burst. Default 2; 0.5 means one every two seconds. Must be above 0. | number from 0.01 to 10000; default `2` |
#### Auto-block
| Setting | Key | What it does | Values |
|---|---|---|---|
| Auto-block repeat offenders | `runway.plugin.protection.rate-limit.auto-block.enabled` | Off: an address over the limit only gets 429s and is never blocked. | `true` or `false`; default `true` |
| Auto-block after this many rate-limit breaches | `runway.plugin.protection.rate-limit.auto-block.breach-threshold` | How many 429s within the window before the address is blocked. Default 60. | whole number from 1 to 100000; default `60` |
| Counted within (seconds) | `runway.plugin.protection.rate-limit.auto-block.window-seconds` | The period the 429s are counted over. Default 60 seconds. | whole number from 1 to 86400; default `60` |
| Auto-block duration (seconds) | `runway.plugin.protection.rate-limit.auto-block.block-seconds` | How long an auto-block lasts; the visitor gets 429 with the remaining time in Retry-After. Default 900 (15 minutes). | whole number from 1 to 604800; default `900` |
#### Exemptions
| Setting | Key | What it does | Values |
|---|---|---|---|
| Never rate-limit or auto-block these IPs/CIDRs (your own audits, probes, load tests) | `runway.plugin.protection.allowlist` | One IP or CIDR per line, e.g. 203.0.113.7 or 198.51.100.0/24. For your own audits, probes and load tests. Loopback is not exempt unless listed: behind a same-host proxy every visitor arrives from loopback. | comma-separated list; default empty |
#### Remember this device
| Setting | Key | What it does | Values |
|---|---|---|---|
| Allow "remember this device" (skip the login captcha on trusted devices) | `runway.plugin.protection.remember-device.enabled` | Off: the login CAPTCHA is shown on every login. | `true` or `false`; default `true` |
| Remember a device for (days) | `runway.plugin.protection.remember-device.days` | How long a device is remembered, 1 to 365. Default 30. | whole number from 1 to 365; default `30` |
## 3. Server-only settings, and why
Set these in `external/application.yml` (or the environment). They stay out of the console because the console cannot change them safely, or cannot exist until they are known.
| Keys | Why not in the console |
|---|---|
| `runway.app-activity.enabled` | It switches off the operator activity log. If the console could turn it off, an operator could silence the record of their own actions. |
| `runway.backups.offsite-dir` | A folder on the server that receives full site archives (user records, encrypted plugin secrets). Set from a browser it could point into a web-served folder or another site's folder; choosing and mounting the share is the server administrator's job. Shown read-only on Backups. |
| `runway.cluster.enabled`<br>`runway.cluster.cluster-name`<br>`runway.cluster.topology`<br>`runway.cluster.session-ttl`<br>`runway.cluster.sessions-map-name`<br>`runway.cluster.events-topic-name`<br>`runway.cluster.embedded.discovery`<br>`runway.cluster.embedded.members`<br>`runway.cluster.embedded.port`<br>`runway.cluster.embedded.port-auto-increment`<br>`runway.cluster.client.addresses`<br>`runway.cluster.client.smart-routing` | Read before the application is built (the cluster member and the shared session store are created at startup), and every node must hold the same value; one node's console cannot change the others. |
| `runway.console.hosts` | The host names the operator console answers on. A wrong value would lock every operator out of the console, so the console cannot be the place to change it: the file on the server is the way back in. Read at startup; each node of a cluster reads its own. |
| `runway.demo.first-run.id`<br>`runway.demo.first-run.host`<br>`runway.demo.first-run.master-username`<br>`runway.demo.first-run.master-password` | Used once, on the first start of an unattended evaluation box, before any operator exists to sign in. The console equivalent is Sites → Install a demo site. |
| `runway.plugins.root` | Read before the application starts: the plugin loader finds the plugins there before the console exists, and the folder decides what code the server runs. |
| `runway.security.app-master-id` | The trust anchor that pins the undeletable application superadmin, read before the application starts; set by the setup wizard and never edited by hand. |
| `runway.security.secret-key` | The key that encrypts every other stored secret. Typing it into a browser would put it on the wire, and changing it would make every stored secret unreadable; the installer keeps it in a root-only file. |
| `runway.storage.external`<br>`runway.storage.sites` | Read before the application starts: the data folder holds application.yml, platform.yml and every site, so the console cannot live anywhere until it is known. |
| `runway.storage.backups` | Read before the application starts, like the data folder, and it receives full site archives (the same reason as runway.backups.offsite-dir). |
| `runway.storage.stats`<br>`runway.storage.logs` | Retired before 1.0 and has no effect; a value set in application.yml is reported once at startup. |
| `runway.tls.enabled`<br>`runway.tls.keystore`<br>`runway.tls.keystore-password`<br>`runway.tls.keystore-type`<br>`runway.tls.key-alias`<br>`runway.tls.sni-host-check`<br>`runway.tls.watch-keystore`<br>`runway.tls.redirect-http.enabled`<br>`runway.tls.redirect-http.port`<br>`runway.tls.redirect-http.status`<br>`runway.tls.redirect-http.acme-challenges-dir` | Read before the server starts serving: the HTTPS and redirect listeners are built from it at startup, and a wrong value set from the console could make the console itself unreachable. The certificate files and their password belong to the server. |
Spring Boot keys Runway pins in its shipped `application.yml` (for example `server.forward-headers-strategy`, `spring.web.resources.add-mappings`, `spring.security.filter.order`) are part of how the platform works, not preferences: do not change them. ADMINISTRATION.md §8 lists them.
File diff suppressed because it is too large. Load diff
+244
View File
@@ -0,0 +1,244 @@
# SPI stability commitment
This document states what Runway's extension API (`runway-spi`) guarantees to the code that compiles against
it — plugins and any first-party extension — and the rules by which it may evolve. It is the promise a plugin
author relies on when they build against a released `runway-spi` and expect their jar to keep loading on a
later Runway.
> **Status: in force from SPI `1.0.0` (Runway `1.0.0`).** The surface below — 56 types in three packages — is
> **frozen**: from here it changes only additively, within the `1.x` line, by the rules in this document. It includes
> the service tier (SPI `0.4.0`–`0.6.0`) through which a plugin reaches the host instead of importing host-internal
> classes. From `1.0.0` the kernel **enforces** the contract at load time: a plugin built for the pre-1.0 contract,
> one that links a kernel class, and one that breaks the Spring-context rules are each **blocked** with a reason on
> the plugins screen (see "How the kernel enforces it" below).
## What the SPI is
`runway-spi` is a **dependency-free** module: the extension interfaces (`mx.quest.runway.spi`), the immutable
boundary model they exchange (`mx.quest.runway.spi.model`) and the host services a plugin receives by injection
(`mx.quest.runway.spi.service`). It depends on **nothing** in the host — a plugin compiles against this thin, stable
artifact (and `runway-spi-testkit` for its tests), never against `runway-app`. `RunwaySpi.VERSION` is the contract
version an extension was built against — a compile-time constant, so the compiler copies it into the plugin;
`RunwaySpi.runtimeVersion()` reports the version of the kernel actually running.
**The 1.0 contract is the SPI alone.** Everything a plugin needs from the host — its settings, its per-site files,
the site's content and URLs, change events, the current request's site, permission checks, messages, starter pages,
console screens — is in the tables below. A plugin that needs something else has found a gap in the SPI; it is
added (additively) in a 1.x MINOR, never reached around.
## The surface (SPI `1.0.0`)
"Since" is the SPI version that introduced the type; every type is part of the `1.0.0` contract regardless.
### Extension axes — interfaces a plugin implements, collected by type
| Type | Since | Lifecycle method | Purpose |
|---|---|---|---|
| `HeadContributor` | 0.1 | `render(HeadContext) → String`, `headInputs(path)` | edge `<head>` markup injected on every page |
| `ContentWidget` | 0.1 | `render(WidgetView) → RenderFragment` | body content at a `data-widget` anchor |
| `PageQualityCheck` | 0.1 | `inspect(PageView) → List<Finding>` | content/SEO checks — advisory by default; an `ERROR` gates publishing on a site set to Enforced/Reviewed |
| `EndpointContributor` | 0.1 | `routes()`, `handle(RouteRequest) → RouteResponse` | servlet-free HTTP routes on the tenant realm |
| `ContentSource` | 0.3.0 | `enumerate` / `resolve` / `body` / `indexableText` | routable plugin content (virtual pages) fed to routing, the catalog, sitemap/llms.txt and search |
| `BackupParticipant` | 0.1 | `export` / `importInto` | per-site data kept **outside** the site folder (no first-party plugin has any; the plugin's own subtree already travels in the backup) |
| `CaptchaService` | 0.2.1 | `widget` / `verify` | the configured CAPTCHA (implemented by the essential plugin, consumed by any plugin with a public form) |
| `SiteLoginProtectionControl` | 0.2.1 | per-site login-protection toggles | implemented by the essential plugin |
`FilterBand` (enum, 0.1) remains in the SPI as an **identity** only: it names the request-pipeline band of a filter
contribution, a host-coupled seam that is not part of the 1.0 contract (see "What is NOT part of this contract").
### Service tier — interfaces the kernel implements, received by ordinary Spring injection
| Type | Since | Scope | What it gives a plugin |
|---|---|---|---|
| `service.PluginSettings` (+ `model.SettingsView`) | 0.4.0 | plugin-scoped | its per-site settings, defaults applied, and its declared secrets decrypted (app-level settings bind through `@ConfigurationProperties("runway.plugin.<id>")`, not this service) |
| `model.PluginInfo` | 0.4.0 | plugin-scoped | its own id, version and install facts |
| `service.PluginLifecycle` | 0.4.0 | callback | `started(PluginInfo)` / `stopping()`, in load order and reverse |
| `service.PluginSiteFiles` (+ `model.FileEntry`) | 0.5.0 | plugin-scoped | its own per-site subtree `sites/<id>/plugins/<pluginId>/`: atomic text writes, capped reads, listing, deletes; confined against crafted paths **and** symbolic links |
| `service.Sites` | 0.5.0 | kernel singleton | a site's `SiteView` by id, off-request |
| `service.RequestContext` | 0.5.0 | kernel singleton | the tenancy the current request is bound to; empty on the application realm and off a request |
| `service.AccessCheck` | 0.5.0 | kernel singleton (bean `authz`) | `may(permissionKey)` for the current principal, fail-closed |
| `service.Messages` | 0.5.0 | kernel singleton | public text by an explicit site id; console text in the operator's UI language |
| `service.SitePages` (+ `model.StarterPage`, `model.InstallResult`) | 0.5.0 | kernel singleton | install a starter page through the site's editorial level |
| `service.ContentCatalogView` (+ `model.CatalogEntry`, `model.LocalizedUrl`) | 0.6.0 | kernel singleton | the site's published content surface with the URLs the host computed (the same addresses the `<head>`, the sitemap and llms.txt use) |
| `service.ContentChanges` | 0.6.0 | plugin-scoped | announce that its own content changed (evicts routing, listings, sitemap and search on every node; notifies listeners) |
| `service.SiteEventListener` (+ `model.SiteLifecycleEvent`, `model.SettingsChange`, `model.CatalogChange`) | 0.6.0 | callback | site lifecycle, its **own** settings saves, every change that may reshape the content surface — phased, after the kernel's caches, outside every host lock, with the item's URLs before and after |
| `service.ConsoleScreen` | 0.6.0 | annotation | a plugin `@Controller` that renders inside the console shell, with no host class |
A plugin-scoped service is bound to the plugin **whose own jar the injecting class came from**, never to an id the
plugin passes, so a plugin can only reach its own data. Rules every service keeps: no method returns `null`; an unsafe
site id (or slug, or path) throws `IllegalArgumentException` before any I/O; every service is thread-safe; off a request
thread the request-bound services answer empty, `false` or the fallback and never throw. A plugin consumes these
interfaces; it does not implement them — an alternative host or a `runway-spi-testkit` fake does, which is why the
additive rules below apply to them unchanged.
### Boundary model — immutable records the host builds (and plugin tests construct)
`Alternate`, `Capabilities`, `CaptchaWidget`, `ContentBody`, `ContentRef`, `Finding`, `HeadContext`, `IconHints`,
`PageMeta`, `PageView`, `Provenance`, `RenderFragment`, `Route`, `RouteRequest`, `RouteResponse`, `SeoTags`, `SiteRef`,
`SiteView`, `SurfacePosture`, `WidgetView` (0.1–0.3); `SettingsView`, `PluginInfo` (0.4.0); `FileEntry`,
`StarterPage`, `InstallResult` (0.5.0); `CatalogEntry`, `LocalizedUrl`, `SiteLifecycleEvent`, `SettingsChange`,
`CatalogChange` (0.6.0). Two interfaces: `BackupReader`, `BackupWriter`. Enums: `Realm`, `Severity`, and the nested
`InstallResult.Outcome`, `CatalogChange.Cause`, `SiteLifecycleEvent.Kind`, `SiteEventListener.Phase`.
### What `1.0.0` itself changed
`1.0.0` freezes the surface; it adds one component and fixes one behaviour:
- **`HeadContext.origin()`** — the trusted origin (`scheme://host[:port]`) a page is served under: the site's base
URL, else, for a host-less site such as the platform's catch-all default, the request's origin as the trusted-proxy
gate left it. A head contributor builds absolute URLs (JSON-LD `@id`s) with it; before, a host-less site's
structured data was relative. The 0.6.0 constructor is kept (`origin` is `""` there).
- **`CatalogEntry.xDefaultPath` / `pathFor`** never name an address the item is not served at: when the site does
not serve an item's primary locale, x-default is the item's first **available** locale (it used to be the site
default, an unprefixed path the item may not exist at — which llms.txt then linked).
## The compatibility rules (in force from `1.0.0`)
The SPI is **binary API**. A plugin compiled against a released `runway-spi` keeps loading on any later version of
the same MAJOR line. That is upheld by evolving **additively only**:
1. **Interfaces evolve by adding `default` methods.** Never add an abstract method (it breaks every existing
implementation), never remove, rename, reorder or re-type an existing method.
2. **Records evolve by adding components with an older-arity constructor kept.** A record gains a field only
alongside a retained constructor (or static factory) of the previous arity, so code built against the old shape
still constructs it. Never reorder, re-type, or remove an existing component. (`HeadContext` keeps four
constructors for exactly this reason.) **Record deconstruction patterns are not source-stable across MINOR
versions** (a pattern names every component, so a new component breaks it at compile time); use the accessors.
3. **Enums may gain constants in a MINOR release.** A `switch` over an SPI enum needs a `default` branch.
4. **Optional behaviour is an opt-in capability, not a fat base.** Where only some implementations participate in a
concern, it is a separate interface or a `Capabilities` flag the host branches on — never a new abstract method.
The host is **capability-driven**: it branches on declared data, never on a concrete type or `instanceof` over a
known catalog.
5. **`key()` values are the forward-compatible contract with stored data.** A stable string `key()` — not the class
name — is persisted with tenant data, so an implementation class is free to move or rename. A duplicate key never
silently shadows: between two kernel contributions it fails startup; when a plugin is involved, the plugin's
contribution is refused — the later plugin's in load order between two plugins — logged with both sides and shown
on the plugins screen, while the plugin's other contributions load.
6. **`RunwaySpi.VERSION` bumps on each additive evolution** (MINOR for a new type, member or component; PATCH for a
documented behaviour fix). A pure Javadoc clarification that does not change the contract's meaning is not a bump.
The version is plain `MAJOR.MINOR.PATCH`; the evolution log on `RunwaySpi.VERSION` is what an author reads to pick
a floor.
7. **A MAJOR line is a hard boundary.** A breaking change lands only in a MAJOR (`2.0.0`), called out in the
changelog. The kernel's MAJOR line also pins the MAJOR lines of the **platform libraries** it provides at runtime
(Spring Framework, Spring Boot, Spring Security, Thymeleaf, Jackson, the Jakarta EE APIs), which a plugin compiles
against `provided`.
8. **The values of the SPI's string constants are frozen, not just their names.** A `static final String`
initialised with a literal is a compile-time constant: the compiler copies the *value* into the plugin's bytecode,
so a plugin built against `1.0.0` keeps using the `1.0.0` value whatever a later kernel declares. Each one names
something the kernel must keep providing under that exact string for the whole `1.x` line:
`ConsoleScreen.LAYOUT_VIEW` (`"operator/op-layout"` — the console layout template),
`ConsoleScreen.CONTENT_TEMPLATE` (`"contentTemplate"`) and `ConsoleScreen.PAGE_TITLE_KEY` (`"pageTitleKey"`)
(model attributes that layout reads), `AccessCheck.BEAN_NAME` (`"authz"` — the bean name in security
expressions), `ContentCatalogView.PAGES_SOURCE` (`"pages"` — the kernel's own content-source key), and
`ContentSource.CAP_INDEXABLE_TEXT` / `CAP_ARBITRARY_PATHS` (`"content.indexable-text"`,
`"content.arbitrary-paths"` — capability flags the host branches on). Renaming the template, the attribute, the
bean or the key in a `1.x` would break every plugin that uses it, silently and at run time. (`RunwaySpi.VERSION`
is inlined too, on purpose — it records what the plugin was built against.) A new constant follows the same rule
from the release that adds it.
## How the kernel enforces it (from `1.0.0`)
Every rule here **blocks** the plugin — it is not wired, the reason is logged and printed in its row on the
**Plugins** screen, plugins that `requires:` it are blocked in cascade, and the platform starts with everything else.
None of them is a boot failure.
| Rule | Refused | Reason shown |
|---|---|---|
| **Mandatory floor** | a plugin with a `mainClass` that declares no `requiresSpi`, or a floor below `0.4.0` (library-only plugins are exempt) | "was built for the pre-1.0 plugin contract …" |
| **Floor** | a floor above the running SPI | "needs Runway SPI X or later …" |
| **MAJOR ceiling** | `kernel MAJOR > max(floor MAJOR, 1)` — a floor of `0.4.0`–`0.6.0` counts as 1.x (the service tier those versions introduced *is* the 1.0 contract); a 1.x floor is refused by a 2.x kernel | "was built for Runway SPI 1.x …" |
| **Host linkage** | a class in the plugin's own jars that references a kernel class outside `mx.quest.runway.spi` (read from the constant pool, without loading the class), or a plugin class living under `mx.quest.runway` | "uses Runway's internal classes …", naming them |
| **Missing SPI types** | an SPI type the running kernel does not have (a missing or wrong floor) | "needs SPI types this Runway does not have …" |
| **Spring-context rules** (before wiring) | a `@Bean` name not starting with the plugin id in lowerCamelCase; a `SecurityFilterChain`, servlet `Filter`, `FilterRegistrationBean`, `BeanPostProcessor` or `BeanFactoryPostProcessor`; a `@Controller` mapping outside `/__admin/<id>` and `/__app/<id>`; an unrestricted `@ControllerAdvice` | "breaks the plugin rules for Runway's shared Spring context …" |
| **Spring-context rules** (after wiring) | the same, found on a component-scanned bean the first check cannot see | the plugin is **quarantined**: the boot ends with the relaunch code (`42`) and the next boot blocks it with that reason |
| **Wiring failure** | a plugin bean that breaks the context refresh | quarantined the same way |
| **Essential dependency** | a `requires:` on the essential plugin | "requires the essential plugin …" |
A plugin's calls that fail at run time are contained instead (next section). The kernel also refuses individual
**contributions** without blocking the plugin: a colliding key, a route that is not exact or not on the tenant realm.
## The purity & isolation guarantees
Every model type is **immutable and host-built**, with collection/array components defensively copied and
null-normalized in the compact constructor — so a view handed to an implementation cannot be mutated by it or by
whoever built it. An extension-axis implementation is therefore a **pure function of its inputs**: it never sees
drafts, other versions, other tenants or other requests, and returns plain values. That keeps it trivially
unit-testable (no Spring, no I/O — `runway-spi-testkit` fakes the services), keeps tenant isolation outside the
extension, and lets the host evolve storage without touching an implementation.
- **`PageQualityCheck.inspect` must return non-null.** An empty list means "nothing to report".
- **`RouteRequest` / `RouteResponse` carry a `byte[] body`**, so their record-generated `equals`/`hashCode` compare it
by reference; do not rely on record equality for such instances. `body()` returns a fresh copy.
- **A `ContentSource` reads only its own per-tenant subtree and settings**, returns only published content with safe
paths, and keeps `enumerate()` metadata-only (it runs on anonymous requests — the sitemap). The kernel re-checks the
first two fail-closed.
## Failure containment (the host's side of the contract)
Every call the host makes into plugin code on a request, dispatch or scheduler path is contained: a
`RuntimeException` or `LinkageError` from `HeadContributor.render`/`headInputs`, `ContentWidget.render`,
`PageQualityCheck.inspect`, `EndpointContributor.handle`, a `ContentSource` method, `PluginLifecycle`,
`SiteEventListener`, `BackupParticipant.importInto` or a plugin's **`@Scheduled` method** (from `1.0.0`) is caught and
replaced — an empty head fragment or widget (that page is then served `Cache-Control: no-store` without validators),
one `WARNING` finding `check.failed` (which never blocks a publish), an endpoint `500` with `no-store`, a skipped
callback or scheduled run (the next run happens on schedule). A `null` where the axis forbids it counts as a failure.
Any other `Error` propagates. `BackupParticipant.export` is deliberately not contained: its failure fails the backup.
The first failure per plugin, axis and key is logged with its stack, then at most once a minute with a count; each is
counted in `runway.plugin.contribution.failures{plugin,axis,key}` and shown on the plugins screen. There is no circuit
breaker: a throwing contributor costs a stack unwind, not a timeout.
## What is NOT part of this contract
- **Kernel classes** (`mx.quest.runway.*` outside `.spi`): storage, sites, pages, the catalog, the host's Spring
events, the console model, the security seams. A plugin that links one is blocked.
- **Servlet filters and Spring Security chains** (`FilterContribution`, `SecurityFilterChain`): servlet- and
Spring-shaped, and able to reach every request; a non-essential plugin may not contribute them. A separate
`runway-spi-servlet` module may be added in a 1.x if a real consumer appears.
- **The kernel's events** (`PageChangedEvent`, `ContentChangedEvent`, `SiteChangedEvent`,
`SitePluginConfigChangedEvent`): internal and cluster-relayed. Plugins observe changes through `SiteEventListener`
and announce them through `ContentChanges`.
- **The URL scheme** (locale prefixes, localized slugs): plugins receive computed URLs, never the rule.
### The essential-plugin exception
A plugin on the kernel's security-floor allowlist — today only **`protection`** — is **part of the kernel
distribution**: built in the Runway reactor, released in the same tag, versioned on the kernel's line (`1.0.0`),
and declaring `requiresSpi: ">=1.0.0"`. It is exempt from the linkage scan and the Spring-context rules, because it
implements the security floor itself (`EdgeGuard`, `LoginAttemptGate`, `LoginFormGuard`, `TrustedDeviceIssuer` and
their collaborators). It still uses the service tier wherever one exists (`@ConsoleScreen`, `RequestContext`). No
plugin may `requires:` it — consumers use `CaptchaService`. If it is installed but does not load — for any reason,
including the floor rules — the platform **fails closed** (tenant pages answer `503`) rather than run without its
security floor. It is not an example to copy.
### The descriptor promise
`plugin.yml` is parsed by the host without loading plugin code, with unknown keys ignored in both directions, so a
descriptor written for a newer kernel loads on an older one and the other way round. Within `1.x` a key keeps its
meaning and new keys are optional — except that, from `1.0.0`, a plugin with a `mainClass` **must** declare
`requiresSpi` (see the mandatory floor above). The keys, their tolerance rules, the configuration namespace, the
on-disk data layout, the backup format, metric names and public paths are covered by the companion commitment
[CONFIGURATION-AND-DATA-STABILITY.md](CONFIGURATION-AND-DATA-STABILITY.md).
## For extension authors
- Depend on `runway-spi` (`provided`) and `runway-spi-testkit` (`test`) — never on `runway-app`. Declare
`requiresSpi` with the lowest version whose additions you use (the evolution log on `RunwaySpi.VERSION`).
- **Where the jars come from.** No Maven repository serves them: every kernel release on
the releases page (<https://g.quest.mx/quest/runway/releases>) attaches `runway-spi-<ver>.jar`, `runway-spi-testkit-<ver>.jar`,
their sources jars and their (standalone) poms, all listed in the release's `SHA256SUMS`. Verify them, install
each with `mvn install:install-file -Dfile=<jar> -DpomFile=<pom> -Dsources=<sources jar>`, then depend on
`mx.quest:runway-spi:<ver>`. The exact commands are in [PLUGIN-DEVELOPMENT.md](PLUGIN-DEVELOPMENT.md) §3,
*Getting the jars*.
- **Artifact version ≠ SPI level.** The Maven version of `runway-spi` is the **kernel release** it came from
(`1.0.0`); the contract level it carries is `RunwaySpi.VERSION` (`1.0.0`). Several kernel releases carry one
SPI level, and a later `1.x` artifact may still be SPI `1.0.0`. This commitment, `requiresSpi:` and the loader all
speak in SPI levels; only your pom names the artifact version.
- **Build against a released kernel version, never a `-SNAPSHOT`.** Your plugin's bytes depend on the SPI jar it
compiled against (your jar embeds your pom, and `javac` inlines `RunwaySpi.VERSION`), so only an immutable,
published kernel version lets a plugin release be rebuilt byte for byte. A plugin version is never republished
from a tree whose kernel pin has moved: a new pin is a new plugin release.
- Read the contract in [PLUGIN-DEVELOPMENT.md](PLUGIN-DEVELOPMENT.md); the plugin-authoring guide
([`plugins/docs/PLUGIN-AUTHORING-GUIDE.md`](../plugins/docs/PLUGIN-AUTHORING-GUIDE.md)) is the code-grounded companion.
- Build against a version and expect additive-only change within the MAJOR line. A MAJOR bump (`1.x → 2.0`) is the
only place a breaking SPI change may land, and the loader will then refuse a plugin built for `1.x` with a reason
rather than let it fail at run time.
+1
View File
@@ -0,0 +1 @@
node_modules/
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
# Reproduce the self-hosted CodeMirror 6 bundle. node_modules is NOT committed; run this to rebuild.
set -euo pipefail
cd "$(dirname "$(readlink -f "$0")")"
npm install --no-audit --no-fund --loglevel=error
OUT_DIR="../../runway-app/src/main/resources/static/vendor"
mkdir -p "$OUT_DIR"
./node_modules/.bin/esbuild entry.mjs \
--bundle --minify --format=iife --target=es2019 --legal-comments=none \
--outfile="$OUT_DIR/codemirror.min.js"
cp codemirror.css "$OUT_DIR/codemirror.min.css"
echo "Built codemirror.min.js ($(wc -c < "$OUT_DIR/codemirror.min.js") bytes) + codemirror.min.css into $OUT_DIR"
+5
View File
@@ -0,0 +1,5 @@
/* Runway page-editor host framing. CodeMirror 6 self-injects its own editor styles at runtime;
this only sizes/frames the host so the editor sits cleanly inside a Tabler card. */
.runway-cm-host { display: block; width: 100%; }
.runway-cm-host .cm-editor { height: 100%; }
.runway-cm-host .cm-editor.cm-focused { outline: none; box-shadow: 0 0 0 .25rem rgba(66,153,225,.25); }
+76
View File
@@ -0,0 +1,76 @@
// Runway tenant page-editor code editor — a self-hosted CodeMirror 6 bundle.
//
// esbuild bundles this into an IIFE (static/vendor/codemirror.min.js) that exposes a small, stable
// window.RunwayEditor facade. CodeMirror 6 injects its own styles at runtime (style-mod), so the
// companion codemirror.min.css only frames the editor host element in the Tabler UI.
//
// Contract:
// RunwayEditor.create(textarea, {mode, height, dark}) -> { view, getValue, setValue, destroy }
// Mounts an editor over a <textarea>, hides the textarea, and keeps textarea.value in sync on
// every edit AND on form submit — so a plain form POST carries the edited source (no JS wiring
// at the call site). mode: "html" (default) | "xml" | "css".
// RunwayEditor.mountAll(root?) -> auto-mounts every textarea[data-cm] under root (default document),
// reading data-cm-mode / data-cm-height; runs once on DOMContentLoaded and is HTMX-rescan safe.
import { EditorView, keymap } from "@codemirror/view";
import { basicSetup } from "codemirror";
import { indentWithTab } from "@codemirror/commands";
import { html } from "@codemirror/lang-html";
import { css } from "@codemirror/lang-css";
import { xml } from "@codemirror/lang-xml";
import { oneDark } from "@codemirror/theme-one-dark";
function langFor(mode) {
switch ((mode || "html").toLowerCase()) {
case "css": return css();
case "xml": return xml();
default: return html();
}
}
function create(textarea, opts) {
opts = opts || {};
const mode = opts.mode || textarea.getAttribute("data-cm-mode") || "html";
const height = opts.height || textarea.getAttribute("data-cm-height") || "60vh";
const dark = opts.dark !== undefined
? opts.dark
: (document.body && document.body.getAttribute("data-cm-theme") === "dark");
const extensions = [
basicSetup,
keymap.of([indentWithTab]),
langFor(mode),
// Sync back to the textarea on every edit so a normal form POST carries the source.
EditorView.updateListener.of((u) => { if (u.docChanged) textarea.value = u.state.doc.toString(); }),
EditorView.theme({
"&": { height: height, border: "1px solid var(--tblr-border-color, #dee2e6)", borderRadius: "4px" },
".cm-scroller": { overflow: "auto", fontFamily: "var(--tblr-font-monospace, monospace)" },
}),
];
if (dark) extensions.push(oneDark);
const view = new EditorView({ doc: textarea.value, extensions });
textarea.parentNode.insertBefore(view.dom, textarea);
textarea.style.display = "none";
// Belt-and-suspenders: force a final sync at submit time.
if (textarea.form) {
textarea.form.addEventListener("submit", () => { textarea.value = view.state.doc.toString(); });
}
return {
view,
getValue: () => view.state.doc.toString(),
setValue: (val) => view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: val } }),
destroy: () => view.destroy(),
};
}
function mountAll(root) {
const scope = root || document;
scope.querySelectorAll("textarea[data-cm]").forEach((ta) => {
if (!ta.__cmMounted) { ta.__cmMounted = create(ta, {}); }
});
}
window.RunwayEditor = { create, mountAll };
document.addEventListener("DOMContentLoaded", () => mountAll(document));
// HTMX-swap safe: re-mount any editors that arrived in swapped content (no-op without HTMX).
document.addEventListener("htmx:afterSwap", (e) => mountAll(e.target || document));
+753
View File
@@ -0,0 +1,753 @@
{
"name": "runway-codemirror-bundle",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "runway-codemirror-bundle",
"version": "1.0.0",
"dependencies": {
"@codemirror/autocomplete": "^6.18.0",
"@codemirror/commands": "^6.7.0",
"@codemirror/lang-css": "^6.3.0",
"@codemirror/lang-html": "^6.4.9",
"@codemirror/lang-xml": "^6.1.0",
"@codemirror/language": "^6.10.0",
"@codemirror/search": "^6.5.0",
"@codemirror/state": "^6.4.0",
"@codemirror/theme-one-dark": "^6.1.2",
"@codemirror/view": "^6.43.0",
"codemirror": "^6.0.1"
},
"devDependencies": {
"esbuild": "^0.24.0"
}
},
"node_modules/@codemirror/autocomplete": {
"version": "6.20.3",
"resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.3.tgz",
"integrity": "sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0"
}
},
"node_modules/@codemirror/commands": {
"version": "6.10.4",
"resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.10.4.tgz",
"integrity": "sha512-Ryk9y9T0FFVF0cUGhAknveAyUOl/A1qReTFi+qPKtOh2Z9F4AUBz3XOrYD4ZEgZirdugVzHvd/2/Wcwy5OliTg==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.7.0",
"@codemirror/view": "^6.27.0",
"@lezer/common": "^1.1.0"
}
},
"node_modules/@codemirror/lang-css": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz",
"integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@lezer/common": "^1.0.2",
"@lezer/css": "^1.1.7"
}
},
"node_modules/@codemirror/lang-html": {
"version": "6.4.11",
"resolved": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.11.tgz",
"integrity": "sha512-9NsXp7Nwp891pQchI7gPdTwBuSuT3K65NGTHWHNJ55HjYcHLllr0rbIZNdOzas9ztc1EUVBlHou85FFZS4BNnw==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/lang-css": "^6.0.0",
"@codemirror/lang-javascript": "^6.0.0",
"@codemirror/language": "^6.4.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0",
"@lezer/css": "^1.1.0",
"@lezer/html": "^1.3.12"
}
},
"node_modules/@codemirror/lang-javascript": {
"version": "6.2.5",
"resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz",
"integrity": "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.6.0",
"@codemirror/lint": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0",
"@lezer/javascript": "^1.0.0"
}
},
"node_modules/@codemirror/lang-xml": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/@codemirror/lang-xml/-/lang-xml-6.1.0.tgz",
"integrity": "sha512-3z0blhicHLfwi2UgkZYRPioSgVTo9PV5GP5ducFH6FaHy0IAJRg+ixj5gTR1gnT/glAIC8xv4w2VL1LoZfs+Jg==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.4.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.0.0",
"@lezer/common": "^1.0.0",
"@lezer/xml": "^1.0.0"
}
},
"node_modules/@codemirror/language": {
"version": "6.12.4",
"resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.4.tgz",
"integrity": "sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.23.0",
"@lezer/common": "^1.5.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0",
"style-mod": "^4.0.0"
}
},
"node_modules/@codemirror/lint": {
"version": "6.9.7",
"resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.7.tgz",
"integrity": "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.42.0",
"crelt": "^1.0.5"
}
},
"node_modules/@codemirror/search": {
"version": "6.7.1",
"resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.7.1.tgz",
"integrity": "sha512-uMe5UO6PamJtSHrXhhHOzSX3ReWtiJrva6GnPMwSOrZtiExb5X5eExhr2OUZQVvdxPsKpY3Ro2mFbQadpPWmHA==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.37.0",
"crelt": "^1.0.5"
}
},
"node_modules/@codemirror/state": {
"version": "6.7.0",
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.0.tgz",
"integrity": "sha512-Zbl9NyscLMZkfXPQnNAIIAFftidrA1UbcJEIMp24C0Bukc2I5T8wJS0wsXYsnDOqCFJUeJ1BITGNs5CqPDSmSg==",
"license": "MIT",
"dependencies": {
"@marijn/find-cluster-break": "^1.0.0"
}
},
"node_modules/@codemirror/theme-one-dark": {
"version": "6.1.3",
"resolved": "https://registry.npmjs.org/@codemirror/theme-one-dark/-/theme-one-dark-6.1.3.tgz",
"integrity": "sha512-NzBdIvEJmx6fjeremiGp3t/okrLPYT0d9orIc7AFun8oZcRk58aejkqhv6spnz4MLAevrKNPMQYXEWMg4s+sKA==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.0.0",
"@lezer/highlight": "^1.0.0"
}
},
"node_modules/@codemirror/view": {
"version": "6.43.4",
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.4.tgz",
"integrity": "sha512-YImu23iyKfncJzT7sRy+rEqEhSc8RhOHqDxwy4WzXRKJwYm6iwf/9OJk5ctCAdZ6yi2ZqaGEvmf55fSVqMDrgg==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.7.0",
"crelt": "^1.0.6",
"style-mod": "^4.1.0",
"w3c-keyname": "^2.2.4"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.24.2.tgz",
"integrity": "sha512-thpVCb/rhxE/BnMLQ7GReQLLN8q9qbHmI55F4489/ByVg2aQaQ6kbcLb6FHkocZzQhxc4gx0sCk0tJkKBFzDhA==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.24.2.tgz",
"integrity": "sha512-tmwl4hJkCfNHwFB3nBa8z1Uy3ypZpxqxfTQOcHX+xRByyYgunVbZ9MzUUfb0RxaHIMnbHagwAxuTL+tnNM+1/Q==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.24.2.tgz",
"integrity": "sha512-cNLgeqCqV8WxfcTIOeL4OAtSmL8JjcN6m09XIgro1Wi7cF4t/THaWEa7eL5CMoMBdjoHOTh/vwTO/o2TRXIyzg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.24.2.tgz",
"integrity": "sha512-B6Q0YQDqMx9D7rvIcsXfmJfvUYLoP722bgfBlO5cGvNVb5V/+Y7nhBE3mHV9OpxBf4eAS2S68KZztiPaWq4XYw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.24.2.tgz",
"integrity": "sha512-kj3AnYWc+CekmZnS5IPu9D+HWtUI49hbnyqk0FLEJDbzCIQt7hg7ucF1SQAilhtYpIujfaHr6O0UHlzzSPdOeA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.24.2.tgz",
"integrity": "sha512-WeSrmwwHaPkNR5H3yYfowhZcbriGqooyu3zI/3GGpF8AyUdsrrP0X6KumITGA9WOyiJavnGZUwPGvxvwfWPHIA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.24.2.tgz",
"integrity": "sha512-UN8HXjtJ0k/Mj6a9+5u6+2eZ2ERD7Edt1Q9IZiB5UZAIdPnVKDoG7mdTVGhHJIeEml60JteamR3qhsr1r8gXvg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.24.2.tgz",
"integrity": "sha512-TvW7wE/89PYW+IevEJXZ5sF6gJRDY/14hyIGFXdIucxCsbRmLUcjseQu1SyTko+2idmCw94TgyaEZi9HUSOe3Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.24.2.tgz",
"integrity": "sha512-n0WRM/gWIdU29J57hJyUdIsk0WarGd6To0s+Y+LwvlC55wt+GT/OgkwoXCXvIue1i1sSNWblHEig00GBWiJgfA==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.24.2.tgz",
"integrity": "sha512-7HnAD6074BW43YvvUmE/35Id9/NB7BeX5EoNkK9obndmZBUk8xmJJeU7DwmUeN7tkysslb2eSl6CTrYz6oEMQg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.24.2.tgz",
"integrity": "sha512-sfv0tGPQhcZOgTKO3oBE9xpHuUqguHvSo4jl+wjnKwFpapx+vUDcawbwPNuBIAYdRAvIDBfZVvXprIj3HA+Ugw==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.24.2.tgz",
"integrity": "sha512-CN9AZr8kEndGooS35ntToZLTQLHEjtVB5n7dl8ZcTZMonJ7CCfStrYhrzF97eAecqVbVJ7APOEe18RPI4KLhwQ==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.24.2.tgz",
"integrity": "sha512-iMkk7qr/wl3exJATwkISxI7kTcmHKE+BlymIAbHO8xanq/TjHaaVThFF6ipWzPHryoFsesNQJPE/3wFJw4+huw==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.24.2.tgz",
"integrity": "sha512-shsVrgCZ57Vr2L8mm39kO5PPIb+843FStGt7sGGoqiiWYconSxwTiuswC1VJZLCjNiMLAMh34jg4VSEQb+iEbw==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.24.2.tgz",
"integrity": "sha512-4eSFWnU9Hhd68fW16GD0TINewo1L6dRrB+oLNNbYyMUAeOD2yCK5KXGK1GH4qD/kT+bTEXjsyTCiJGHPZ3eM9Q==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.24.2.tgz",
"integrity": "sha512-S0Bh0A53b0YHL2XEXC20bHLuGMOhFDO6GN4b3YjRLK//Ep3ql3erpNcPlEFed93hsQAjAQDNsvcK+hV90FubSw==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.24.2.tgz",
"integrity": "sha512-8Qi4nQcCTbLnK9WoMjdC9NiTG6/E38RNICU6sUNqK0QFxCYgoARqVqxdFmWkdonVsvGqWhmm7MO0jyTqLqwj0Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.24.2.tgz",
"integrity": "sha512-wuLK/VztRRpMt9zyHSazyCVdCXlpHkKm34WUyinD2lzK07FAHTq0KQvZZlXikNWkDGoT6x3TD51jKQ7gMVpopw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.24.2.tgz",
"integrity": "sha512-VefFaQUc4FMmJuAxmIHgUmfNiLXY438XrL4GDNV1Y1H/RW3qow68xTwjZKfj/+Plp9NANmzbH5R40Meudu8mmw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.24.2.tgz",
"integrity": "sha512-YQbi46SBct6iKnszhSvdluqDmxCJA+Pu280Av9WICNwQmMxV7nLRHZfjQzwbPs3jeWnuAhE9Jy0NrnJ12Oz+0A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.24.2.tgz",
"integrity": "sha512-+iDS6zpNM6EnJyWv0bMGLWSWeXGN/HTaF/LXHXHwejGsVi+ooqDfMCCTerNFxEkM3wYVcExkeGXNqshc9iMaOA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.24.2.tgz",
"integrity": "sha512-hTdsW27jcktEvpwNHJU4ZwWFGkz2zRJUz8pvddmXPtXDzVKTTINmlmga3ZzwcuMpUvLw7JkLy9QLKyGpD2Yxig==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.24.2.tgz",
"integrity": "sha512-LihEQ2BBKVFLOC9ZItT9iFprsE9tqjDjnbulhHoFxYQtQfai7qfluVODIYxt1PgdoyQkz23+01rzwNwYfutxUQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.24.2.tgz",
"integrity": "sha512-q+iGUwfs8tncmFC9pcnD5IvRHAzmbwQ3GPS5/ceCyHdjXubwQWI12MKWSNSMYLJMq23/IUCvJMS76PDqXe1fxA==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.24.2.tgz",
"integrity": "sha512-7VTgWzgMGvup6aSqDPLiW5zHaxYJGTO4OokMjIlrCtf+VpEL+cXKtCvg723iguPYI5oaUNdS+/V7OU2gvXVWEg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@lezer/common": {
"version": "1.5.2",
"resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.2.tgz",
"integrity": "sha512-sxQE460fPZyU3sdc8lafxiPwJHBzZRy/udNFynGQky1SePYBdhkBl1kOagA9uT3pxR8K09bOrmTUqA9wb/PjSQ==",
"license": "MIT"
},
"node_modules/@lezer/css": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@lezer/css/-/css-1.3.4.tgz",
"integrity": "sha512-N+tn9tej2hPvyKgHEApMOQfHczDJCwxrRFS3SPn9QjYN+uwHvEDnCgKRrb3mxDYxRS8sKMM8fhC3+lc04Abz5Q==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.3.0"
}
},
"node_modules/@lezer/highlight": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz",
"integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.3.0"
}
},
"node_modules/@lezer/html": {
"version": "1.3.13",
"resolved": "https://registry.npmjs.org/@lezer/html/-/html-1.3.13.tgz",
"integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0"
}
},
"node_modules/@lezer/javascript": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.4.tgz",
"integrity": "sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.1.3",
"@lezer/lr": "^1.3.0"
}
},
"node_modules/@lezer/lr": {
"version": "1.4.10",
"resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.10.tgz",
"integrity": "sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.0.0"
}
},
"node_modules/@lezer/xml": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/@lezer/xml/-/xml-1.0.6.tgz",
"integrity": "sha512-CdDwirL0OEaStFue/66ZmFSeppuL6Dwjlk8qk153mSQwiSH/Dlri4GNymrNWnUmPl2Um7QfV1FO9KFUyX3Twww==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0"
}
},
"node_modules/@marijn/find-cluster-break": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.3.tgz",
"integrity": "sha512-FY+MKLBoTsLNJF/eLWaOsXGdz6uh3Iu1axjPf6TUq92IYumcTcXWHoS747JARLkcdlJ/Waiaxc5wQfFO8jC6NA==",
"license": "MIT"
},
"node_modules/codemirror": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/codemirror/-/codemirror-6.0.2.tgz",
"integrity": "sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/commands": "^6.0.0",
"@codemirror/language": "^6.0.0",
"@codemirror/lint": "^6.0.0",
"@codemirror/search": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.0.0"
}
},
"node_modules/crelt": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz",
"integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==",
"license": "MIT"
},
"node_modules/esbuild": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.24.2.tgz",
"integrity": "sha512-+9egpBW8I3CD5XPe0n6BfT5fxLzxrlDzqydF3aviG+9ni1lDC/OvMHcxqEFV0+LANZG5R1bFMWfUrjVsdwxJvA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.24.2",
"@esbuild/android-arm": "0.24.2",
"@esbuild/android-arm64": "0.24.2",
"@esbuild/android-x64": "0.24.2",
"@esbuild/darwin-arm64": "0.24.2",
"@esbuild/darwin-x64": "0.24.2",
"@esbuild/freebsd-arm64": "0.24.2",
"@esbuild/freebsd-x64": "0.24.2",
"@esbuild/linux-arm": "0.24.2",
"@esbuild/linux-arm64": "0.24.2",
"@esbuild/linux-ia32": "0.24.2",
"@esbuild/linux-loong64": "0.24.2",
"@esbuild/linux-mips64el": "0.24.2",
"@esbuild/linux-ppc64": "0.24.2",
"@esbuild/linux-riscv64": "0.24.2",
"@esbuild/linux-s390x": "0.24.2",
"@esbuild/linux-x64": "0.24.2",
"@esbuild/netbsd-arm64": "0.24.2",
"@esbuild/netbsd-x64": "0.24.2",
"@esbuild/openbsd-arm64": "0.24.2",
"@esbuild/openbsd-x64": "0.24.2",
"@esbuild/sunos-x64": "0.24.2",
"@esbuild/win32-arm64": "0.24.2",
"@esbuild/win32-ia32": "0.24.2",
"@esbuild/win32-x64": "0.24.2"
}
},
"node_modules/style-mod": {
"version": "4.1.3",
"resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.3.tgz",
"integrity": "sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==",
"license": "MIT"
},
"node_modules/w3c-keyname": {
"version": "2.2.8",
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
"integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
"license": "MIT"
}
}
}
+25
View File
@@ -0,0 +1,25 @@
{
"name": "runway-codemirror-bundle",
"version": "1.0.0",
"private": true,
"description": "Self-hosted CodeMirror 6 bundle for the Runway tenant page editor. Built with esbuild into an IIFE exposing window.RunwayEditor; the output (codemirror.min.js/.css) is committed under runway-app/src/main/resources/static/vendor/ and served at /__assets/vendor/. node_modules is NOT committed — run build.sh to reproduce.",
"scripts": {
"build": "bash build.sh"
},
"dependencies": {
"@codemirror/autocomplete": "^6.18.0",
"@codemirror/commands": "^6.7.0",
"@codemirror/lang-css": "^6.3.0",
"@codemirror/lang-html": "^6.4.9",
"@codemirror/lang-xml": "^6.1.0",
"@codemirror/language": "^6.10.0",
"@codemirror/search": "^6.5.0",
"@codemirror/state": "^6.4.0",
"@codemirror/theme-one-dark": "^6.1.2",
"@codemirror/view": "^6.43.0",
"codemirror": "^6.0.1"
},
"devDependencies": {
"esbuild": "^0.24.0"
}
}
+222
View File
@@ -0,0 +1,222 @@
# Runway monitoring bundle
Drop-in Prometheus + Grafana assets for a Runway deployment. They read the metrics Runway exposes at
`/actuator/prometheus` — the JVM/HTTP metrics Actuator ships, the route-level `http_server_requests_*`, the
Runway platform gauges, and the **per-site** request timer `runway_http_server_requests_seconds_*` (tagged
`site` and `outcome`).
## 1. Expose the endpoint to your monitoring system
`/actuator/prometheus` is **not public** — by default only an authenticated application superadmin/admin may read
it. For an unattended scraper, set a **scrape token** in the external `application.yml`:
```yaml
runway:
metrics:
scrape-token: "<a long random string>"
```
Then Prometheus authenticates with a bearer token — nothing else about the endpoint changes, and the token
grants access to **`/actuator/prometheus` only** (not the rest of `/actuator`). Example `prometheus.yml` job:
```yaml
scrape_configs:
- job_name: runway
metrics_path: /actuator/prometheus
scheme: https # or http behind a TLS-terminating proxy
authorization:
type: Bearer
credentials: "<the same scrape-token value>"
static_configs:
- targets: ["runway.example.com:8443"]
```
> Leave `scrape-token` blank to keep the endpoint operator-only (no token auth). Treat the token as a secret —
> it is read-only, but it reveals per-site traffic. Keep the external `application.yml` `chmod 600`.
### Behind a reverse proxy — a scrape that 503s while `curl` gets 200
If Runway sits behind a reverse proxy that **routes by an exact `Host` match**, the scraper can get **503** while
`curl` from the same host with the same token gets **200**. Two causes produce that identical symptom:
**1. A `Host`-header port mismatch (the common one).** A Prometheus / VictoriaMetrics scraper is an
**HTTP/1.1** client (VictoriaMetrics uses `fasthttp`, which is HTTP/1.1-only) and, when its target is written
`host:443`, it sends **`Host: runway.example.com:443` — with the port**. A proxy rule that matches the host
*exactly* (e.g. HAProxy `acl … hdr(host) -i runway.example.com`) then **misses it**, because **HTTP/2 normalizes
the `:authority` port away but HTTP/1.1 does not** — so the request falls through to the proxy's *default* /
*other* backend and 503s (HAProxy's *"No server is available to handle this request"* if that backend is down).
`curl` works because it sends `Host` without the default `:443` (or negotiates HTTP/2, where the port is
normalized). This is why an otherwise-identical `curl` — same token, same headers — gets 200.
**2. TLS-fingerprint / bot filtering (less common).** A **WAF** that fingerprints clients (JA3/JA4) or filters
by `User-Agent` (`vm_promscrape`) / "non-browser client" can route the Go client to a deny/tarpit/dead backend
for the same *"scraper 503s, curl 200"* symptom — Go's TLS `ClientHello` differs from a browser's or `curl`'s.
**Diagnose at the proxy**, not in Runway (`/actuator/health` is `UP` throughout — Runway is not down): log which
**backend** the scraper matched and the **`Host`** it sent. HAProxy `httplog` shows the backend as e.g.
`runway/…` (good) vs `servers/<NOSRV>` (fell through to a down default). **Fix at the proxy** — a deployment
gotcha, not a Runway bug:
- **make the host rule port-tolerant** — match `runway.example.com` *and* `runway.example.com:443`, or strip the
port before matching (HAProxy: `hdr(host),field(1,:)`); or
- **allowlist the scraper's source IP** / **exempt `/actuator/prometheus`** — least-privilege, IP- and/or
path-scoped, and the endpoint stays protected by its bearer token; or
- point the scraper at Runway's **internal** address (behind the proxy, e.g. over the VPN / on `:8080`) so it
never crosses the proxy at all — or simply set the Prometheus target to the **bare host without `:443`**.
## 2. Alert rules
`runway-prometheus-alerts.yml` — reference it from `prometheus.yml`:
```yaml
rule_files:
- /etc/prometheus/rules/runway-prometheus-alerts.yml
```
The rules cover target-down, per-site 5xx rate, per-site latency, dropped log lines, suspended sites, and high
heap. Thresholds and `for:` windows are conservative starting points — tune them to your traffic.
## 3. Grafana dashboard
`runway-grafana-dashboard.json` — import it in Grafana (Dashboards → New → Import → Upload JSON), and pick your
Prometheus data source when prompted. It has an **overview row** (sites / suspended / maintenance / plugins
loaded / log lines dropped) and per-site **request rate**, **5xx rate**, **latency**, plus **JVM heap**, with a
`site` template variable to focus one tenant.
## Metrics reference (the ones these assets use)
| Metric | Type | Meaning |
|--------|------|---------|
| `runway_sites` | gauge | configured sites |
| `runway_sites_suspended` | gauge | operator-suspended sites |
| `runway_sites_maintenance` | gauge | sites in tenant maintenance mode |
| `runway_plugins_loaded` | gauge | plugins currently loaded |
| `runway_logs_dropped` | gauge | access/audit log lines dropped under load since startup |
| `runway_edge_rejections_total` | counter | requests rejected at the protection edge, tagged `status` (403/429) and `reason` (`rate-limit`, `blocklist-manual`, `blocklist-auto`, `blocklist-cidr`, `unspecified`) |
| `runway_http_server_requests_seconds_count` / `_sum` | timer | **per-site** request count / total latency, tagged `site`, `outcome` |
| `http_server_requests_seconds_*` | timer | route-level request timing (Actuator built-in), tagged `uri`, `status`, `method`, `outcome` |
| `jvm_memory_used_bytes` / `jvm_memory_max_bytes` | gauge | JVM memory (Actuator built-in) |
### A metric family whose names come from class names
Spring Security registers one meter per filter in a security chain, **named after the filter class**:
```
spring_security_filterchains_LoginProtectionFilter_{before,after}_total
spring_security_filterchains_PrometheusScrapeAuthFilter_{before,after}_total
```
These are not names Runway chose, and they move when the class moves. **Renaming a security filter class
renames these production metrics**, which reads to a disappearance detector as an outage. If you alert on
series vanishing, exclude the `spring_security_filterchains_*` family, or accept that it will fire on an
ordinary refactor.
On the Runway side the names are pinned by a test (`SecurityFilterMetricNamesTest`) so a rename becomes a
deliberate decision rather than an accident — but the coupling is inherent to how Spring Security names these
meters, so treat them as fragile identifiers regardless.
### Reading `runway_edge_rejections_total`
This is the only signal for traffic the edge turned away. Those requests short-circuit at
`FilterOrder.CORE_PROTECTION` **without calling the chain**, so they never reach the access log at the other
end of the ladder — before this counter existed they were invisible everywhere.
The `reason` tag is what makes it actionable, because the status alone is not:
| `reason` | what it means | what to do about it |
|---|---|---|
| `rate-limit` | the per-IP token bucket throttled the request (`429`) | Usually benign in small numbers. Sustained volume from one source means either an abusive client or a threshold set too tight for a legitimate crawler. |
| `blocklist-manual` | an operator banned this address (`403`) | Expected. Nothing to investigate unless you did not expect it. |
| `blocklist-auto` | the limiter escalated repeated throttling into a temporary ban (`429` + `Retry-After` with the time remaining; `403` only for an indefinite one) | Worth reading. A rise here means clients are hitting the limit hard enough to be escalated — check whether a search crawler is being caught. |
| `blocklist-cidr` | a blocked range matched | Expected if you block ranges. |
| `unspecified` | the installed guard rejected without stating a reason | Only from a custom or older guard. |
**A rise in `blocklist-auto` or `rate-limit` for search-crawler traffic is an indexing-loss scenario**, not just
an abuse signal: a crawler that is throttled or banned stops fetching, and nothing else in the product reports
that. Pair this counter with the `runway.protect` log, which carries the client IP and the (untrusted, spoofable)
User-Agent for the same rejections.
Counts are exact even when log lines are throttled — see `OPERATIONS.md`.
**The series exist at `0` from startup.** Every `(status, reason)` pair the installed guard can produce is
registered when the process starts, so this metric is in the scrape from the first second of a clean boot.
That matters more than it looks:
- A panel shows `0`, not "No data". On a quiet night those two read very differently: one says *the guard is
running and turning nobody away*, the other says *I don't know whether the guard is running*.
- The series can take part in **disappearance detection**. Previously it was absent until the first rejection
— which on a healthy host can be days — so an `absent()`-style rule fired on a restart. The tempting
workaround, suppressing that rule around restarts, is exactly wrong: **a rename ships inside a release and a
release arrives at a restart**, so the suppression window is precisely when a real rename lands.
- `rate()` and `increase()` behave across the window containing first use, instead of starting mid-window.
Only combinations that can actually occur are registered — a `429` tagged `blocklist-manual` is never
published, because a permanent zero for something no code path can produce reads as evidence rather than as
silence. If you install a custom guard, it declares its own outcomes (`EdgeGuard#declaredOutcomes`); one that
declares nothing behaves as before, appearing on first use.
Health (`/actuator/health`, including the `storage` indicator) is a separate **probe**, not a scraped metric;
point your uptime check or systemd/HAProxy health check at it. The `up` metric Prometheus records for the scrape
target drives the `RunwayInstanceDown` alert.
## Per-site liveness (`/__health`)
The scrape endpoint above is **platform-wide**. To check that an individual tenant is serving, probe that site's
own host — per-site metrics cannot do this, because a site with no traffic and a site that is down look identical.
```yaml
# prometheus.yml — blackbox_exporter, one target per tenant host
- job_name: runway-sites
metrics_path: /probe
params:
module: [http_2xx]
static_configs:
- targets:
- https://acme.example.com/__health
- https://nocturne.example.com/__health
relabel_configs:
- source_labels: [__address__]
target_label: __param_target
- source_labels: [__param_target]
target_label: instance
- target_label: __address__
replacement: blackbox:9115
```
`200` = serving (`status` is `up` or `degraded`); `503` = not serving; `404` = the Host matches no site (check the
probe URL before assuming an outage). Alert on `down`, ticket on `degraded`. The probe is excluded from tenant
bandwidth accounting and from the per-site request timer, so polling it costs the tenant nothing.
For the cause (`suspended` / `maintenance` / `over_quota` / `platform_degraded`), send
`Authorization: Bearer $RUNWAY_HEALTH_TOKEN`; without it the body carries status only, on purpose.
## ⚠ The `outcome` label has DIFFERENT CASE in the two request-timer families
Both are exposed, under the same job, and a selector written in the wrong case renders **empty rather than
erroring** — the worst way for a monitoring query to be wrong. Someone who has just written a working query
against one family will get silence from the other and reasonably conclude there is no traffic.
| Meter | Tagged by | `outcome` values |
|---|---|---|
| `http_server_requests_seconds_*` (Micrometer's own) | route/URI | `SUCCESS`, `CLIENT_ERROR`, `SERVER_ERROR`, `REDIRECTION`, `INFORMATIONAL` — **UPPER** |
| `runway_http_server_requests_seconds_*` (Runway's per-site) | `site` | `success`, `client_error`, `server_error`, `redirection`, `informational` — **lower** |
This is a collision of two reasonable conventions, not a defect: the first follows Micrometer's `Outcome` enum,
the second is Runway's own per-tenant meter. Copy-pasteable, correct for each:
```promql
# per-SITE error rate (Runway's meter — lowercase)
sum by (site) (rate(runway_http_server_requests_seconds_count{outcome="server_error"}[5m]))
# per-ROUTE error rate (Micrometer's meter — UPPERCASE)
sum by (uri) (rate(http_server_requests_seconds_count{outcome="SERVER_ERROR"}[5m]))
```
If you want to be immune to the distinction, match case-insensitively — `outcome=~"(?i)server_error"` — at the
cost of a slower selector.
*The shipped dashboard and alert rules in this directory use the lowercase per-site form throughout, so they are
correct as-is. Normalising the two onto one convention would be a **breaking** change to every existing query,
so it is deliberately deferred to a future major rather than done quietly.*
+141
View File
@@ -0,0 +1,141 @@
{
"__inputs": [
{
"name": "DS_PROMETHEUS",
"label": "Prometheus",
"description": "The Prometheus data source scraping Runway's /actuator/prometheus",
"type": "datasource",
"pluginId": "prometheus",
"pluginName": "Prometheus"
}
],
"title": "Runway",
"uid": "runway-overview",
"tags": ["runway"],
"timezone": "browser",
"schemaVersion": 39,
"refresh": "30s",
"time": { "from": "now-6h", "to": "now" },
"templating": {
"list": [
{
"name": "datasource",
"type": "datasource",
"query": "prometheus",
"current": {},
"hide": 0
},
{
"name": "site",
"type": "query",
"datasource": "${datasource}",
"query": "label_values(runway_http_server_requests_seconds_count, site)",
"includeAll": true,
"multi": true,
"refresh": 2,
"current": { "text": "All", "value": "$__all" }
}
]
},
"panels": [
{
"id": 1,
"type": "stat",
"title": "Sites",
"datasource": "${datasource}",
"gridPos": { "h": 4, "w": 4, "x": 0, "y": 0 },
"targets": [ { "expr": "runway_sites", "refId": "A" } ]
},
{
"id": 2,
"type": "stat",
"title": "Suspended sites",
"datasource": "${datasource}",
"gridPos": { "h": 4, "w": 4, "x": 4, "y": 0 },
"fieldConfig": { "defaults": { "thresholds": { "steps": [ { "color": "green", "value": null }, { "color": "red", "value": 1 } ] } } },
"targets": [ { "expr": "runway_sites_suspended", "refId": "A" } ]
},
{
"id": 3,
"type": "stat",
"title": "Sites in maintenance",
"datasource": "${datasource}",
"gridPos": { "h": 4, "w": 4, "x": 8, "y": 0 },
"targets": [ { "expr": "runway_sites_maintenance", "refId": "A" } ]
},
{
"id": 4,
"type": "stat",
"title": "Plugins loaded",
"datasource": "${datasource}",
"gridPos": { "h": 4, "w": 4, "x": 12, "y": 0 },
"targets": [ { "expr": "runway_plugins_loaded", "refId": "A" } ]
},
{
"id": 5,
"type": "stat",
"title": "Log lines dropped",
"datasource": "${datasource}",
"gridPos": { "h": 4, "w": 4, "x": 16, "y": 0 },
"fieldConfig": { "defaults": { "thresholds": { "steps": [ { "color": "green", "value": null }, { "color": "red", "value": 1 } ] } } },
"targets": [ { "expr": "runway_logs_dropped", "refId": "A" } ]
},
{
"id": 10,
"type": "timeseries",
"title": "Request rate by site (req/s)",
"datasource": "${datasource}",
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 4 },
"fieldConfig": { "defaults": { "unit": "reqps" } },
"targets": [
{
"expr": "sum by (site) (rate(runway_http_server_requests_seconds_count{site=~\"$site\"}[5m]))",
"legendFormat": "{{site}}",
"refId": "A"
}
]
},
{
"id": 11,
"type": "timeseries",
"title": "Server-error (5xx) rate by site",
"datasource": "${datasource}",
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 4 },
"fieldConfig": { "defaults": { "unit": "reqps" } },
"targets": [
{
"expr": "sum by (site) (rate(runway_http_server_requests_seconds_count{outcome=\"server_error\",site=~\"$site\"}[5m]))",
"legendFormat": "{{site}}",
"refId": "A"
}
]
},
{
"id": 12,
"type": "timeseries",
"title": "Average request latency by site",
"datasource": "${datasource}",
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 12 },
"fieldConfig": { "defaults": { "unit": "s" } },
"targets": [
{
"expr": "sum by (site) (rate(runway_http_server_requests_seconds_sum{site=~\"$site\"}[5m])) / clamp_min(sum by (site) (rate(runway_http_server_requests_seconds_count{site=~\"$site\"}[5m])), 1e-9)",
"legendFormat": "{{site}}",
"refId": "A"
}
]
},
{
"id": 13,
"type": "timeseries",
"title": "JVM heap used",
"datasource": "${datasource}",
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 12 },
"fieldConfig": { "defaults": { "unit": "bytes" } },
"targets": [
{ "expr": "sum(jvm_memory_used_bytes{area=\"heap\"})", "legendFormat": "used", "refId": "A" },
{ "expr": "sum(jvm_memory_max_bytes{area=\"heap\"})", "legendFormat": "max", "refId": "B" }
]
}
]
}
+80
View File
@@ -0,0 +1,80 @@
# Runway — Prometheus alerting rules.
#
# Load these into Prometheus (rule_files: in prometheus.yml) alongside a scrape job that hits
# /actuator/prometheus (see monitoring/README.md for the scrape-token scrape config). The rules use the
# meters Runway exposes: the built-in `http.server.requests` (route-level), the Runway-specific
# `runway_http_server_requests_seconds_*` (per-site), the platform gauges (`runway_sites*`,
# `runway_plugins_loaded`, `runway_logs_dropped`), the JVM metrics Actuator ships, and Prometheus's own `up`.
#
# Thresholds are deliberately conservative starting points — tune `for:` windows and comparison values to
# your traffic. Every rule is annotated so an alert is self-explanatory in a pager.
groups:
- name: runway.availability
rules:
- alert: RunwayInstanceDown
expr: up{job="runway"} == 0
for: 2m
labels:
severity: critical
annotations:
summary: "Runway instance {{ $labels.instance }} is not scrapeable"
description: "Prometheus cannot scrape /actuator/prometheus for 2 minutes — the process is down or the scrape token/target is misconfigured."
- name: runway.requests
rules:
# Per-site server-error (5xx) rate. Uses the per-site timer's _count series.
- alert: RunwaySiteHighServerErrorRate
expr: sum by (site) (rate(runway_http_server_requests_seconds_count{outcome="server_error"}[5m])) > 0.1
for: 10m
labels:
severity: warning
annotations:
summary: "Site {{ $labels.site }} is serving 5xx errors"
description: "Server-error rate for site {{ $labels.site }} has exceeded 0.1/s for 10 minutes."
# Per-site average request latency (Timer _sum / _count). A blunt but useful signal.
- alert: RunwaySiteHighLatency
expr: |
sum by (site) (rate(runway_http_server_requests_seconds_sum[5m]))
/ clamp_min(sum by (site) (rate(runway_http_server_requests_seconds_count[5m])), 1e-9) > 2
for: 10m
labels:
severity: warning
annotations:
summary: "Site {{ $labels.site }} is slow"
description: "Average request latency for site {{ $labels.site }} has exceeded 2s for 10 minutes."
- name: runway.platform
rules:
# The async telemetry queue dropped log lines under load — capacity or disk pressure.
- alert: RunwayLogLinesDropped
expr: increase(runway_logs_dropped[15m]) > 0
for: 0m
labels:
severity: warning
annotations:
summary: "Runway is dropping access/audit log lines"
description: "{{ $value }} log line(s) were dropped in the last 15 minutes — the telemetry queue is saturated (raise runway.logs.queue-capacity or investigate disk I/O)."
# Informational: a site is operator-suspended (public traffic 503s). Comment out if suspensions are routine.
- alert: RunwaySitesSuspended
expr: runway_sites_suspended > 0
for: 5m
labels:
severity: info
annotations:
summary: "{{ $value }} site(s) are suspended"
description: "One or more sites are operator-suspended; their public traffic is being 503'd."
- name: runway.jvm
rules:
- alert: RunwayHighHeapUsage
expr: |
sum by (instance) (jvm_memory_used_bytes{area="heap"})
/ sum by (instance) (jvm_memory_max_bytes{area="heap"}) > 0.9
for: 10m
labels:
severity: warning
annotations:
summary: "Runway heap usage is high on {{ $labels.instance }}"
description: "Heap usage has been above 90% of max for 10 minutes — raise -Xmx or investigate a leak."
+53
View File
@@ -0,0 +1,53 @@
# Runway plugins
This folder holds **Runway plugin projects**. Each plugin is a **standalone project** (its own build) that
compiles against the Runway SPI only (`mx.quest:runway-spi`, plus `runway-spi-testkit` for its tests) from the local Maven repository and deploys as a
folder under a Runway install's `external/plugins/<id>/`. The contract is **SPI `1.0.0`** (Runway `1.0.0`): the
kernel blocks a plugin that links its internal classes. The SPI jars are not yet published to a Maven repository — see the authoring
guide, §2.
Each Runway release on the releases page (<https://g.quest.mx/quest/runway/releases>) carries the zips of these
plugins built for it, beside the kernel's own files and listed in the same `SHA256SUMS`.
## Layout
```
plugins/
├── docs/PLUGIN-AUTHORING-GUIDE.md # THE canonical guide: build any Runway plugin from scratch
├── demo/ # the reference "kitchen-sink" plugin — exercises EVERY seam
├── search/ # on-site search: box widget + /search + /search/api + a published SiteSearchEngine SPI
├── search-lucene/ # a Lucene engine for `search` (requires: search + lucene-provider; per-locale analyzers, heap or disk)
└── lucene-provider/ # CODE-LESS library provider: bundles Apache Lucene under lib/ (no mainClass)
```
The essential **protection** plugin is not here: it is `runway-plugin-protection` at the root of the repository,
and ships inside the Runway installer.
Each plugin carries a `README.md` and a `plugin.yml` (and, when it has code, its unit tests), and versions independently (its
version is in its `plugin.yml`). Each also carries a `docs/<NAME>-PLUGIN.md`, and most a
`scripts/verify-against-host.sh` that checks it against the packaged host. One does not have the verify script:
**`lucene-provider`** has `docs/LUCENE-PROVIDER-PLUGIN.md` but no verify script — it is a code-less library bundle
with no code of its own to verify.
## Start here
- **Building a new plugin?** Read [`docs/PLUGIN-AUTHORING-GUIDE.md`](docs/PLUGIN-AUTHORING-GUIDE.md) — it covers
the project setup, the `plugin.yml` descriptor, every SPI, settings, permissions, resources, build/install,
and the pitfalls. Then **copy the closest existing plugin** as your starting template and strip what you don't
need.
- **Reference plugins by pattern:**
- Every seam at once → [`demo/`](demo/).
- Publishing your **own** SPI for other plugins → [`search/`](search/) (`SiteSearchEngine`).
- Implementing another plugin's SPI (`requires:`) + **consuming a library-provider** (Lucene) → [`search-lucene/`](search-lucene/).
- A **code-less library-provider** plugin (bundle a shared library under `lib/`, no `mainClass`) →
[`lucene-provider/`](lucene-provider/) (Apache Lucene) — consumed by a `requires:` plugin (`search-lucene`).
## Conventions
- Each plugin project is self-contained, with no external dependencies beyond the host artifacts in `~/.m2`. The
authoring guide lives at the top level (`docs/PLUGIN-AUTHORING-GUIDE.md`) and nowhere else is current:
`demo/docs/PLUGIN-AUTHORING-GUIDE.md` is only a pointer to it.
- Plugin **id** (and its install-folder name) is short and path-safe (e.g. `runway-demo`); the Maven artifactId
is **`runway-plugin-<id>`** (so `runway-plugin-runway-demo`), because the release zip is named after it,
`runway-plugin-<id>-<version>.zip`; the Java package lives **outside** `mx.quest.runway`.
- Build with JDK 25 (point `JAVA_HOME` at it) and Maven.
+6
View File
@@ -0,0 +1,6 @@
target/
*.class
.idea/
*.iml
.vscode/
.DS_Store
+9
View File
@@ -0,0 +1,9 @@
# Changelog
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
## [2.1.0] — 2026-10-21
First public release of `runway-demo`, the reference ("kitchen-sink") plugin: it exercises every extension axis and
every service of the Runway SPI, and is meant to be copied as the start of a new plugin. Requires SPI `1.0.0`
(Runway `1.0.0` or later). Licensed under the Apache License 2.0 (`LICENSE`, `NOTICE`).
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+6
View File
@@ -0,0 +1,6 @@
runway-demo — the Runway reference plugin
Copyright 2026 Quest ICT SAS de CV
Licensed under the Apache License, Version 2.0 (the file LICENSE). Unlike the Runway kernel, which is
licensed under the GNU Affero General Public License version 3, this plugin is offered under a
permissive license so that it can be copied as the starting point of a plugin under any terms.
+84
View File
@@ -0,0 +1,84 @@
# runway-demo — the Runway kitchen-sink reference plugin
One plugin that **exercises the whole Runway plugin contract**: every extension axis (head contributor, content
widgets, endpoints including an anonymous form `POST`, a page-quality check, a content source) and **every service
and callback of the SPI service tier** (SPI `1.0.0`: `PluginSettings`, `PluginInfo`/`PluginLifecycle`,
`PluginSiteFiles`, `Sites`, `RequestContext`, `AccessCheck`, `Messages`, `SitePages`, `ContentCatalogView`,
`ContentChanges`, `SiteEventListener`, `@ConsoleScreen`), plus every setting type, personal-data declaration,
permissions, a menu entry, a dashboard card, an admin fragment, static assets, templates and i18n. It links **only
the Runway SPI**. It is the worked reference for the canonical
[authoring guide](../docs/PLUGIN-AUTHORING-GUIDE.md) and the template to copy when starting a new plugin.
- **The walkthrough — every service, what the demo does with it, when you would use it:**
[`docs/DEMO-PLUGIN.md`](docs/DEMO-PLUGIN.md)
- **How to build any Runway plugin:** [`../docs/PLUGIN-AUTHORING-GUIDE.md`](../docs/PLUGIN-AUTHORING-GUIDE.md)
- **Release history:** [`CHANGELOG.md`](CHANGELOG.md)
## Requirements
A Runway kernel carrying **SPI `1.0.0`** or later: every `1.x` kernel (`requiresSpi: ">=1.0.0"` counts as a 1.x
floor; a kernel whose SPI is below it blocks the plugin at startup with a reason). The build needs
`mx.quest:runway-spi` and `runway-spi-testkit` in `~/.m2`.
## Build
```bash
export JAVA_HOME=<a JDK 25>
mvn verify
```
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.
Runs 82 unit tests (over the SPI testkit's fakes, plus a scan proving the compiled classes link nothing of the host
but the SPI) and produces the thin `target/runway-plugin-demo.jar` and **both** installable forms:
`target/runway-demo/` (the install-ready folder) and `target/runway-plugin-runway-demo-<version>.zip` (the archive
the management UI upload expects). Two builds produce byte-identical artifacts. The zip is named after the plugin id,
`runway-plugin-<id>-<version>.zip`, like every plugin's; the jar inside it is `runway-plugin-demo.jar`.
## Install (either path, then restart the host)
```bash
cp -r target/runway-demo <runway-external>/plugins/ # 1. filesystem (or scripts/install-into.sh <external>)
# 2. app console → /__app/plugins → install → upload runway-plugin-runway-demo-<version>.zip
```
The plugin loads only once the host is in **ACTIVE** mode (after first-run setup); it is skipped in WIZARD mode.
## Verify (one command)
```bash
HOST_JAR=<runway checkout>/runway-app/target/runway-app-<version>-exec.jar \
JAVA_HOME=/path/to/jdk-25 VERIFY_TMPDIR=<scratch dir> VERIFY_LOG_DIR=<evidence dir> scripts/verify-against-host.sh
```
It builds the plugin (offline, never `mvn install`), drops it into a throwaway Runway deployment, runs the
first-run wizard to reach ACTIVE mode and checks 58 things live — from "zero host-linkage and bean-name warnings"
through a `GET` writing nothing, the anonymous feedback `POST`, the console screen's CSRF-checked actions, the showcase page appearing and
disappearing, to a transfer copy leaving `notes.yml` out. `HOST_JAR` defaults to the host checkout's jar matching
its pom version.
## Try it
- Tenant console → **Runway demo** (needs `runway-demo|manage-notes`; administrators hold it): the demo screen.
Add a note, install the demo page, publish a showcase, check a path, watch *Recent changes*.
- `/demo` — the demo page (after installing it): the notice widget and the public feedback form.
- `/demo/showcase` — the showcase page, while one is published.
- `GET /demo/hello.txt` — a per-site greeting in the visitor's language.
- `GET /demo/echo.json?q=1` — what the platform tells an endpoint about your request.
- `GET /demo/notes.json` — the notes as JSON, gated by `manage-notes` (`403` without it).
- Any public page's `<head>` — a generator meta and the plugin's stylesheet.
- The plugin's per-site settings page — every setting type, and the admin fragment below the form.
## Starting a new plugin from it
Copy this folder, rename the descriptor `id`, the Maven `artifactId`, the Java package (`mx.quest.demo`) and the
bean-name prefix (`runwayDemo…` → your id in lowerCamelCase), and delete what you do not need. Keep the tests that
check the contract (`DemoPluginConfigTest`, `DemoTemplatesTest`) — they are the cheapest way to stay inside it.
_Java package `mx.quest.demo` · plugin id `runway-demo` · version 2.1.0 · `requiresSpi: ">=1.0.0"`._
## License
Apache License 2.0 (`LICENSE`, `NOTICE`), copyright Quest ICT SAS de CV. You are free to copy this plugin as the
start of your own plugin and to release yours under any terms.
+431
View File
@@ -0,0 +1,431 @@
# The `runway-demo` plugin — a walkthrough of the Runway plugin contract
> The **kitchen-sink reference plugin**. Every extension axis and every service of the SPI service tier
> is used here once, in the place a real plugin would use it, with a comment in the code saying
> **when you would use it**. Read this document top to bottom to learn the contract; copy the folder to start a
> plugin. The canonical rules live in the authoring guide (`../../docs/PLUGIN-AUTHORING-GUIDE.md`); this document
> shows them working.
- **id** `runway-demo` · **install folder** `external/plugins/runway-demo/` · **Java package** `mx.quest.demo`
- **version** `2.1.0` · **`requiresSpi`** `">=1.0.0"` · links **only** `mx.quest.runway.spi`
- **jar** `runway-plugin-demo.jar` (thin: 18 top-level classes, nothing bundled) · **Maven artifactId**
`runway-plugin-runway-demo` · **release zip** `runway-plugin-runway-demo-<version>.zip`
- **Verified** live against the packaged kernel (§9) and by 82 unit tests with 20 mutation checks (§8).
---
## 1. What it does
| Feature | Who sees it | Built on |
|---|---|---|
| A generator `<meta>`, the plugin stylesheet and an inert analytics `<script>` in every page's `<head>` | visitors | `HeadContributor` + `PluginSettings` |
| A notice callout at `data-widget="demo-notice/<instance>"` | visitors | `ContentWidget` + `PluginSettings` + `Messages.site` |
| A "leave a message" form at `data-widget="demo-feedback/<instance>"`, posting without a CSRF token | visitors | `ContentWidget` + an **anonymous** `POST` route |
| `/demo/hello.txt`, `/demo/echo.json`, `/demo/notes.json` (permission-gated) | visitors / operators | `EndpointContributor` + `AccessCheck` + `Messages.site` |
| SEO advice in the page editor (long title, no description, no `<h1>`) | site managers | `PageQualityCheck` + `PluginSettings` |
| Per-site **notes** (operator notes, visitors' messages, a settings audit note), personal data | operators | `PluginSiteFiles` + `siteData.personal` |
| A **showcase** page at `/demo/showcase`, published from the console | visitors | `ContentSource` + `ContentChanges` + a `SOURCE` listener |
| A **demo page** at `/demo` installed in one click | site managers | `SitePages` + `AccessCheck` |
| The demo's **console screen** (`/__admin/runway-demo`) | operators | `@ConsoleScreen` + `RequestContext` + `Messages.console` + `ContentCatalogView` |
| *Recent changes* on that screen, with URLs before and after | operators | `SiteEventListener` (`CONSUMER`) + `Sites` |
| A dashboard card and an admin fragment under the settings form | operators | descriptor + templates + `Sites`, `SitePages.pathOf`, `PluginSettings.secret`, `PluginInfo` |
| A start/stop hook logging the built-against and running SPI | the boot log | `PluginLifecycle` + `PluginInfo` |
---
## 2. The files
```
demo/
├── plugin.yml the descriptor: floor, personal data, permissions, both settings schemas, menu, card
├── pom.xml runway-spi (+ runway-spi-testkit for tests) and platform libraries, all provided
├── CHANGELOG.md · README.md
├── scripts/verify-against-host.sh build → throwaway Runway → boot ACTIVE → 58 live checks
├── scripts/install-into.sh copy the assembled plugin into an external/ tree
├── i18n/messages[_es].properties console AND public text (add-only)
├── static/ css/demo.css · js/demo-analytics.js · notes-help.html (/__plugin/runway-demo/static/…)
├── templates/ decoupled Thymeleaf (.html markup + .th.xml logic)
│ ├── console.* the @ConsoleScreen content
│ ├── showcase.* the content source's body template
│ ├── dashboard.* the dashboard card
│ └── admin.* the fragment under the settings form (filename convention)
└── src/main/java/mx/quest/demo/
├── DemoPluginConfig mainClass: every bean, wired explicitly, named runwayDemo…
├── DemoAppProps app-level settings (@ConfigurationProperties via @Bean)
├── DemoAnalyticsHead HeadContributor
├── DemoNoticeWidget ContentWidget "demo-notice"
├── DemoFeedbackWidget ContentWidget "demo-feedback" (the anonymous form)
├── DemoMetaLengthCheck PageQualityCheck
├── DemoEndpoints EndpointContributor (3 GETs + the anonymous POST)
├── DemoNotesStore · Note · NotesFile PluginSiteFiles: notes.yml
├── DemoShowcaseStore · Showcase PluginSiteFiles + ContentChanges: showcase.yml
├── DemoShowcaseSource ContentSource + SiteEventListener (SOURCE)
├── DemoActivity SiteEventListener (CONSUMER) + Sites
├── DemoLifecycle PluginLifecycle + PluginInfo
├── DemoAdminModel backs the card and the admin fragment
├── DemoConsoleController @ConsoleScreen: RequestContext, AccessCheck, Messages.console, SitePages, ContentCatalogView
└── Html escaping (every axis that returns HTML owns its escaping)
```
---
## 3. Wiring: how a plugin gets the kernel's services (`DemoPluginConfig`)
The kernel registers `mainClass` into its Spring context **before refresh**; the plugin's `@Bean` methods receive
the services as ordinary parameters. There is nothing else to learn — no lookup, no handle, no host class.
```java
@Bean
public DemoShowcaseStore runwayDemoShowcaseStore(PluginSiteFiles files, ContentChanges changes) {
return new DemoShowcaseStore(files, changes);
}
```
- **Plugin-scoped services** — `PluginSettings`, `PluginSiteFiles`, `ContentChanges`, `PluginInfo` — are bound to
*this* plugin by **the jar the injecting class was loaded from** (`DemoPluginConfig` is in the plugin's own jar).
No method takes a plugin id, so a plugin can never read another's settings or files. Inject them in your own
classes: injection from a `lib/` jar, from kernel code, or through a bare `getBean(...)` fails at startup.
- **Kernel singletons** — `Sites`, `RequestContext`, `AccessCheck`, `Messages`, `SitePages`, `ContentCatalogView`.
- **Bean names start with the plugin id in lowerCamelCase** (`runwayDemo…`); the kernel
blocks a plugin with any other name. The demo's app-level settings bean is therefore a
`@Bean @ConfigurationProperties("runway.plugin.runway-demo")` method, **not** `@EnableConfigurationProperties`
(which names the bean `runway.plugin.runway-demo-mx.quest.demo.DemoAppProps`).
- **What a plugin may contribute to Spring:** SPI implementations, plain beans, and `@Controller`s mapped under
`/__admin/<id>` or `/__app/<id>`. **Not:** servlet `Filter`s, `SecurityFilterChain`s, bean (factory)
post-processors, unrestricted `@ControllerAdvice`. Return the **concrete** class from a `@Bean` method so Spring
sees every interface it implements (`DemoShowcaseSource` is a content source *and* a listener).
---
## 4. The service tier, one service at a time
Each subsection: what the demo does, where, and **when you would use it**.
### 4.1 `PluginSettings` — my per-site settings
*Where:* `DemoAnalyticsHead`, `DemoNoticeWidget`, `DemoFeedbackWidget`, `DemoMetaLengthCheck`, `DemoEndpoints`,
`DemoAdminModel`.
```java
SettingsView site = settings.site(view.site().id());
if (!site.bool("notice.enabled", true)) { return RenderFragment.empty(); }
int maxChars = (int) site.integer("notice.max-chars", 280, 1, 2000); // clamped
```
`site(siteId)` returns the descriptor's `siteSettings:` defaults overlaid by what the operator saved; the typed
accessors never throw (a bad value yields the fallback). `secret(siteId, key)` hands a `type: secret` value back in
clear — `DemoAdminModel.siteTokenConfigured` only asks whether `analytics.site-token` is set and never shows it.
**Use it** for every per-site setting read; a save applies at once on every node. App-level (platform) settings
are not here: they bind through `@ConfigurationProperties` under `runway.plugin.<id>.*` and apply on restart
(`DemoAppProps`).
### 4.2 `PluginInfo` and `PluginLifecycle` — who am I, and the start/stop hook
*Where:* `DemoLifecycle` (and `PluginInfo` injected into `DemoAdminModel` and the console controller).
`started(PluginInfo self)` runs once the platform is up, in plugin load order; `stopping()` at shutdown, in reverse
order, only if `started` returned normally. Both block the host's thread — keep them short. The demo logs
`runway-demo 2.1.0 started — install dir …; built against SPI 1.0.0, running on SPI 1.0.0`:
`RunwaySpi.VERSION` is a compile-time constant (what the plugin was **built against**, copied into the plugin's
classes), `RunwaySpi.runtimeVersion()` is the running kernel's. **Use it** to open an
index, start your own executor, warm a cache — and to close them again.
### 4.3 `PluginSiteFiles` and `siteData.personal` — my per-site data
*Where:* `DemoNotesStore` (`notes.yml`), `DemoShowcaseStore` (`showcase.yml`).
The plugin's folder of a site, `sites/<id>/plugins/runway-demo/`: inside the site folder, so **full backups carry it
and a deleted site takes it along** — no `BackupParticipant` needed. Paths are relative, confined (no `..`, no
symlink escape), each write is atomic; a **read-modify-write** (append a note) is the plugin's to serialize, which
the store does per site. A write for a site whose folder does not exist fails rather than creating it.
**A `GET` never writes.** Opening the console screen, the settings page or `/demo/notes.json` only reads. A site
with no notes yet shows a welcome note, but the store does not save it then: the site has no `notes.yml` until the
first write — a console note, a visitor's message or the settings audit note. That first write saves the welcome
note together with the new note, so the note the operator saw stays in the list (it gets the time of that write).
**Rule:** a page that only shows data must not change a site. Show defaults from memory; write on the first `POST`.
(2.0.0 wrote the welcome note on the first read, so each site got a `notes.yml` as soon as someone opened the
screen.)
`notes.yml` holds what people typed, so `plugin.yml` declares it:
```yaml
siteData:
personal:
- notes.yml
```
A **transfer copy** of the site (for someone outside the organisation) leaves it out and lists it in the
manifest; a full backup keeps it. **Rule:** any file holding visitor or user input is personal. The showcase is
published content and is not declared.
### 4.4 `Sites` — a site's view from its id, off-request
*Where:* `DemoAdminModel.siteName` (a console fragment only has `tenantSiteId`), `DemoActivity.onSiteLifecycle`
(a listener only has the event's site id).
**Use it** whenever code that knows only an id — a listener, a background task, a fragment — needs the site's
name, locales or base URL. Empty for an unknown id; an unsafe id throws.
### 4.5 `RequestContext` — which site is this console request about?
*Where:* `DemoConsoleController.boundSite()`.
A console screen has no `RouteRequest`; `RequestContext.site()` is how it learns the tenancy. It is **empty on the
application console** (`/__app/…`), so the screen answers `404` there. An endpoint does not need it: its
`RouteRequest` already carries the site.
### 4.6 `AccessCheck` — may the current user do this?
*Where:* `DemoEndpoints` (`/demo/notes.json` → `403` without `runway-demo|manage-notes`), every console handler
(`@PreAuthorize("@authz.may('runway-demo|manage-notes')")`), the starter-page install (`may("EDIT_PAGES")`, a
kernel permission), and the admin fragment (`${@authz.may('runway-demo|manage-notes')}` shows the screen link).
One bean, three spellings: inject `AccessCheck` in Java, `@authz` in `@PreAuthorize` and templates. Fail-closed:
no request, no principal, an undeclared key, or an anonymous route → `false`. **Use it** every time your code
decides; a menu entry's or card's `permission:` only hides UI (and must be the full key `<id>|<permission>`).
### 4.7 `Messages` — localized text for visitors and for operators
*Where:* `Messages.site` in `DemoEndpoints.hello`, both widgets, the showcase title, the starter page title;
`Messages.console` for the console screen's flash messages.
`site(siteId, locale, code, fallback, args…)` resolves the site's own bundle first, then every plugin's `i18n/`
(add-only), in the **visitor's** locale; `console(code, fallback, args…)` resolves the console bundles in the
**operator's** UI language. With arguments the text is a `MessageFormat` pattern (write `''` for an apostrophe).
Templates use `#{…}` for the same console bundle.
### 4.8 `SitePages` — install my starter page
*Where:* `DemoConsoleController.installPage` (and `pathOf` in `DemoAdminModel` and the screen).
The demo page (`/demo`, slug `runway-demo`, `noindex`) carries both widget anchors and pulls the site's chrome
through `${master}`. `install` never overwrites and **never publishes around the site's editorial level**:
| Outcome | When | The demo says |
|---|---|---|
| `PUBLISHED` | Advisory site; Enforced/Reviewed with the checks passing and the right to approve | "Demo page published at /demo." |
| `PENDING_REVIEW` | Reviewed site, the user lacks `APPROVE_PAGES` | "… waiting in the review queue." |
| `DRAFT_BLOCKED` | the quality checks blocked publishing | "… as a draft: the quality checks blocked publishing." + the findings |
| `ALREADY_EXISTS` | the slug exists (any state) | "A demo page already exists at /demo; nothing changed." |
The `switch` has a `default` branch (the enum may grow). The plugin checks the caller may edit pages **before**
calling — `SitePages` leaves that to the plugin. `pathOf` finds the page wherever an operator moved it.
### 4.9 `ContentCatalogView` — the site's published content surface
*Where:* the console screen's *Content surface* card.
`entries(siteId)` lists every published page and content item with the URLs **the host computed** (the same
computation as the page `<head>`, so a listing never disagrees with the pages). `pageAt(siteId, path, locale)`
answers which published page owns a path; `servablePath(siteId, path)` whether content may live there at all (not
`/__…`, `/login`, an endpoint route…). `refresh(siteId)` drops the cached listing — a manual reindex; ordinary
changes never need it. **Use it** for a sitemap, a search index, an "is this path taken?" check.
### 4.10 `ContentSource` + `ContentChanges` — my own routable content
*Where:* `DemoShowcaseSource` (the source), `DemoShowcaseStore.publish/unpublish` (the announcements).
The source serves `/demo/showcase` through the kernel's routing, the site's chrome, the sitemap and on-site search
(`CAP_INDEXABLE_TEXT`). `enumerate` is metadata-only (it runs on anonymous requests); `resolve` is a cheap path
comparison; `body` renders the escaped text into `templates/showcase.*`, which may rely only on `${master}`,
`${content.*}`, `${locale}` and `${urls[…]}`. Every publish moves `updatedAt`, which the page's `ETag` folds.
After every write, the store announces it — after the write, outside its own lock:
```java
files.writeText(siteId, FILE, yaml.writeValueAsString(...));
changes.changed(siteId, DemoShowcaseSource.SOURCE_KEY, DemoShowcaseSource.ID);
```
On return, routing, the listing, sitemaps and search have been evicted on every node and every listener on this
node has run. The kernel refuses a source key the plugin does not own, and a call from inside a
`SiteEventListener` callback (a test proves the second).
### 4.11 `SiteEventListener` — react to changes
*Where:* `DemoShowcaseSource` (phase `SOURCE`) and `DemoActivity` (phase `CONSUMER`, the default).
- **`SOURCE`** is for a content source dropping its own state. All `SOURCE` listeners run first, the kernel evicts
its listing again, then the `CONSUMER`s — so a consumer that re-reads the listing never sees a source's stale
state. The showcase source evicts its cached read on its own `CONTENT` changes (a change **replayed from another
node** is the only way this node learns the file changed) and on wholesale lifecycle events (`DELETED`,
`RESTORED`).
- **`CONSUMER`** reacts to everything else. `DemoActivity`:
- `onSettingsChanged` — a save of **this plugin's own** settings; appends the audit note **only when
`change.local()`**, so a cluster writes it once, not once per node;
- `onCatalogChanged` — records each change (`page`, `content`, `site`, `settings`) with `previousUrls` (where
the item was — a deleted page still names its old address) and `currentUrls` (where it is now); the console's
*Recent changes* shows them;
- `onSiteLifecycle` — logs the event with the site's name (`Sites`) and drops what it recorded on a wholesale
event.
The kernel guarantees: every kernel cache is already evicted when a callback runs; no host lock is held (calling
any service is safe); a throwing callback is logged and counted, never propagated. Callbacks run on the writer's
thread: **evict, record or enqueue** — anything slow belongs on your own executor.
### 4.12 `@ConsoleScreen` — a screen inside the console
*Where:* `DemoConsoleController` + `templates/console.*`; the menu entry opens it.
```java
@Controller
@ConsoleScreen
@RequestMapping("/__admin/runway-demo")
public class DemoConsoleController {
@GetMapping
@PreAuthorize("@authz.may('runway-demo|manage-notes')")
public String screen(...) {
model.addAttribute(ConsoleScreen.CONTENT_TEMPLATE, "__plugin__/runway-demo/console");
model.addAttribute(ConsoleScreen.PAGE_TITLE_KEY, "runwaydemo.console.title");
return ConsoleScreen.LAYOUT_VIEW;
}
}
```
The kernel fills the shell (topbar, menus, language switcher, footer); the plugin needs no `@ControllerAdvice`.
Every mapping lies under `/__admin/runway-demo`, so the console's sign-in, realm security and CSRF apply. The
content template may rely on `tenantSiteId`, `_csrf`, `${@<own bean>…}`, `${@authz.may(…)}`, `#{…}` — and on
what the controller itself put in the model (`rd`). The screen renders its own flash (`runwayDemoFlash`,
`runwayDemoError`); the shell's flash region is not promised to plugins.
**The `POST` rule.** The `GET` only reads. Everything that changes state — add a note, install the page, publish or
unpublish the showcase, refresh the listing — is a `<form method="post">` carrying the session's token
(`<input class="rd-csrf" type="hidden" name="_csrf">`, bound in `console.th.xml` to `${_csrf}`), followed by a
redirect (post/redirect/get). A link or an `<img>` on another web site can therefore never act through a signed-in
operator's browser. Spring MVC binds the form fields (`@RequestParam`).
### 4.13 The anonymous `POST` route — a public form without a token
*Where:* `DemoEndpoints` (`Route.anonymousPost("/demo/feedback", …)`) + `DemoFeedbackWidget`.
A form on a page every visitor shares (and caches) cannot carry a per-session CSRF token, and an anonymous visitor
has no session. Declaring the route `anonymous` exempts **exactly that method and path** from CSRF; the kernel
makes that safe by running the handler with **no principal** (`AccessCheck.may` is `false` even for a signed-in
administrator) and accepting only an `application/x-www-form-urlencoded` body (`415` otherwise). The handler keeps
its own guards — a honeypot field, a length cap, five messages per minute per `req.clientIp()` (the address after
the kernel's trusted-proxy gate; never a header) — reads the fields from `req.form()` only (personal text never in
a URL), and answers `303` back with only an outcome flag the widget renders. **Use it** only for a form any visitor
may submit with no account; never for an action on something a signed-in user owns.
---
## 5. The axes (pure functions of their inputs)
| Axis | Class | Notes |
|---|---|---|
| `HeadContributor` | `DemoAnalyticsHead` | `@Order(200)`; returns `""`, never `null`; `headInputs` names `plugins/runway-demo.yml` so a settings change moves the page `ETag`; emits plain `<script src>` (the kernel stamps the CSP nonce) |
| `ContentWidget` | `DemoNoticeWidget`, `DemoFeedbackWidget` | anchor `<div id="…" data-widget="<key>/<instance>">`; `RenderFragment.empty()` to stay silent; reads only its view (the query, the path) |
| `PageQualityCheck` | `DemoMetaLengthCheck` | an `ERROR` blocks publishing on Enforced/Reviewed sites — the demo's `h1.missing` is an `ERROR` on purpose |
| `EndpointContributor` | `DemoEndpoints` | exact paths, tenant realm; `RouteRequest` carries locale, query, form, lowercase headers, `clientIp`, `origin` |
| `ContentSource` | `DemoShowcaseSource` | §4.10 |
A throwing axis is contained by the kernel (empty head/widget output served `no-store`, a `500` for an endpoint)
and counted on the plugins screen.
---
## 6. What the demo deliberately does not do
- **No servlet filter.** **Servlet filters are outside the Runway 1.0 plugin contract:** a filter needs servlet types the SPI does not
carry, runs on every request of every site, and no feature plugin needs one. `FilterBand` stays a kernel concept
(it places the kernel's and the essential protection plugin's filters). A plugin that wants to shape a response
uses an axis — a head contributor, a widget, an endpoint. The kernel blocks a plugin with
a `Filter` bean.
- **No `BackupParticipant`.** The notes live in the site's folder, which backups carry. The axis remains for data a
plugin keeps *outside* the site folder (none in 1.0).
- **No `@Primary`.** That is for the singleton kernel seams the essential `protection` plugin arms; every demo
contribution is collected by type.
- **No `requires:` / `conflicts:`** (a hard dependency would stop the demo from always loading); the forms are in
the descriptor's comments.
- **`essential` is not claimed** — only kernel security-floor ids on the allowlist may.
- **No per-instance widget config** (`widgetSettings:`): the `search` plugin is the example of that.
---
## 7. Templates and i18n
- **Decoupled Thymeleaf**: markup in `.html` with zero `th:*`, logic in the sibling `.th.xml`. A repeated `id` in a
`.html` is a hard error (a test forbids it); iterated rows use classes and `//` selectors. Form actions are
constants in the markup (`th:action`/`th:attr` run in a restricted context).
- **Fragments** (`dashboard`, `admin`) are bare (a root element, no `<html>`) and read the plugin's own bean
`${@runwayDemoAdminModel…}` with `tenantSiteId`.
- **The body template** (`showcase`) pulls the site's chrome by the `${master}` variable, never a literal name.
- **i18n**: `i18n/messages[_es].properties` is appended to the console's and every site's message sources
(add-only). The descriptor's labels, the console templates' `#{…}` and both `Messages` calls read it. A test
keeps English and Spanish in step and fails on a key used but missing.
---
## 8. Tests
`mvn verify` runs 82 tests over `runway-spi-testkit` (no kernel, no Spring Boot):
| Class | Covers |
|---|---|
| `DemoSpiUnitTest` | head, both widgets, quality check, every endpoint route incl. the anonymous feedback POST (honeypot, blank, query ignored, rate limit, foreign return path), lowercase header names |
| `DemoNotesStoreTest` | the notes over `TempDirSiteFiles`: a read shows the welcome and writes nothing, the first append keeps it, order, caps, isolation, lenient reads, an unreadable file never overwritten, a missing site, unsafe ids |
| `DemoShowcaseTest` | publish/unpublish announce through `EventDispatch`, the source's refs/body/resolve, `updatedAt`, the TTL backstop, eviction on a replayed change and on wholesale events only, the kernel's refusal from inside a callback |
| `DemoActivityTest` | own vs other plugins' settings, `local`, URLs before/after, the bound, wholesale drops, failures contained |
| `DemoConsoleControllerTest` | the screen and each action through MockMvc: the shell model, opening the screen writes no file, 404 on the app console, every flash, `EDIT_PAGES`, every install outcome, a failed install, the path check, refresh |
| `DemoTemplatesTest` | every `POST` action has a form carrying the CSRF field; no link points at an action; no repeated id; every selector matches |
| `DemoPluginConfigTest` | wiring from SPI fakes alone, bean names, forbidden Spring types, the controller's gates and mappings, template bean references, descriptor (floor, version, personal data, menu, secrets), i18n, **the compiled classes link no `mx.quest.runway` class outside `.spi`**, the removed classes are gone |
Mutation-checked: 20 deliberate breaks (the `local` gate, each eviction, each announcement, the honeypot, the rate
limit boundary, the permission gates, body-only fields, a missing `@PreAuthorize`, the notes bound, the
personal-data declaration, the TTL boundary, escaping, the open-redirect guard, a form's CSRF field, an
unprefixed bean name, the clamp) — each makes a test fail.
---
## 9. Build, install, verify
```bash
export JAVA_HOME=<a JDK 25>
cd demo && mvn verify
# target/runway-demo/ the install-ready folder
# target/runway-plugin-runway-demo-<version>.zip the archive the management UI upload expects (byte-reproducible)
JAVA_HOME=/path/to/jdk-25 HOST_JAR=…/runway-app-1.0.0-exec.jar VERIFY_TMPDIR=… VERIFY_LOG_DIR=… scripts/verify-against-host.sh
```
The first build downloads its Maven dependencies, and needs the `runway-spi` jars installed in `~/.m2` as the
[authoring guide §2](../../docs/PLUGIN-AUTHORING-GUIDE.md#2-prerequisites) describes.
The verify script never runs `mvn install`. Its result for 2.1.0: **58 passed, 0 failed**.
From the host log:
```
plugins: 1 registered, 0 blocked
runway-demo 2.1.0 started — install dir …/plugins/runway-demo; built against SPI 1.0.0, running on SPI 1.0.0
runway-demo settings changed for site 'default': audit note appended (now 4 notes)
transfer export: blanked 1 secret value(s) in runway-demo.yml: [analytics.site-token]
```
Four notes: the welcome note (stored by the first write, a visitor's message), that message, the operator's note
and the audit note. Before the first write, the signed-in site user (`owner`) opened the screen, `notes.json` and the settings page, and
the site still had no `notes.yml`.
The log shows no host-linkage ("uses host internals"), bean-name or surface finding — each would block the plugin,
which the script's `is blocked` check catches. *Recent changes* after installing the page and publishing then
unpublishing the showcase (newest first):
```
content runway-demo:showcase before /demo/showcase after —
content runway-demo:showcase before — after /demo/showcase
page pages:runway-demo before — after /demo
page pages:runway-demo before — after /demo
```
(The install is two page writes — the draft, then its publication.)
---
## 10. Known limits
- A non-anonymous `EndpointContributor` `POST` is not limited to header tokens: it reads every form field whether
the CSRF token travels as a form **field** or in the `X-CSRF-TOKEN` header. The demo keeps its operator actions in a
`@ConsoleScreen` controller by choice.
- *Recent changes* is per node and in memory (it is a demonstration of the callback, not an audit log); it starts
empty after a restart.
- Changes nobody announces (a file edited by hand) reach the showcase within its 60-second cache lifetime and the
content listing within its own 30 seconds.
@@ -0,0 +1,9 @@
# Writing a Runway plugin — moved
The authoring guide is maintained in **one place**: [`../../docs/PLUGIN-AUTHORING-GUIDE.md`](../../docs/PLUGIN-AUTHORING-GUIDE.md)
at `plugins/docs/`.
This file used to hold a copy of it. The copy had drifted (it still described host-coupled seams — `RunwayPlugin`,
`FilterContribution`, `SitePluginConfigService` — that the SPI service tier replaced), and a stale copy beside the
reference plugin is worse than none. For how the demo itself uses every service, read
[`DEMO-PLUGIN.md`](DEMO-PLUGIN.md).
+118
View File
@@ -0,0 +1,118 @@
# =============================================================================
# runway-demo plugin i18n bundle (English).
#
# The Runway kernel appends this bundle to the operator console's MessageSource AND to every site's public
# MessageSource (add-only: a plugin may add keys but never override a core or site key). Console text is read
# with #{...} in the console templates and Messages.console(...) in Java; visitor-facing text with
# Messages.site(siteId, locale, ...). A message that takes arguments ({0}) is a java.text.MessageFormat pattern:
# write a literal apostrophe as ''. Keys live WITH the plugin, never in core. Keep messages_es.properties in step
# (a test checks both define the same keys).
# =============================================================================
# --- Control-point permission labels ---
runwaydemo.perm.settings=Configure the Runway Demo plugin
runwaydemo.perm.manageNotes=Manage Runway Demo notes
# --- App-level settings labels ---
runwaydemo.settings.bannerEnabled=Show the site-wide banner
runwaydemo.settings.bannerText=Site-wide banner text
runwaydemo.settings.cacheMax=Cache size (entries)
runwaydemo.settings.generatorLabel=Generator meta-tag label
runwaydemo.settings.writeKey=Analytics write key (secret)
# --- Per-site settings labels ---
runwaydemo.settings.noticeEnabled=Show the notice widget
runwaydemo.settings.noticeStyle=Notice style
runwaydemo.settings.noticeMax=Notice maximum length
runwaydemo.settings.analyticsEnabled=Enable analytics head tags
runwaydemo.settings.siteToken=Per-site analytics token (secret)
runwaydemo.settings.feedbackEnabled=Accept messages from the public feedback form
runwaydemo.settings.titleRatio=Title-length warning ratio
runwaydemo.settings.ignoreCodes=Suppressed quality-check codes
# --- Menu ---
runwaydemo.menu.console=Runway demo
# --- Public (site) text: Messages.site ---
runwaydemo.hello=Hello from the runway-demo plugin!
runwaydemo.notice.body=This is the runway-demo notice widget (instance "{0}") on site "{1}".
runwaydemo.feedback.label=Leave a message
runwaydemo.feedback.send=Send
runwaydemo.feedback.thanks=Thank you — your message was kept.
runwaydemo.feedback.invalid=Please write a message first.
runwaydemo.feedback.limited=Too many messages from your address — please try again in a minute.
runwaydemo.showcase.title=Showcase
runwaydemo.page.title=Runway demo
# --- Dashboard card and admin fragment ---
runwaydemo.card.notes=Notes: {0}
runwaydemo.card.versions=Plugin {0} · built against SPI {1} · running on SPI {2}
runwaydemo.card.console=Open the demo screen
runwaydemo.admin.title=Runway Demo — status and notes
runwaydemo.admin.notes=Notes for this site: {0}
runwaydemo.admin.banner=App-level banner enabled: {0}
runwaydemo.admin.writeKey=App-level analytics key configured: {0}
runwaydemo.admin.siteToken=Per-site analytics token configured: {0}
runwaydemo.admin.page=Demo page at {0}
runwaydemo.admin.page.none=The demo page is not installed.
# --- Console screen (@ConsoleScreen): #{...} and Messages.console ---
runwaydemo.console.title=Runway demo
runwaydemo.console.heading=Runway demo
runwaydemo.console.help=Help
runwaydemo.console.yes=yes
runwaydemo.console.no=no
runwaydemo.console.ioError=The change could not be saved.
runwaydemo.console.about=This plugin
runwaydemo.console.version=Version
runwaydemo.console.builtSpi=Built against SPI
runwaydemo.console.runningSpi=Running on SPI
runwaydemo.console.page=Demo page
runwaydemo.console.page.desc=A ready-made page carrying the notice and feedback widgets. It is installed through the site's editorial rules and then belongs to the site like any other page.
runwaydemo.console.page.at=Installed at
runwaydemo.console.page.install=Install the demo page
runwaydemo.console.page.forbidden=Installing a page needs the permission to edit pages.
runwaydemo.console.page.failed=The demo page could not be installed.
runwaydemo.console.page.published=Demo page published at {0}.
runwaydemo.console.page.pending=Demo page created at {0} and waiting in the review queue.
runwaydemo.console.page.blocked=Demo page created at {0} as a draft: the quality checks blocked publishing.
runwaydemo.console.page.exists=A demo page already exists at {0}; nothing changed.
runwaydemo.console.page.other=Demo page install finished: {0} {1}
runwaydemo.console.notes=Notes
runwaydemo.console.notes.desc=Kept in the plugin's own folder of this site. They hold what people typed, so they are declared personal data and transfer copies leave them out.
runwaydemo.console.note.new=New note
runwaydemo.console.note.add=Add note
runwaydemo.console.note.blank=Write something first.
runwaydemo.console.note.added=Note added.
runwaydemo.console.showcase=Showcase page
runwaydemo.console.showcase.desc=Served by the plugin's content source. Publishing or unpublishing announces the change, so routing, sitemaps and search follow at once.
runwaydemo.console.showcase.at=Published at
runwaydemo.console.showcase.text=Showcase text
runwaydemo.console.showcase.publish=Publish
runwaydemo.console.showcase.unpublish=Unpublish
runwaydemo.console.showcase.empty=Nothing is published.
runwaydemo.console.showcase.blank=Write something first.
runwaydemo.console.showcase.published=Showcase published at {0}.
runwaydemo.console.showcase.unpublished=Showcase unpublished.
runwaydemo.console.showcase.none=No showcase was published.
runwaydemo.console.catalog=Content surface
runwaydemo.console.catalog.source=Source
runwaydemo.console.catalog.item=Item
runwaydemo.console.catalog.path=Path
runwaydemo.console.catalog.refresh=Refresh the listing
runwaydemo.console.catalog.refreshed=Content listing refreshed.
runwaydemo.console.check=Check a path
runwaydemo.console.check.path=Path
runwaydemo.console.check.unsafe=unsafe path
runwaydemo.console.check.servable=content may live here
runwaydemo.console.check.reserved=reserved: no content may live here
runwaydemo.console.check.owner=owned by the published page {0}
runwaydemo.console.check.free=no published page owns it
runwaydemo.console.activity=Recent changes
runwaydemo.console.activity.empty=No change seen since the platform started.
runwaydemo.console.activity.at=When
runwaydemo.console.activity.cause=Cause
runwaydemo.console.activity.item=Item
runwaydemo.console.activity.before=URLs before
runwaydemo.console.activity.after=URLs after
runwaydemo.console.activity.local=On this node
+108
View File
@@ -0,0 +1,108 @@
# =============================================================================
# Paquete i18n del plugin runway-demo (Español).
# El kernel de Runway añade este paquete al MessageSource de la consola Y al MessageSource público de cada sitio
# (solo añade: un plugin puede agregar claves pero nunca sobrescribir una del núcleo o del sitio). Un mensaje con
# argumentos ({0}) es un patrón java.text.MessageFormat: un apóstrofo literal se escribe ''. Debe definir las
# mismas claves que messages.properties (lo comprueba una prueba).
# =============================================================================
runwaydemo.perm.settings=Configurar el plugin Runway Demo
runwaydemo.perm.manageNotes=Gestionar las notas de Runway Demo
runwaydemo.settings.bannerEnabled=Mostrar el aviso de todo el sitio
runwaydemo.settings.bannerText=Texto del aviso de todo el sitio
runwaydemo.settings.cacheMax=Tamaño de caché (entradas)
runwaydemo.settings.generatorLabel=Etiqueta de la meta-etiqueta generator
runwaydemo.settings.writeKey=Clave de escritura de analítica (secreto)
runwaydemo.settings.noticeEnabled=Mostrar el widget de aviso
runwaydemo.settings.noticeStyle=Estilo del aviso
runwaydemo.settings.noticeMax=Longitud máxima del aviso
runwaydemo.settings.analyticsEnabled=Activar etiquetas de analítica en head
runwaydemo.settings.siteToken=Token de analítica del sitio (secreto)
runwaydemo.settings.feedbackEnabled=Aceptar mensajes del formulario público de comentarios
runwaydemo.settings.titleRatio=Ratio de aviso por longitud de título
runwaydemo.settings.ignoreCodes=Códigos de comprobación suprimidos
runwaydemo.menu.console=Demo de Runway
runwaydemo.hello=¡Hola desde el plugin runway-demo!
runwaydemo.notice.body=Este es el widget de aviso de runway-demo (instancia "{0}") en el sitio "{1}".
runwaydemo.feedback.label=Deja un mensaje
runwaydemo.feedback.send=Enviar
runwaydemo.feedback.thanks=Gracias — guardamos tu mensaje.
runwaydemo.feedback.invalid=Escribe un mensaje primero.
runwaydemo.feedback.limited=Demasiados mensajes desde tu dirección — inténtalo de nuevo en un minuto.
runwaydemo.showcase.title=Escaparate
runwaydemo.page.title=Demo de Runway
runwaydemo.card.notes=Notas: {0}
runwaydemo.card.versions=Plugin {0} · compilado con SPI {1} · ejecutándose en SPI {2}
runwaydemo.card.console=Abrir la pantalla de la demo
runwaydemo.admin.title=Runway Demo — estado y notas
runwaydemo.admin.notes=Notas de este sitio: {0}
runwaydemo.admin.banner=Aviso de la aplicación activado: {0}
runwaydemo.admin.writeKey=Clave de analítica de la aplicación configurada: {0}
runwaydemo.admin.siteToken=Token de analítica del sitio configurado: {0}
runwaydemo.admin.page=Página de la demo en {0}
runwaydemo.admin.page.none=La página de la demo no está instalada.
runwaydemo.console.title=Demo de Runway
runwaydemo.console.heading=Demo de Runway
runwaydemo.console.help=Ayuda
runwaydemo.console.yes=sí
runwaydemo.console.no=no
runwaydemo.console.ioError=No se pudo guardar el cambio.
runwaydemo.console.about=Este plugin
runwaydemo.console.version=Versión
runwaydemo.console.builtSpi=Compilado con SPI
runwaydemo.console.runningSpi=Ejecutándose en SPI
runwaydemo.console.page=Página de la demo
runwaydemo.console.page.desc=Una página lista para usar con los widgets de aviso y de comentarios. Se instala según las reglas editoriales del sitio y después pertenece al sitio como cualquier otra página.
runwaydemo.console.page.at=Instalada en
runwaydemo.console.page.install=Instalar la página de la demo
runwaydemo.console.page.forbidden=Instalar una página requiere el permiso de editar páginas.
runwaydemo.console.page.failed=No se pudo instalar la página de la demo.
runwaydemo.console.page.published=Página de la demo publicada en {0}.
runwaydemo.console.page.pending=Página de la demo creada en {0}, en espera en la cola de revisión.
runwaydemo.console.page.blocked=Página de la demo creada en {0} como borrador: las comprobaciones de calidad bloquearon la publicación.
runwaydemo.console.page.exists=Ya existe una página de la demo en {0}; no se cambió nada.
runwaydemo.console.page.other=Instalación de la página de la demo terminada: {0} {1}
runwaydemo.console.notes=Notas
runwaydemo.console.notes.desc=Se guardan en la carpeta propia del plugin en este sitio. Contienen lo que la gente escribió, así que se declaran datos personales y las copias de transferencia las omiten.
runwaydemo.console.note.new=Nota nueva
runwaydemo.console.note.add=Agregar nota
runwaydemo.console.note.blank=Escribe algo primero.
runwaydemo.console.note.added=Nota agregada.
runwaydemo.console.showcase=Página escaparate
runwaydemo.console.showcase.desc=La sirve la fuente de contenido del plugin. Publicar o retirar anuncia el cambio, así que el enrutamiento, los sitemaps y la búsqueda se actualizan al instante.
runwaydemo.console.showcase.at=Publicada en
runwaydemo.console.showcase.text=Texto del escaparate
runwaydemo.console.showcase.publish=Publicar
runwaydemo.console.showcase.unpublish=Retirar
runwaydemo.console.showcase.empty=No hay nada publicado.
runwaydemo.console.showcase.blank=Escribe algo primero.
runwaydemo.console.showcase.published=Escaparate publicado en {0}.
runwaydemo.console.showcase.unpublished=Escaparate retirado.
runwaydemo.console.showcase.none=No había ningún escaparate publicado.
runwaydemo.console.catalog=Superficie de contenido
runwaydemo.console.catalog.source=Fuente
runwaydemo.console.catalog.item=Elemento
runwaydemo.console.catalog.path=Ruta
runwaydemo.console.catalog.refresh=Actualizar el listado
runwaydemo.console.catalog.refreshed=Listado de contenido actualizado.
runwaydemo.console.check=Comprobar una ruta
runwaydemo.console.check.path=Ruta
runwaydemo.console.check.unsafe=ruta no segura
runwaydemo.console.check.servable=puede haber contenido aquí
runwaydemo.console.check.reserved=reservada: no puede haber contenido aquí
runwaydemo.console.check.owner=pertenece a la página publicada {0}
runwaydemo.console.check.free=ninguna página publicada la ocupa
runwaydemo.console.activity=Cambios recientes
runwaydemo.console.activity.empty=No se ha visto ningún cambio desde que arrancó la plataforma.
runwaydemo.console.activity.at=Cuándo
runwaydemo.console.activity.cause=Causa
runwaydemo.console.activity.item=Elemento
runwaydemo.console.activity.before=URL antes
runwaydemo.console.activity.after=URL después
runwaydemo.console.activity.local=En este nodo
+74
View File
@@ -0,0 +1,74 @@
# =============================================================================
# Runway Demo Plugin — descriptor
# The kitchen-sink REFERENCE plugin: it exercises every extension axis and every
# service of the SPI service tier, each the way a real plugin should
# use it. Copy it to start a new plugin. Links ONLY the Runway SPI.
# The install folder name MUST equal this `id`: external/plugins/runway-demo/.
# =============================================================================
id: runway-demo
name: Runway Demo (Kitchen-Sink Plugin)
version: 2.1.0
# The lowest SPI level this plugin needs; a kernel below it BLOCKS the plugin at startup with a reason. Declare the
# floor of the NEWEST type you use: without it, an older kernel would load the plugin and fail at the first request
# that touches a missing type. SPI 1.0.0 is the frozen 1.x contract.
requiresSpi: ">=1.0.0"
# The @Configuration registered into the host context before refresh. Its package lives OUTSIDE
# mx.quest.runway (mx.quest.demo) so the host never scans it, and every bean it defines is named runwayDemo…
mainClass: mx.quest.demo.DemoPluginConfig
# `enabled` (optional, default true) is the operator's disable switch — omit to stay enabled.
# `essential` is honored ONLY for kernel security-floor ids on the EssentialAllowlist (only 'protection'); a
# normal plugin must NOT claim it.
# `requires:` / `conflicts:` — this demo has no hard dependency, so it always loads. Forms (documented in
# docs/DEMO-PLUGIN.md): requires: [ some-id ], [ some-id >= 1.2.0 ], [ some-id == 1.2.0 ]; conflicts: [ id ].
# --- Personal data ---------------------------------------------------------------------------------------
# notes.yml holds what people typed: operator notes from the console AND visitors' messages from the public
# feedback form. A TRANSFER copy of a site (the one handed to someone outside the organisation) leaves it out
# and lists it in the archive's manifest; a FULL backup keeps it. Paths are relative to
# sites/<id>/plugins/runway-demo/ (end a folder with "/"). showcase.yml is published content, not personal.
siteData:
personal:
- notes.yml
# --- Grantable control-point permissions (namespaced <id>|<declId> in the catalog) -------------------
# `settings` is the reserved id that gates this plugin's per-tenant settings form.
# `manage-notes` gates the demo's console screen, its actions and /demo/notes.json (enforced server-side with
# AccessCheck / @authz.may on the FULL key "runway-demo|manage-notes"; the menu and card use the full key too).
# defaultRoles is EMPTY: control points start ungranted. Administrators hold them via the wildcard tier; a
# tenant superadmin grants them explicitly to the seed OPERATOR role or a custom role.
permissions:
- { id: settings, realm: tenant, label: runwaydemo.perm.settings, defaultRoles: [] }
- { id: manage-notes, realm: tenant, label: runwaydemo.perm.manageNotes, defaultRoles: [] }
# --- App-level settings (PLATFORM concerns; bound as runway.plugin.runway-demo.* from -------------------
# external/plugin-settings/runway-demo.yml; applied on RESTART; read via the DemoAppProps bean)
settings:
- { key: banner.enabled, type: boolean, default: true, label: runwaydemo.settings.bannerEnabled }
- { key: banner.text, type: text, label: runwaydemo.settings.bannerText }
- { key: cache.max-entries, type: int, default: 500, range: "1..100000", label: runwaydemo.settings.cacheMax }
- { key: generator.label, type: string, default: "Runway Demo", label: runwaydemo.settings.generatorLabel }
- { key: analytics.write-key, type: secret, label: runwaydemo.settings.writeKey }
# --- Per-tenant settings (tenant-owned BEHAVIOUR; stored in sites/<id>/plugins/runway-demo.yml; applied ----
# IMMEDIATELY; read with PluginSettings.site(siteId), a `secret` with PluginSettings.secret(siteId, key))
siteSettings:
- { key: notice.enabled, type: boolean, default: true, label: runwaydemo.settings.noticeEnabled }
- { key: notice.style, type: enum, default: info, range: "info,warning,danger", label: runwaydemo.settings.noticeStyle }
- { key: notice.max-chars, type: int, default: 280, range: "1..2000", label: runwaydemo.settings.noticeMax }
- { key: analytics.enabled, type: boolean, default: false, label: runwaydemo.settings.analyticsEnabled }
- { key: analytics.site-token, type: secret, label: runwaydemo.settings.siteToken }
- { key: feedback.enabled, type: boolean, default: true, label: runwaydemo.settings.feedbackEnabled }
- { key: quality.title-warn-ratio, type: decimal, default: 1.0, label: runwaydemo.settings.titleRatio }
- { key: quality.ignore-codes, type: list, default: "", label: runwaydemo.settings.ignoreCodes }
# --- Tenant-console menu entry: the demo's own console screen (@ConsoleScreen), gated by the FULL key -------
menu:
- { realm: tenant, region: menu, order: 60, label: runwaydemo.menu.console,
path: "/__admin/runway-demo", permission: "runway-demo|manage-notes", icon: "fa-solid fa-flask" }
# --- Tenant dashboard card (fragment resolves to __plugin__/runway-demo/dashboard = templates/dashboard.*) --
dashboardCards:
- { realm: tenant, order: 20, fragment: dashboard, permission: "runway-demo|manage-notes" }
+184
View File
@@ -0,0 +1,184 @@
<?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 dependency versions the Runway kernel uses (Spring Boot 4.0.6), so every
`provided` Spring / Jackson type the plugin compiles against is byte-identical to the class the host
loads at runtime. A plugin is NOT a Spring Boot application — there is NO spring-boot-maven-plugin
repackage here; `mvn package` produces a THIN jar of only this plugin's own classes.
-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.0.6</version>
<relativePath/>
</parent>
<groupId>mx.quest</groupId>
<!-- runway-plugin-<plugin id>, as for every plugin in this repository: the release zip is named after it
(runway-plugin-runway-demo-<version>.zip under the tag runway-demo-<version>). -->
<artifactId>runway-plugin-runway-demo</artifactId>
<version>2.1.0</version>
<packaging>jar</packaging>
<name>Runway Demo Plugin</name>
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<description>
The kitchen-sink REFERENCE plugin for Runway: every extension axis (head, widget, endpoint incl. an
anonymous form POST, page-quality check, content source) and every service of the SPI service tier
(PluginSettings, PluginInfo/PluginLifecycle, PluginSiteFiles, Sites, RequestContext, AccessCheck, Messages,
SitePages, ContentCatalogView, ContentChanges, SiteEventListener, @ConsoleScreen), app-level and per-tenant
settings, personal-data declaration, permissions, a menu entry, a dashboard card, an admin fragment, static
assets, templates and i18n. 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 this plugin compiles against: a RELEASED kernel (its SPI jars installed
from that release's assets). The plugin's runtime floor is plugin.yml's
requiresSpi, not this number. -->
<runway.version>1.0.0</runway.version>
</properties>
<dependencies>
<!--
The dependency-free extension API: the axis interfaces, the service tier and the immutable model
records. COMPILE scope — it is the host's own stable artifact, resolved parent-first from the shared
classloader at runtime. This is the ONLY Runway artifact a plugin depends on.
-->
<dependency>
<groupId>mx.quest</groupId>
<artifactId>runway-spi</artifactId>
<version>${runway.version}</version>
</dependency>
<!-- NO runway-app dependency, in any scope: a host import no longer compiles, and the
kernel's host-linkage scanner finds nothing to report. -->
<!-- In-memory fakes of every SPI service with the kernel's input rules (TempDirSiteFiles, FakePluginSettings,
FakeSiteServices, FakeContentCatalog, EventDispatch). Tests only. -->
<dependency>
<groupId>mx.quest</groupId>
<artifactId>runway-spi-testkit</artifactId>
<version>${runway.version}</version>
<scope>test</scope>
</dependency>
<!-- The PLATFORM libraries the host provides at runtime (the kernel's MAJOR line pins their MAJOR lines):
compile against them, never bundle them. -->
<!-- Spring context/Boot: @Configuration, @Bean, @ConfigurationProperties. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<scope>provided</scope>
</dependency>
<!-- Spring MVC: the @ConsoleScreen @Controller (DemoConsoleController). -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<scope>provided</scope>
</dependency>
<!-- Spring Security: @PreAuthorize("@authz.may('…')") on the console handlers. -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<scope>provided</scope>
</dependency>
<!-- Jackson 3 (tools.jackson) YAML: the plugin's own serializer for notes.yml and showcase.yml. -->
<dependency>
<groupId>tools.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<scope>provided</scope>
</dependency>
<!-- Unit tests run against the compiled classes (NEVER spring-boot:run — DevTools' restart classloader
loads ZERO plugins). The servlet API lets MockMvc drive the console controller in-process. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!-- Stable deployed filename (no version/classifier): target/runway-plugin-demo.jar. It deliberately keeps
its pre-2.0.1 name although the artifactId changed: the kernel loads EVERY *.jar in the plugin's folder
(plugin.yml names no jar), so a filesystem upgrade that copies the new folder over the old one would
otherwise leave the old jar beside the new and load both. The console upload replaces the whole
folder; a copy does not. -->
<finalName>runway-plugin-demo</finalName>
<plugins>
<!--
After the jar is built, assemble the plugin in BOTH installable forms the platform accepts:
1. target/runway-demo/ — the install-ready folder for a FILESYSTEM install
(`cp -r target/runway-demo <runway-external>/plugins/` + restart).
2. target/runway-plugin-runway-demo-<version>.zip — the archive the MANAGEMENT UI upload expects
(/__app/plugins → install): plugin.yml under a single wrapping dir (runway-demo/) alongside
the jar + static/ templates/ i18n/. The host validates the descriptor and lays it into
external/plugins/<id>/ (id from the descriptor), then applies on restart.
-->
<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}/runway-demo"/>
<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}/NOTICE" todir="${stage}"/>
<copy file="${project.build.directory}/runway-plugin-demo.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>
<!-- The UI-uploadable archive: plugin.yml under a single wrapping dir. -->
<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="runway-demo"/>
</touch>
<zip destfile="${project.build.directory}/${project.artifactId}-${project.version}.zip">
<zipfileset dir="${project.build.directory}" includes="runway-demo/**"/>
</zip>
<echo message="Staged install folder: ${stage}"/>
<echo message="UI-uploadable archive: ${project.build.directory}/${project.artifactId}-${project.version}.zip"/>
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env bash
#
# install-into.sh — copy the assembled runway-demo plugin into a Runway deployment's external tree.
# The host must be RESTARTED afterwards for the plugin to load (restart-to-install; no hot reload).
#
# Usage: scripts/install-into.sh <runway-external-dir>
# e.g. scripts/install-into.sh /opt/runway-data/external
set -euo pipefail
EXTERNAL="${1:?usage: install-into.sh <runway-external-dir>}"
PROJECT_DIR="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
STAGE="$PROJECT_DIR/target/runway-demo"
[ -d "$STAGE" ] || { echo "ERROR: $STAGE not built — run 'mvn package' first"; exit 1; }
[ -d "$EXTERNAL" ] || { echo "ERROR: not a directory: $EXTERNAL"; exit 1; }
mkdir -p "$EXTERNAL/plugins"
rm -rf "$EXTERNAL/plugins/runway-demo"
cp -a "$STAGE" "$EXTERNAL/plugins/runway-demo"
echo "installed runway-demo → $EXTERNAL/plugins/runway-demo"
echo "RESTART the Runway host for it to load (plugins load only in ACTIVE mode)."
+269
View File
@@ -0,0 +1,269 @@
#!/usr/bin/env bash
# Build the runway-demo plugin, drop it into a THROWAWAY Runway deployment, boot the PACKAGED host in ACTIVE mode, and
# prove the demo's contract end to end:
# - it loads with ZERO host-linkage and bean-name/surface warnings, and its PluginLifecycle hook runs;
# - head injection, the static assets, /demo/hello.txt and /demo/echo.json (lowercase headers, clientIp, origin);
# no timing header any more (servlet filters are outside the 1.0 plugin contract);
# - /demo/notes.json is permission-gated (AccessCheck): 403 anonymous, 200 for the signed-in owner;
# - a GET writes nothing: the owner opening the screen, notes.json and the settings page leaves the site with no
# notes.yml, though the screen shows the welcome note;
# - the anonymous feedback POST (no session, no CSRF token) is stored as a note and 303s back with only an outcome;
# honeypot, blank, query-string fields and a non-form body are refused; a GET submits nothing;
# - the @ConsoleScreen renders inside the console shell for the owner, is refused to an anonymous caller, and its
# actions are CSRF-checked POSTs (403 without the token); with the token: a note is added, the starter page is
# installed through SitePages and serves both widgets, the showcase ContentSource publishes (ContentChanges) and
# unpublishes, and the SiteEventListener shows each change with its URLs before and after;
# - saving the per-site settings appends the audit note (onSettingsChanged) and a per-site secret is read back
# (PluginSettings.secret) without being shown;
# - a FULL backup carries notes.yml and a TRANSFER copy leaves it out (siteData.personal) and lists it.
# 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 backup manifests and the fetched
# pages 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)"
VER="$(sed -n 's/^version: *//p' "$HERE/plugin.yml")" # the release under test
# 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=Demo-Admin-2026; SITE_USER=owner; SITE_PW=Demo-Site-2026
SECRET_KEY=demo-verify-master-key-2026
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"
mkdir -p "${VERIFY_TMPDIR:-${TMPDIR:-/tmp}}"
SCRATCH="$(mktemp -d "${VERIFY_TMPDIR:-${TMPDIR:-/tmp}}/runway-demo-verify.XXXXXX")"
cleanup() {
[ -z "${VERIFY_LOG_DIR:-}" ] || { mkdir -p "$VERIFY_LOG_DIR" \
&& cp "$SCRATCH"/*.log "$SCRATCH"/*-manifest.yml "$SCRATCH"/*.html "$SCRATCH"/*.json "$VERIFY_LOG_DIR"/ 2>/dev/null; }
# Wait for the host to exit before deleting: a JVM still shutting down rewrites files under external/ and makes
# `rm -rf` leave the scratch folder behind.
[ "$KEEP" = "yes" ] || { kill "${PID:-0}" 2>/dev/null; wait "${PID:-0}" 2>/dev/null; rm -rf "$SCRATCH"; }
}
trap cleanup EXIT
EXT="$SCRATCH/external"
mkdir -p "$EXT/plugins"
cp -r "$HERE/target/runway-demo" "$EXT/plugins/runway-demo"
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; }
boot() { ( cd "$SCRATCH" && exec "$JAVA" -jar "$JAR" --server.port="$PORT" --runway.storage.external="$EXT" \
--runway.security.secret-key="$SECRET_KEY" ) >"$1" 2>&1 & PID=$!; }
echo "[verify] booting host (wizard) on :$PORT ..."
boot "$SCRATCH/wizard.log"
wait_for "$SCRATCH/wizard.log" "Started RunwayApplication" 90 || { echo "wizard did not start"; tail -20 "$SCRATCH/wizard.log"; exit 1; }
curl -s -o /dev/null -X POST "$BASE/setup" --data-urlencode "username=$APP_USER" --data-urlencode "password=$APP_PW" \
--data-urlencode "displayName=Root" --data-urlencode "siteAdminUsername=$SITE_USER" --data-urlencode "siteAdminPassword=$SITE_PW"
for _ in $(seq 1 30); do kill -0 "$PID" 2>/dev/null || break; sleep 1; done
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"
SITES="$EXT/sites"
NOTES="$SITES/default/plugins/runway-demo/notes.yml"
code() { curl -s -o /dev/null -w '%{http_code}' "$@"; }
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 'runway-demo' is blocked|plugin-quarantine\" '$LOG'"
ck "ZERO host-linkage warnings" "! grep -q 'uses host internals' '$LOG'"
ck "ZERO bean-name/surface warnings" "! grep -qE \"plugin 'runway-demo': .*allowed until Runway 1.0\" '$LOG'"
ck "no WARN/ERROR names the plugin" "! grep -E ' (WARN|ERROR) ' '$LOG' | grep -qiE 'runway-demo|mx.quest.demo'"
ck "no key collision / degraded" "! grep -qiE 'collision|duplicate key|degraded' '$LOG'"
# The running SPI is the host's (0.6.0 on beta14, 1.0.0 on rc1): accept any, as the plugin itself reports both.
ck "PluginLifecycle.started ran with PluginInfo" \
"grep -qE 'runway-demo $VER started — install dir .*runway-demo; built against SPI [0-9]+\\.[0-9]+\\.[0-9]+, running on SPI [0-9]+\\.[0-9]+\\.[0-9]+' '$LOG'"
echo "== public surfaces =="
ck "static css, script and help page served" \
"[ \"\$(code '$BASE/__plugin/runway-demo/static/css/demo.css')\" = 200 ] && [ \"\$(code '$BASE/__plugin/runway-demo/static/js/demo-analytics.js')\" = 200 ] && [ \"\$(code '$BASE/__plugin/runway-demo/static/notes-help.html')\" = 200 ]"
curl -s -D "$SCRATCH/home-headers.txt" "$BASE/" > "$SCRATCH/home.html"
ck "head injection on / (generator meta + stylesheet)" \
"grep -q 'name=\"generator\" content=\"Runway Demo\"' '$SCRATCH/home.html' && grep -q '/__plugin/runway-demo/static/css/demo.css' '$SCRATCH/home.html'"
ck "no X-Demo-Plugin header (the servlet filter is gone)" "! grep -qi '^X-Demo-Plugin' '$SCRATCH/home-headers.txt'"
ck "GET /demo/hello.txt = 200, localized greeting" \
"curl -s '$BASE/demo/hello.txt' | grep -q '^Hello from the runway-demo plugin!'"
curl -s -H 'X-Test: Yes' "$BASE/demo/echo.json?q=1" > "$SCRATCH/echo.json"
ck "echo.json: lowercase header names, gated clientIp, origin, query" \
"grep -q '\"x-test\":\"Yes\"' '$SCRATCH/echo.json' && grep -qE '\"clientIp\":\"(127.0.0.1|\\[0:0:0:0:0:0:0:1\\])\"' '$SCRATCH/echo.json' && grep -q '\"origin\":\"http://localhost:$PORT\"' '$SCRATCH/echo.json' && grep -q '\"param.q\":\"1\"' '$SCRATCH/echo.json'"
ck "GET /demo/notes.json anonymous = 403 (AccessCheck)" "[ \"\$(code '$BASE/demo/notes.json')\" = 403 ]"
echo "== a GET writes nothing: the welcome note is shown, not stored =="
JAR_C="$SCRATCH/cookies.txt"
sc() { curl -s -H 'Accept-Language: en' -c "$JAR_C" -b "$JAR_C" "$@"; }
token() { grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//'; }
sc -o /dev/null -X POST "$BASE/login" --data-urlencode "username=$SITE_USER" --data-urlencode "password=$SITE_PW" \
--data-urlencode "_csrf=$(sc "$BASE/login" | token)"
sc "$BASE/__admin/runway-demo" > "$SCRATCH/screen-first.html"
sc -o /dev/null "$BASE/demo/notes.json"
sc -o /dev/null "$BASE/__admin/plugins/runway-demo/settings"
ck "the owner's screen shows the welcome note" "grep -q 'this note is data the runway-demo plugin' '$SCRATCH/screen-first.html'"
ck "…yet the screen, notes.json and the settings page wrote no notes.yml" "[ ! -e '$NOTES' ]"
echo "== the anonymous feedback POST (no session, no CSRF token) =="
post() { curl -s -o /dev/null -w '%{http_code} %{redirect_url}' -X POST "$@"; }
R="$(post "$BASE/demo/feedback" --data-urlencode 'return=/demo' --data-urlencode 'message=Hello from a visitor' \
--data-urlencode 'website=')"
ck "valid POST -> 303 back with ?demo-feedback=thanks" "[ \"\${R%% *}\" = 303 ] && echo '$R' | grep -q '/demo?demo-feedback=thanks'"
ck "the redirect carries no submitted value" "! echo '$R' | grep -qi 'visitor'"
ck "stored in sites/default/plugins/runway-demo/notes.yml as a visitor note" \
"grep -q 'Hello from a visitor' '$NOTES' && grep -q 'origin: \"\\?visitor' '$NOTES'"
ck "a GET submits nothing (404)" "[ \"\$(code '$BASE/demo/feedback?message=via-get')\" = 404 ] && ! grep -q 'via-get' '$NOTES'"
ck "a filled honeypot fakes success and stores nothing" \
"post '$BASE/demo/feedback' -d 'message=bot-spam&website=http://spam' | grep -q 'demo-feedback=thanks' && ! grep -q 'bot-spam' '$NOTES'"
ck "a blank message -> ?demo-feedback=invalid" "post '$BASE/demo/feedback' -d 'message=%20' | grep -q 'demo-feedback=invalid'"
ck "fields in the query string are ignored" \
"post '$BASE/demo/feedback?message=in-the-url' -d 'x=1' | grep -q 'demo-feedback=invalid' && ! grep -q 'in-the-url' '$NOTES'"
ck "a multipart body is refused 415 by the kernel" \
"[ \"\$(curl -s -o /dev/null -w '%{http_code}' -X POST '$BASE/demo/feedback' -F 'message=multi')\" = 415 ]"
ck "notes.yml is never served publicly" \
"( for u in '/plugins/runway-demo/notes.yml' '/__plugin/runway-demo/static/../../notes.yml'; do curl -s --path-as-is '$BASE'\$u | grep -q 'Hello from a visitor' && exit 1; done; exit 0 )"
echo "== the @ConsoleScreen and its CSRF-checked actions =="
ck "anonymous GET /__admin/runway-demo is refused (sign-in required)" \
"[ \"\$(code '$BASE/__admin/runway-demo')\" != 200 ]"
ck "anonymous POST without a token -> 403" "[ \"\$(code -X POST '$BASE/__admin/runway-demo/notes' -d text=x)\" = 403 ]"
# The owner signed in above (the GET-writes-nothing checks); the session is in $JAR_C.
SCREEN="$BASE/__admin/runway-demo"
sc "$SCREEN" > "$SCRATCH/screen-0.html"
ck "the owner sees the screen inside the console shell" \
"grep -q 'id=\"op-main\"' '$SCRATCH/screen-0.html' && grep -q 'id=\"rd-heading\"' '$SCRATCH/screen-0.html' && grep -q '<title id=\"op-title\">Runway demo · ' '$SCRATCH/screen-0.html'"
ck "…showing the plugin version and both SPI versions" \
"grep -q 'id=\"rd-version\">$VER<' '$SCRATCH/screen-0.html' && grep -qE 'id=\"rd-running\">[0-9]+\\.[0-9]+\\.[0-9]+<' '$SCRATCH/screen-0.html'"
ck "…and its actions as POST forms carrying a non-empty CSRF token" \
"grep -q 'method=\"post\" action=\"/__admin/runway-demo/install-page\"' '$SCRATCH/screen-0.html' && grep -qE 'class=\"rd-csrf\" type=\"hidden\" name=\"_csrf\" value=\"[^\"]+\"' '$SCRATCH/screen-0.html'"
ck "the owner's POST without the token -> 403, nothing added" \
"[ \"\$(sc -o /dev/null -w '%{http_code}' -X POST '$SCREEN/notes' -d text=forged)\" = 403 ] && ! grep -q forged '$NOTES'"
ck "a GET on an action path changes nothing" \
"[ \"\$(sc -o /dev/null -w '%{http_code}' '$SCREEN/install-page')\" != 302 ] && [ ! -e '$SITES/default/templates/runway-demo.html' ]"
act() { # path [curl args...] -> follows the redirect, prints the screen
local p="$1"; shift
# No -X POST: with -L it would also turn the redirect's follow-up GET into a POST. --data-urlencode makes it a POST.
sc -L "$SCREEN$p" --data-urlencode "_csrf=$(sc "$SCREEN" | token)" "$@"
}
act /notes --data-urlencode 'text=An operator note' > "$SCRATCH/screen-note.html"
ck "add a note: flash, listed, stored as a console note" \
"grep -q 'Note added.' '$SCRATCH/screen-note.html' && grep -q 'An operator note' '$SCRATCH/screen-note.html' && grep -q 'An operator note' '$NOTES'"
ck "the owner reads /demo/notes.json (200)" "[ \"\$(sc -o /dev/null -w '%{http_code}' '$BASE/demo/notes.json')\" = 200 ]"
act /install-page > "$SCRATCH/screen-page.html"
ck "install the starter page through SitePages (Advisory site -> published)" \
"grep -q 'Demo page published at /demo.' '$SCRATCH/screen-page.html'"
curl -s "$BASE/demo" > "$SCRATCH/demo-page.html"
ck "/demo serves both widgets inside the site's chrome" \
"grep -q 'rw-demo-notice' '$SCRATCH/demo-page.html' && grep -q 'action=\"/demo/feedback\"' '$SCRATCH/demo-page.html' && grep -q 'name=\"return\" value=\"/demo\"' '$SCRATCH/demo-page.html'"
ck "…and shows a feedback outcome from the query flag" \
"curl -s '$BASE/demo?demo-feedback=thanks' | grep -q 'Thank you'"
act /install-page > "$SCRATCH/screen-page2.html"
ck "a second install changes nothing" "grep -q 'A demo page already exists at /demo; nothing changed.' '$SCRATCH/screen-page2.html'"
ck "the path check: /demo is owned by the published page runway-demo" \
"sc '$SCREEN?path=/demo' | grep -q 'owned by the published page runway-demo'"
ck "the path check: /__admin is reserved" "sc '$SCREEN?path=/__admin' | grep -q 'reserved: no content may live here'"
echo "== the showcase ContentSource, ContentChanges and the SiteEventListener =="
ck "nothing at /demo/showcase before publishing" "[ \"\$(code '$BASE/demo/showcase')\" = 404 ]"
act /showcase --data-urlencode 'text=Showcase <live> text' > "$SCRATCH/screen-show.html"
ck "publish: flash and live block" \
"grep -q 'Showcase published at /demo/showcase.' '$SCRATCH/screen-show.html' && grep -q 'Showcase &lt;live&gt; text' '$SCRATCH/screen-show.html'"
curl -s "$BASE/demo/showcase" > "$SCRATCH/showcase.html"
ck "/demo/showcase serves the escaped text inside the site's chrome" \
"grep -q '<h1 id=\"showcase-title\">Showcase</h1>' '$SCRATCH/showcase.html' && grep -q 'Showcase &lt;live&gt; text' '$SCRATCH/showcase.html'"
ck "the content listing shows the source's entry" "grep -q '<td class=\"rd-cat-source\">runway-demo</td>' '$SCRATCH/screen-show.html'"
ck "the listener saw the CONTENT change with its URL after" \
"grep -A4 '<td class=\"rd-act-item\">runway-demo:showcase</td>' '$SCRATCH/screen-show.html' | grep -q '<td class=\"rd-act-after\">/demo/showcase</td>'"
act /showcase/unpublish > "$SCRATCH/screen-unshow.html"
ck "unpublish: flash, and /demo/showcase is gone at once" \
"grep -q 'Showcase unpublished.' '$SCRATCH/screen-unshow.html' && [ \"\$(code '$BASE/demo/showcase')\" = 404 ]"
ck "the listener saw the removal with the URL before (previousUrls)" \
"grep -A3 '<td class=\"rd-act-item\">runway-demo:showcase</td>' '$SCRATCH/screen-unshow.html' | head -4 | grep -q '<td class=\"rd-act-before\">/demo/showcase</td>'"
echo "== per-site settings: the audit note (onSettingsChanged) and a secret (PluginSettings.secret) =="
SETTINGS="$BASE/__admin/plugins/runway-demo/settings"
BEFORE="$(grep -c 'Per-site settings saved at' "$NOTES" || true)"
sc -o /dev/null -X POST "$SETTINGS" --data-urlencode "notice.enabled=true" --data-urlencode "notice.style=warning" \
--data-urlencode "notice.max-chars=280" --data-urlencode "feedback.enabled=true" \
--data-urlencode "quality.title-warn-ratio=1.0" --data-urlencode "analytics.site-token=verify-token-42" \
--data-urlencode "_csrf=$(sc "$SETTINGS" | token)"
CFG="$SITES/default/plugins/runway-demo.yml"
ck "the save appended one audit note" "[ \"\$(grep -c 'Per-site settings saved at' '$NOTES')\" = \$(( $BEFORE + 1 )) ]"
ck "the secret is stored ENC(...), never in clear" "grep -q 'analytics.site-token: .*ENC(' '$CFG' && ! grep -q verify-token-42 '$CFG'"
sc "$SETTINGS" > "$SCRATCH/settings.html"
ck "the admin fragment reads it back as configured, without the value" \
"grep -q 'Per-site analytics token configured: true' '$SCRATCH/settings.html' && ! grep -q verify-token-42 '$SCRATCH/settings.html'"
ck "…and links the screen for a user who may open it (@authz.may)" "grep -q 'id=\"rd-admin-console\"' '$SCRATCH/settings.html'"
ck "the saved style applies at once" "curl -s '$BASE/demo' | grep -q 'rw-demo-notice-warning'"
echo "== backups: a full backup keeps notes.yml, a transfer copy leaves it out =="
sc -o "$SCRATCH/full.zip" "$BASE/__admin/backups/download"
sc -o "$SCRATCH/transfer.zip" "$BASE/__admin/backups/download-transfer"
zipq() { # zip mode [suffix] -> exit status / prints
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/runway-demo/notes.yml with the notes" \
"zipq '$SCRATCH/full.zip' read plugins/runway-demo/notes.yml | grep -q 'Hello from a visitor'"
ck "the transfer copy has NO plugins/runway-demo/notes.yml" "! zipq '$SCRATCH/transfer.zip' has plugins/runway-demo/notes.yml"
ck "…and its manifest lists the omission" "grep -q 'plugins/runway-demo/notes.yml' '$SCRATCH/transfer-manifest.yml'"
ck "…while the settings file travels with the secret blanked" \
"zipq '$SCRATCH/transfer.zip' has plugins/runway-demo.yml && ! zipq '$SCRATCH/transfer.zip' read plugins/runway-demo.yml | grep -q 'ENC('"
ck "the full backup's manifest omits nothing of the demo" "! grep -q 'plugins/runway-demo/notes.yml' '$SCRATCH/full-manifest.yml'"
echo "== nothing went wrong along the way =="
ck "no WARN/ERROR names the plugin after the run" "! grep -E ' (WARN|ERROR) ' '$LOG' | grep -qiE 'runway-demo|mx.quest.demo'"
ck "no contribution failure was counted" "! grep -qiE 'contribution .*fail|listener .*threw' '$LOG'"
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,137 @@
package mx.quest.demo;
import java.time.Instant;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import mx.quest.runway.spi.model.CatalogChange;
import mx.quest.runway.spi.model.LocalizedUrl;
import mx.quest.runway.spi.model.SettingsChange;
import mx.quest.runway.spi.model.SiteLifecycleEvent;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.service.SiteEventListener;
import mx.quest.runway.spi.service.Sites;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@code SiteEventListener} in the default {@link Phase#CONSUMER CONSUMER} phase — what a plugin that reacts to
* changes it does not own implements (a sitemap, a search index, a change notifier). It replaces listening to the
* host's internal Spring events, whose order against the kernel's caches was never a contract.
*
* <p><b>When each callback is for:</b>
* <ul>
* <li>{@link #onSettingsChanged} — a save of <b>this plugin's own</b> per-site settings (and nothing else);
* {@code PluginSettings.site()} already returns the new values. The demo writes an audit note, as 1.x did —
* but only when {@link SettingsChange#local()} is true: on a cluster every node receives the change (the
* others as a replay, {@code local == false}), and a side effect must happen once, not once per node.</li>
* <li>{@link #onCatalogChanged} — anything that may reshape a site's content surface: a page write ({@code PAGE}),
* a {@code ContentChanges} call ({@code CONTENT}), a lifecycle event ({@code SITE}) or any plugin's settings
* save ({@code SETTINGS}). A {@code PAGE} or {@code CONTENT} change carries the item's URLs <b>before</b>
* ({@code previousUrls}, so a deleted or moved item still names its old address) and <b>after</b>
* ({@code currentUrls}). The demo keeps the last {@value #KEEP} per site in memory and shows them on its
* console screen — an IndexNow-style notifier would submit the union of both lists.</li>
* <li>{@link #onSiteLifecycle} — created, updated, suspended, resumed, deleted, restored. On a <b>wholesale</b>
* event (deleted, restored) drop everything derived from the site's files; here, the recorded activity.</li>
* </ul>
* <b>Guarantees you can rely on:</b> every kernel cache the change affects is already evicted (reads see the new
* state); no host lock is held (calling any service is safe); one throwing callback is logged and counted, never
* propagated. <b>Duty:</b> callbacks run on the writer's thread — evict, record or enqueue; anything slow (a network
* call, an index rebuild) belongs on your own executor. The audit note is one small, bounded file write.
*
* <p>It also shows {@link Sites}: the way code that knows a site only by id — a listener, a background task — gets
* the site's {@link SiteView}, off-request.
*/
public class DemoActivity implements SiteEventListener {
/** How many recent changes are kept per site. */
static final int KEEP = 10;
private static final Logger log = LoggerFactory.getLogger(DemoActivity.class);
/**
* One recorded change, as the console screen shows it.
*
* @param at when this node received it
* @param cause {@code PAGE}, {@code CONTENT}, {@code SITE}, {@code SETTINGS} (lower case)
* @param item {@code <sourceKey>:<id>}, the plugin for a settings change, or {@code ""}
* @param previousUrls the item's paths before the change
* @param currentUrls the item's paths after it
* @param local whether the change happened on this node
*/
public record Entry(Instant at, String cause, String item, List<String> previousUrls, List<String> currentUrls,
boolean local) {
}
private final DemoNotesStore notes;
private final Sites sites;
private final ConcurrentMap<String, Deque<Entry>> recent = new ConcurrentHashMap<>();
public DemoActivity(DemoNotesStore notes, Sites sites) {
this.notes = notes;
this.sites = sites;
}
@Override
public void onSiteLifecycle(SiteLifecycleEvent event) {
String name = sites.find(event.siteId()).map(SiteView::displayName).orElse("(gone)");
log.info("runway-demo saw site '{}' ({}) {}{}", event.siteId(), name, event.kind(),
event.fromBackup() ? " from a backup" : "");
if (event.wholesale()) {
recent.remove(event.siteId());
}
}
@Override
public void onSettingsChanged(SettingsChange change) {
if (!change.local()) {
return; // replayed from another node: that node already wrote the note
}
try {
int count = notes.append(change.siteId(), "Per-site settings saved at " + Instant.now(),
Note.ORIGIN_SYSTEM);
log.info("runway-demo settings changed for site '{}': audit note appended (now {} notes)",
change.siteId(), count);
} catch (RuntimeException e) {
log.warn("runway-demo could not append the settings audit note for site '{}': {}", change.siteId(),
e.toString());
}
}
@Override
public void onCatalogChanged(CatalogChange change) {
String item = switch (change.cause()) {
case PAGE, CONTENT -> (change.sourceKey() == null ? "?" : change.sourceKey()) + ":"
+ (change.id() == null ? "*" : change.id());
case SETTINGS -> change.pluginId() == null ? "" : change.pluginId();
default -> ""; // SITE, and any cause a later SPI adds
};
Entry entry = new Entry(Instant.now(), change.cause().name().toLowerCase(Locale.ROOT), item,
paths(change.previousUrls()), paths(change.currentUrls()), change.local());
Deque<Entry> entries = recent.computeIfAbsent(change.siteId(), id -> new ArrayDeque<>());
synchronized (entries) {
entries.addFirst(entry);
while (entries.size() > KEEP) {
entries.removeLast();
}
}
}
/** The site's recent changes, newest first. */
public List<Entry> recent(String siteId) {
Deque<Entry> entries = recent.get(siteId);
if (entries == null) {
return List.of();
}
synchronized (entries) {
return List.copyOf(entries);
}
}
private static List<String> paths(List<LocalizedUrl> urls) {
return urls.stream().map(LocalizedUrl::path).toList();
}
}
@@ -0,0 +1,98 @@
package mx.quest.demo;
import java.util.List;
import mx.quest.runway.spi.RunwaySpi;
import mx.quest.runway.spi.model.PluginInfo;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.spi.service.SitePages;
import mx.quest.runway.spi.service.Sites;
/**
* Backs the plugin's console fragments — the dashboard card ({@code templates/dashboard.*}) and the admin fragment
* under the settings form ({@code templates/admin.*}). The host does not push data into a fragment; the fragment's
* decoupled logic reads this bean by name, {@code ${@runwayDemoAdminModel.noteCount(tenantSiteId)}}, with
* {@code tenantSiteId} supplied by the console (and {@code null} on the application console, so every accessor is
* null-safe and a fragment never errors).
*
* <p>What a fragment may rely on is a contract: the variables {@code tenantSiteId} and {@code _csrf}, the expressions
* {@code ${@<own bean>…}} and {@code ${@authz.may('…')}}, and {@code #{…}} messages. Nothing else in the console's
* model is promised — so anything else a fragment shows comes from a bean like this one.
*
* <p>It shows three services in their read-only roles: {@link Sites} (a site's view from its id, off-request — the
* fragment only has the id), {@link SitePages#pathOf} (where "our" starter page lives now, whatever its state, even
* after an operator moved it) and {@link PluginSettings#secret} (whether a per-site secret is set — answered without
* ever exposing the value). {@link PluginInfo} is this plugin's identity.
*/
public class DemoAdminModel {
private static final int RECENT = 5;
private final DemoNotesStore notes;
private final DemoAppProps props;
private final PluginSettings settings;
private final Sites sites;
private final SitePages pages;
private final PluginInfo self;
public DemoAdminModel(DemoNotesStore notes, DemoAppProps props, PluginSettings settings, Sites sites,
SitePages pages, PluginInfo self) {
this.notes = notes;
this.props = props;
this.settings = settings;
this.sites = sites;
this.pages = pages;
this.self = self;
}
private static boolean noSite(String siteId) {
return siteId == null || siteId.isBlank();
}
public int noteCount(String siteId) {
return noSite(siteId) ? 0 : notes.count(siteId);
}
/** The newest notes, newest first, for the admin fragment's list. */
public List<Note> recentNotes(String siteId) {
return noSite(siteId) ? List.of() : notes.recent(siteId, RECENT);
}
/** The site's display name, from {@link Sites#find}; the id itself when the site is unknown. */
public String siteName(String siteId) {
return noSite(siteId) ? "" : sites.find(siteId).map(SiteView::displayName).orElse(siteId);
}
/** Where the demo's starter page lives now (any state), or {@code ""} when it is not installed. */
public String demoPagePath(String siteId) {
return noSite(siteId) ? "" : pages.pathOf(siteId, DemoConsoleController.STARTER_SLUG).orElse("");
}
/** Whether the per-site {@code analytics.site-token} secret is set; the value itself never leaves the plugin. */
public boolean siteTokenConfigured(String siteId) {
return !noSite(siteId) && settings.secret(siteId, "analytics.site-token").isPresent();
}
/** This plugin's version, from {@code plugin.yml} (via {@link PluginInfo}). */
public String pluginVersion() {
return self.version();
}
/** The SPI version this plugin was compiled against (a constant the compiler inlined). */
public String builtSpi() {
return RunwaySpi.VERSION;
}
/** The SPI version of the kernel this plugin is running on. */
public String runningSpi() {
return RunwaySpi.runtimeVersion();
}
public boolean bannerEnabled() {
return props.getBanner().isEnabled();
}
public boolean analyticsKeyConfigured() {
return props.getAnalytics().hasKey();
}
}
@@ -0,0 +1,76 @@
package mx.quest.demo;
import java.util.List;
import mx.quest.runway.spi.HeadContributor;
import mx.quest.runway.spi.RunwaySpi;
import mx.quest.runway.spi.model.Capabilities;
import mx.quest.runway.spi.model.HeadContext;
import mx.quest.runway.spi.model.SettingsView;
import mx.quest.runway.spi.service.PluginSettings;
/**
* {@code HeadContributor} — splices markup into every page's {@code <head>} at the response edge, so it lands on every
* page without any edit to a tenant's templates. Ordered {@code @Order(200)} in {@link DemoPluginConfig}, after the
* kernel's own SEO ({@code @Order(100)}) and icon ({@code @Order(90)}) contributors.
*
* <p>Emits an escaped {@code <meta name="generator">} from the app-level {@code generator.label} setting, the plugin's
* stylesheet while the per-site notice is enabled, and — only when the per-site {@code analytics.enabled} flag is on
* and the app-level {@code analytics.write-key} secret is set — an inert analytics {@code <script>} (plain
* {@code <script src>}: the kernel stamps the CSP nonce on it). Returns {@code ""}, never {@code null}, when it has
* nothing to add.
*
* <p><b>{@code PluginSettings}</b> is how a plugin reads its own per-site settings: {@code site(siteId)} returns a
* {@link SettingsView} with the {@code siteSettings:} defaults already applied and the saved values over them, so the
* code fallback only matters for undeclared keys. It is bound to this plugin by the jar it was injected into.
*/
public class DemoAnalyticsHead implements HeadContributor {
private final DemoAppProps props;
private final PluginSettings settings;
public DemoAnalyticsHead(DemoAppProps props, PluginSettings settings) {
this.props = props;
this.settings = settings;
}
@Override
public String key() {
return "runway-demo/analytics";
}
@Override
public String render(HeadContext ctx) {
SettingsView site = settings.site(ctx.site().id());
StringBuilder out = new StringBuilder();
// A provenance comment: the SPI this plugin was built against (a constant), and an input the host hands in.
out.append("\n<!-- runway-demo ").append(Html.escape(RunwaySpi.VERSION))
.append(ctx.noindex() ? " (noindex)" : "").append(" -->");
out.append("\n<meta name=\"generator\" content=\"").append(Html.escape(props.getGenerator().getLabel()))
.append("\">");
if (site.bool("notice.enabled", true)) {
// The plugin's own stylesheet, from its static-asset namespace, so the widgets are styled.
out.append("\n<link rel=\"stylesheet\" href=\"/__plugin/runway-demo/static/css/demo.css\">");
}
if (site.bool("analytics.enabled", false) && props.getAnalytics().hasKey()) {
// Inert placeholder — a real plugin would emit its vendor's snippet here. No key goes into the page.
out.append("\n<script data-demo-analytics=\"1\" src=\"/__plugin/runway-demo/static/js/demo-analytics.js\"")
.append(" data-site=\"").append(Html.escape(ctx.site().id())).append("\" defer></script>");
}
return out.toString();
}
@Override
public Capabilities capabilities() {
return Capabilities.of("head.per-locale");
}
/**
* This contributor's whole per-site input: its own settings file. Head markup is spliced in after a page's
* {@code ETag} has been computed, so the host folds the files listed here into the validator — without it, a
* settings change would alter the delivered page but not its {@code ETag}, and clients would keep the old head.
*/
@Override
public List<String> headInputs(String siteId) {
return List.of("plugins/runway-demo.yml");
}
}
@@ -0,0 +1,112 @@
package mx.quest.demo;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
/**
* The demo's <b>app-level</b> settings, bound from {@code external/plugin-settings/runway-demo.yml} (keys under
* {@code runway.plugin.runway-demo.*}) — the plugin.yml {@code settings:} schema. App-level settings are PLATFORM
* concerns and apply on <b>restart</b>; a plugin reads them through its own Spring {@code @ConfigurationProperties}
* binding (descriptor contract), never through host machinery. Field defaults mirror the schema defaults so the
* plugin behaves sensibly when the file is absent.
*
* <p>Registered by the {@code @Bean @ConfigurationProperties("runway.plugin.runway-demo")} method
* {@code DemoPluginConfig#runwayDemoAppProps}, <b>not</b> by {@code @EnableConfigurationProperties}: that annotation
* names the bean {@code "<prefix>-<class name>"}, which breaks the kernel's rule that every plugin bean name starts
* with the plugin id ({@code runwayDemo…}).
*
* <p>The {@code analytics.write-key} is a {@code secret}-typed <i>app-level</i> setting: in the property map it is the
* {@code ENC(...)} ciphertext the host stores, so this demo uses it as presence only. (A <i>per-site</i> secret is
* read in clear with {@code PluginSettings.secret} — see {@link DemoAdminModel#siteTokenConfigured}.)
*/
public class DemoAppProps {
@NestedConfigurationProperty
private final Banner banner = new Banner();
@NestedConfigurationProperty
private final Cache cache = new Cache();
@NestedConfigurationProperty
private final Generator generator = new Generator();
@NestedConfigurationProperty
private final Analytics analytics = new Analytics();
public Banner getBanner() {
return banner;
}
public Cache getCache() {
return cache;
}
public Generator getGenerator() {
return generator;
}
public Analytics getAnalytics() {
return analytics;
}
/** {@code banner.enabled} / {@code banner.text} — a site-wide chrome banner (text is verbatim/multi-line). */
public static class Banner {
private boolean enabled = true;
private String text = "";
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = (text == null) ? "" : text;
}
}
/** {@code cache.max-entries} — a platform tuning knob (int, range-checked by the console form). */
public static class Cache {
private int maxEntries = 500;
public int getMaxEntries() {
return maxEntries;
}
public void setMaxEntries(int maxEntries) {
this.maxEntries = maxEntries;
}
}
/** {@code generator.label} — the value emitted in the {@code <meta name="generator">} head tag. */
public static class Generator {
private String label = "Runway Demo";
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = (label == null || label.isBlank()) ? "Runway Demo" : label;
}
}
/** {@code analytics.write-key} — a {@code secret}; opaque ENC(...) ciphertext in the property map. */
public static class Analytics {
private String writeKey = "";
public String getWriteKey() {
return writeKey;
}
public void setWriteKey(String writeKey) {
this.writeKey = (writeKey == null) ? "" : writeKey;
}
public boolean hasKey() {
return !writeKey.isBlank();
}
}
}
@@ -0,0 +1,309 @@
package mx.quest.demo;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import mx.quest.runway.spi.RunwaySpi;
import mx.quest.runway.spi.model.CatalogEntry;
import mx.quest.runway.spi.model.Finding;
import mx.quest.runway.spi.model.InstallResult;
import mx.quest.runway.spi.model.PluginInfo;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.model.StarterPage;
import mx.quest.runway.spi.service.AccessCheck;
import mx.quest.runway.spi.service.ConsoleScreen;
import mx.quest.runway.spi.service.ContentCatalogView;
import mx.quest.runway.spi.service.Messages;
import mx.quest.runway.spi.service.RequestContext;
import mx.quest.runway.spi.service.SitePages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
/**
* The demo's own screen inside the tenant console, {@value #BASE} — a {@code @Controller} annotated
* {@link ConsoleScreen}. <b>When to use {@code @ConsoleScreen}:</b> whenever a plugin needs more than the settings form
* and the admin fragment below it — a list to manage, an action to run. The kernel fills the console shell (topbar,
* menus, language switcher, footer) for every request this class handles, so the plugin needs no
* {@code @ControllerAdvice} and no host class. A handler sets {@link ConsoleScreen#CONTENT_TEMPLATE} and
* {@link ConsoleScreen#PAGE_TITLE_KEY} and returns {@link ConsoleScreen#LAYOUT_VIEW}.
*
* <p><b>The rules this class follows:</b>
* <ul>
* <li>Every mapping lies under {@code /__admin/runway-demo} (the kernel refuses a plugin controller elsewhere), so
* the tenant console's sign-in, realm security and CSRF protection apply unchanged.</li>
* <li>Every handler is gated with {@code @PreAuthorize("@authz.may('runway-demo|manage-notes')")} — the
* {@link AccessCheck} bean under its expression name. The menu entry's {@code permission:} only hides the
* link.</li>
* <li>Everything that <b>changes state is a {@code POST}</b> from a form carrying the console's CSRF token
* ({@code ${_csrf}}); the {@code GET} only reads, so a link or an {@code <img>} on another web site can never
* trigger an action through a signed-in operator's browser. Each {@code POST} redirects back (post/redirect/get)
* with a flash message, so a reload never repeats it. Spring MVC binds the form fields, so no SPI type is
* needed to read them.</li>
* </ul>
*
* <p>It is also where four services are used in their natural place:
* <ul>
* <li>{@link RequestContext#site()} — <b>which site this console request manages</b>. A console screen has no
* {@code RouteRequest}; this is how it learns the tenancy. It is empty on the application console
* ({@code /__app}), which this screen does not serve (404).</li>
* <li>{@link Messages#console} — console text in the <b>operator's</b> UI language (the flash messages), as opposed
* to {@link Messages#site}, which is for what a site's visitors read.</li>
* <li>{@link SitePages#install} — "install my starter page" through the site's editorial rules: never overwrites,
* never publishes around an Enforced or Reviewed site, and reports one of four outcomes the operator is told in
* words. The plugin checks the caller may edit pages first ({@link AccessCheck#may} with the kernel permission
* {@code EDIT_PAGES}).</li>
* <li>{@link ContentCatalogView} — <b>the site's published content surface</b> with the URLs the host computed:
* {@code entries} (what a sitemap or search index lists), {@code pageAt} (which published page owns a path),
* {@code servablePath} (may content live at a path at all) and {@code refresh} (a manual reindex).</li>
* </ul>
*/
@Controller
@ConsoleScreen
@RequestMapping(DemoConsoleController.BASE)
public class DemoConsoleController {
static final String BASE = "/__admin/runway-demo";
static final String GATE = "@authz.may('runway-demo|manage-notes')";
static final String CONTENT = "__plugin__/runway-demo/console";
static final String TITLE_KEY = "runwaydemo.console.title";
/** The starter page's slug and path. */
static final String STARTER_SLUG = "runway-demo";
static final String STARTER_PATH = "/demo";
/** The flash attributes this screen renders itself (the shell's own flash region is not promised to plugins). */
static final String FLASH = "runwayDemoFlash";
static final String FLASH_ERROR = "runwayDemoError";
/** The most catalog rows the screen lists. */
static final int CATALOG_ROWS = 50;
private static final Logger log = LoggerFactory.getLogger(DemoConsoleController.class);
/** One row of the content-surface table. */
public record CatalogRow(String source, String id, String path, boolean own) {
}
/** The answer of the path check: servable at all, and the published page that owns it, if any. */
public record PathCheck(String path, boolean safe, boolean servable, String ownerSlug) {
}
/** Everything the screen shows, built per request. */
public record Screen(SiteView site, String pluginVersion, String builtSpi, String runningSpi,
int noteCount, List<Note> notes, String showcaseText, String showcasePath,
String starterPath, int catalogTotal, List<CatalogRow> catalog,
List<DemoActivity.Entry> activity, PathCheck pathCheck) {
}
private final RequestContext request;
private final AccessCheck access;
private final Messages messages;
private final SitePages pages;
private final ContentCatalogView catalog;
private final DemoNotesStore notes;
private final DemoShowcaseStore showcase;
private final DemoActivity activity;
private final PluginInfo self;
public DemoConsoleController(RequestContext request, AccessCheck access, Messages messages, SitePages pages,
ContentCatalogView catalog, DemoNotesStore notes, DemoShowcaseStore showcase,
DemoActivity activity, PluginInfo self) {
this.request = request;
this.access = access;
this.messages = messages;
this.pages = pages;
this.catalog = catalog;
this.notes = notes;
this.showcase = showcase;
this.activity = activity;
this.self = self;
}
/** The screen. Read-only: it changes nothing, so it is a {@code GET}. {@code ?path=} runs the path check. */
@GetMapping
@PreAuthorize(GATE)
public String screen(@RequestParam(name = "path", required = false) String path, Model model) {
SiteView site = boundSite();
String siteId = site.id();
List<CatalogEntry> entries = catalog.entries(siteId);
List<CatalogRow> rows = new ArrayList<>();
for (CatalogEntry entry : entries.subList(0, Math.min(CATALOG_ROWS, entries.size()))) {
rows.add(new CatalogRow(entry.sourceKey(), entry.ref().id(), entry.pathFor(site.defaultLocale()),
DemoShowcaseSource.SOURCE_KEY.equals(entry.sourceKey())));
}
Optional<Showcase> current = showcase.current(siteId);
model.addAttribute("rd", new Screen(site, self.version(), RunwaySpi.VERSION,
RunwaySpi.runtimeVersion(), notes.count(siteId), notes.recent(siteId, 10),
current.map(Showcase::text).orElse(null), DemoShowcaseSource.PATH,
pages.pathOf(siteId, STARTER_SLUG).orElse(""), entries.size(), rows, activity.recent(siteId),
path == null || path.isBlank() ? null : check(site, path.strip())));
model.addAttribute(ConsoleScreen.CONTENT_TEMPLATE, CONTENT);
model.addAttribute(ConsoleScreen.PAGE_TITLE_KEY, TITLE_KEY);
return ConsoleScreen.LAYOUT_VIEW;
}
private PathCheck check(SiteView site, String path) {
try {
boolean servable = catalog.servablePath(site.id(), path);
String owner = catalog.pageAt(site.id(), path, site.defaultLocale()).orElse(null);
return new PathCheck(path, true, servable, owner);
} catch (IllegalArgumentException unsafe) {
return new PathCheck(path, false, false, null);
}
}
/** Adds an operator note (a field of the form body). */
@PostMapping("/notes")
@PreAuthorize(GATE)
public String addNote(@RequestParam(name = "text", defaultValue = "") String text, RedirectAttributes flash) {
String siteId = boundSite().id();
if (text.isBlank()) {
return back(flash, FLASH_ERROR, console("runwaydemo.console.note.blank", "Write something first."));
}
try {
notes.append(siteId, text, Note.ORIGIN_CONSOLE);
} catch (UncheckedIOException e) {
log.warn("runway-demo could not add a note for site {}: {}", siteId, e.toString());
return back(flash, FLASH_ERROR, console("runwaydemo.console.ioError", "The change could not be saved."));
}
return back(flash, FLASH, console("runwaydemo.console.note.added", "Note added."));
}
/** Publishes the showcase page; the store announces the change with {@code ContentChanges}. */
@PostMapping("/showcase")
@PreAuthorize(GATE)
public String publishShowcase(@RequestParam(name = "text", defaultValue = "") String text,
RedirectAttributes flash) {
String siteId = boundSite().id();
if (text.isBlank()) {
return back(flash, FLASH_ERROR, console("runwaydemo.console.showcase.blank", "Write something first."));
}
try {
showcase.publish(siteId, text);
} catch (UncheckedIOException e) {
log.warn("runway-demo could not publish the showcase of site {}: {}", siteId, e.toString());
return back(flash, FLASH_ERROR, console("runwaydemo.console.ioError", "The change could not be saved."));
}
return back(flash, FLASH, console("runwaydemo.console.showcase.published", "Showcase published at {0}.",
DemoShowcaseSource.PATH));
}
/** Unpublishes the showcase page; announced like a publish. */
@PostMapping("/showcase/unpublish")
@PreAuthorize(GATE)
public String unpublishShowcase(RedirectAttributes flash) {
String siteId = boundSite().id();
boolean was;
try {
was = showcase.unpublish(siteId);
} catch (UncheckedIOException e) {
log.warn("runway-demo could not unpublish the showcase of site {}: {}", siteId, e.toString());
return back(flash, FLASH_ERROR, console("runwaydemo.console.ioError", "The change could not be saved."));
}
return was
? back(flash, FLASH, console("runwaydemo.console.showcase.unpublished", "Showcase unpublished."))
: back(flash, FLASH, console("runwaydemo.console.showcase.none", "No showcase was published."));
}
/** Installs the starter page carrying the demo's two widgets, through the site's editorial rules. */
@PostMapping("/install-page")
@PreAuthorize(GATE)
public String installPage(RedirectAttributes flash) {
SiteView site = boundSite();
if (!access.may("EDIT_PAGES")) {
return back(flash, FLASH_ERROR, console("runwaydemo.console.page.forbidden",
"Installing a page needs the permission to edit pages."));
}
String title = messages.site(site.id(), site.defaultLocale(), "runwaydemo.page.title", "Runway demo");
StarterPage page = new StarterPage(STARTER_SLUG, STARTER_PATH,
Map.of(site.defaultLocale().getLanguage(), title), starterHtml(title), starterLogic(), true);
InstallResult result;
try {
result = pages.install(site.id(), page);
} catch (RuntimeException e) {
// IllegalStateException: another page serves the path, the master is missing, a write failed (no stray
// draft is left behind). IllegalArgumentException would mean our own slug/path is unsafe — a bug here.
log.warn("runway-demo starter page install failed for site {}: {}", site.id(), e.toString());
return back(flash, FLASH_ERROR, console("runwaydemo.console.page.failed",
"The demo page could not be installed."));
}
return back(flash, FLASH, describe(result));
}
/** Drops the site's cached content listing — the "reindex" button; ordinary changes never need it. */
@PostMapping("/catalog/refresh")
@PreAuthorize(GATE)
public String refreshCatalog(RedirectAttributes flash) {
catalog.refresh(boundSite().id());
return back(flash, FLASH, console("runwaydemo.console.catalog.refreshed", "Content listing refreshed."));
}
/** The operator's words for each install outcome; an outcome added in a later SPI MINOR gets a neutral line. */
String describe(InstallResult result) {
String path = result.path();
return switch (result.outcome()) {
case PUBLISHED -> console("runwaydemo.console.page.published", "Demo page published at {0}.", path);
case PENDING_REVIEW -> console("runwaydemo.console.page.pending",
"Demo page created at {0} and waiting in the review queue.", path);
case DRAFT_BLOCKED -> {
StringBuilder text = new StringBuilder(console("runwaydemo.console.page.blocked",
"Demo page created at {0} as a draft: the quality checks blocked publishing.", path));
for (Finding finding : result.blocking()) {
text.append(' ').append(finding.code()).append(": ").append(finding.message());
}
yield text.toString();
}
case ALREADY_EXISTS -> console("runwaydemo.console.page.exists",
"A demo page already exists at {0}; nothing changed.", path);
default -> console("runwaydemo.console.page.other", "Demo page install finished: {0} {1}",
result.outcome(), path);
};
}
/** The site this console request manages; 404 when there is none (the application console). */
private SiteView boundSite() {
return request.site().orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
}
private String console(String code, String fallback, Object... args) {
return messages.console(code, fallback, args);
}
private static String back(RedirectAttributes flash, String kind, String text) {
flash.addFlashAttribute(kind, text);
return "redirect:" + BASE;
}
/**
* The starter page: the master's chrome seams, a heading, and the two widget anchors (an {@code id} and a
* {@code data-widget} on one element each). An {@code <h1>} keeps the page clear of the demo's own quality check.
*/
static String starterHtml(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=\"demo-page-title\">" + t + "</h1>\n"
+ " <div id=\"demo-notice\" data-widget=\"demo-notice/page\"></div>\n"
+ " <div id=\"demo-feedback\" data-widget=\"demo-feedback/page\"></div>\n"
+ "</main>\n<footer id=\"site-footer\"></footer>\n</body>\n</html>\n";
}
/** The starter page's decoupled logic: the master's chrome by the {@code ${master}} variable, never a literal. */
static String starterLogic() {
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=\"#demo-page-title\" th:text=\"${pageTitle}\"/>\n"
+ "</thlogic>\n";
}
}
@@ -0,0 +1,233 @@
package mx.quest.demo;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.function.LongSupplier;
import mx.quest.runway.spi.EndpointContributor;
import mx.quest.runway.spi.model.Capabilities;
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.SurfacePosture;
import mx.quest.runway.spi.service.AccessCheck;
import mx.quest.runway.spi.service.Messages;
import mx.quest.runway.spi.service.PluginSettings;
import tools.jackson.databind.json.JsonMapper;
/**
* {@code EndpointContributor} — plugin HTTP routes on a site's public host, without touching a servlet. The frozen
* {@link RouteRequest} carries the resolved site, the negotiated locale, the query, the form body, lowercase headers,
* the gated client IP and the request origin; each route declares a {@link SurfacePosture}. Routes are exact paths
* on the tenant realm and must avoid the reserved kernel prefixes ({@code /__…}, {@code /login}, …).
*
* <ul>
* <li>{@code GET /demo/hello.txt} — public, {@code discoverable()}: a greeting localized with
* {@link Messages#site} in the request's negotiated locale.</li>
* <li>{@code GET /demo/echo.json} — public: echoes what the host put in the {@code RouteRequest}.</li>
* <li>{@code GET /demo/notes.json} — <b>permission-gated</b> with {@link AccessCheck}: only a signed-in user holding
* {@code runway-demo|manage-notes} gets the notes; anyone else gets {@code 403}. <b>When to use
* {@code AccessCheck}:</b> every time your code must decide whether the current user may do something — the
* menu and dashboard-card {@code permission:} keys only hide UI. It is fail-closed (no request, no principal,
* an undeclared key → {@code false}) and is the same bean as {@code @authz} in {@code @PreAuthorize} and
* templates.</li>
* <li>{@code POST /demo/feedback} — an <b>anonymous form route</b> ({@link Route#anonymousPost}): the public
* feedback form of {@link DemoFeedbackWidget} posts here with <b>no CSRF token</b>. <b>When to use the
* anonymous flag:</b> only for a form any visitor may submit with no account, placed on a page every visitor
* shares, which therefore cannot carry a per-session token (a contact form, a newsletter sign-up). The kernel
* exempts exactly this method and path from CSRF and makes that safe by running the handler with <b>no
* principal</b> ({@code AccessCheck.may} is {@code false} even for a signed-in administrator) and accepting only
* an {@code application/x-www-form-urlencoded} body. Keep your own abuse guards: here a honeypot field, a length
* cap and a per-address rate limit keyed by {@link RouteRequest#clientIp()} (the address after the kernel's
* trusted-proxy gate — never a header). Never use the flag for an action on something a signed-in user owns;
* those are CSRF-checked {@code POST}s (the demo's console screen, {@link DemoConsoleController}).</li>
* </ul>
*/
public class DemoEndpoints implements EndpointContributor {
static final String HELLO_PATH = "/demo/hello.txt";
static final String ECHO_PATH = "/demo/echo.json";
static final String NOTES_PATH = "/demo/notes.json";
static final String FEEDBACK_PATH = "/demo/feedback";
static final String PERMISSION = "runway-demo|manage-notes";
/** Feedback messages one client address may send per {@link #WINDOW_MILLIS}. */
static final int FEEDBACK_PER_WINDOW = 5;
static final long WINDOW_MILLIS = TimeUnit.MINUTES.toMillis(1);
/** Above this many tracked addresses, stale ones are swept (bounds the limiter's memory). */
private static final int MAX_TRACKED = 10_000;
private final AccessCheck access;
private final DemoNotesStore notes;
private final Messages messages;
private final PluginSettings settings;
private final LongSupplier clockMillis;
private final JsonMapper json = JsonMapper.builder().build();
private final ConcurrentMap<String, Deque<Long>> recentFeedback = new ConcurrentHashMap<>();
public DemoEndpoints(AccessCheck access, DemoNotesStore notes, Messages messages, PluginSettings settings) {
this(access, notes, messages, settings, System::currentTimeMillis);
}
DemoEndpoints(AccessCheck access, DemoNotesStore notes, Messages messages, PluginSettings settings,
LongSupplier clockMillis) {
this.access = access;
this.notes = notes;
this.messages = messages;
this.settings = settings;
this.clockMillis = clockMillis;
}
@Override
public String key() {
return "runway-demo/endpoints";
}
@Override
public List<Route> routes() {
return List.of(
new Route("GET", HELLO_PATH, Realm.TENANT, SurfacePosture.discoverable()),
new Route("GET", ECHO_PATH, Realm.TENANT, SurfacePosture.safeDefault()),
new Route("GET", NOTES_PATH, Realm.TENANT, SurfacePosture.safeDefault()),
Route.anonymousPost(FEEDBACK_PATH, SurfacePosture.safeDefault()));
}
@Override
public RouteResponse handle(RouteRequest req) {
// The kernel dispatches by method + path; checking the method again is the second line of defence.
return switch (req.method().toUpperCase(Locale.ROOT) + " " + req.path()) {
case "GET " + HELLO_PATH -> hello(req);
case "GET " + ECHO_PATH -> echo(req);
case "GET " + NOTES_PATH -> notes(req);
case "POST " + FEEDBACK_PATH -> feedback(req);
default -> RouteResponse.notFound();
};
}
private RouteResponse hello(RouteRequest req) {
String greeting = messages.site(req.site().id(), req.locale(), "runwaydemo.hello",
"Hello from the runway-demo plugin!") + "\n"
+ "site: " + req.site().displayName() + " (" + req.site().id() + ")\n"
+ "locale: " + req.locale().toLanguageTag() + "\n"
+ "baseUrl: " + (req.site().baseUrl() == null ? "(derived)" : req.site().baseUrl()) + "\n"
+ "origin: " + (req.origin().isEmpty() ? "(unknown)" : req.origin()) + "\n";
return RouteResponse.text(200, greeting);
}
private RouteResponse echo(RouteRequest req) {
Map<String, Object> payload = new LinkedHashMap<>();
payload.put("method", req.method());
payload.put("path", req.path());
payload.put("site", req.site().id());
payload.put("locale", req.locale().toLanguageTag()); // negotiated: ?lang → cookie → Accept-Language → default
payload.put("query", req.query()); // the URL query string only
payload.put("form", req.form()); // a url-encoded body's fields (empty on a GET)
payload.put("param.q", req.param("q").orElse(null)); // query first, then form
payload.put("headers", req.headers()); // lowercase names; no X-Forwarded-* ever
payload.put("clientIp", req.clientIp()); // after the trusted-proxy gate; null when unknown
payload.put("origin", req.origin()); // scheme://host[:port]; "" when unknown
return jsonResponse(200, payload);
}
private RouteResponse notes(RouteRequest req) {
if (!access.may(PERMISSION)) {
return RouteResponse.text(403, "Forbidden — requires the runway-demo \"manage-notes\" permission.\n");
}
List<Note> siteNotes = notes.list(req.site().id());
Map<String, Object> payload = new LinkedHashMap<>();
payload.put("site", req.site().id());
payload.put("count", siteNotes.size());
payload.put("notes", siteNotes);
return jsonResponse(200, payload);
}
/**
* Keeps a visitor's message as a note, then answers {@code 303} back to the form's page with an outcome flag
* (never a submitted value). Fields are read from the form <b>body</b> only, so personal text never has to
* travel in a URL. A failure to store propagates: the kernel answers {@code 500}, logs and counts it.
*/
private RouteResponse feedback(RouteRequest req) {
String siteId = req.site().id();
if (!settings.site(siteId).bool("feedback.enabled", true)) {
return RouteResponse.notFound();
}
String back = safeLocalPath(formField(req, "return"));
if (!formField(req, "website").isEmpty()) {
return redirect(back, "thanks"); // a bot filled the honeypot: pretend success, keep nothing
}
String message = formField(req, "message");
if (message.isEmpty()) {
return redirect(back, "invalid");
}
if (!allow(req.clientIp())) {
return redirect(back, "limited");
}
notes.append(siteId, message, Note.ORIGIN_VISITOR);
return redirect(back, "thanks");
}
/** A sliding-window limit per gated client address; an unknown address shares one bucket (fail-safe). */
boolean allow(String clientIp) {
long now = clockMillis.getAsLong();
if (recentFeedback.size() > MAX_TRACKED) {
recentFeedback.entrySet().removeIf(e -> {
synchronized (e.getValue()) {
return e.getValue().isEmpty() || now - e.getValue().peekLast() >= WINDOW_MILLIS;
}
});
}
Deque<Long> times = recentFeedback.computeIfAbsent(clientIp == null ? "unknown" : clientIp,
k -> new ArrayDeque<>());
synchronized (times) {
while (!times.isEmpty() && now - times.peekFirst() >= WINDOW_MILLIS) {
times.pollFirst();
}
if (times.size() >= FEEDBACK_PER_WINDOW) {
return false;
}
times.addLast(now);
return true;
}
}
private static String formField(RouteRequest req, String name) {
List<String> values = req.form().get(name);
return values == null || values.isEmpty() ? "" : values.get(0).strip();
}
/** A same-origin local path (one leading "/", no scheme, backslash, whitespace or control character), else "/". */
static String safeLocalPath(String path) {
if (path == null || !path.startsWith("/") || path.startsWith("//") || path.contains("://")) {
return "/";
}
for (int i = 0; i < path.length(); i++) {
char c = path.charAt(i);
if (c <= 0x20 || c == '\\' || c == 0x7f) {
return "/";
}
}
return path;
}
private static RouteResponse redirect(String path, String outcome) {
String location = path + (path.contains("?") ? "&" : "?") + DemoFeedbackWidget.OUTCOME_PARAM + "=" + outcome;
return new RouteResponse(303, Map.of("Location", location), new byte[0]);
}
private RouteResponse jsonResponse(int status, Object payload) {
byte[] body = json.writeValueAsString(payload).getBytes(StandardCharsets.UTF_8);
return new RouteResponse(status, Map.of("Content-Type", "application/json; charset=utf-8"), body);
}
@Override
public Capabilities capabilities() {
return Capabilities.of("endpoint.tenant", "endpoint.json", "endpoint.anonymous-form");
}
}
@@ -0,0 +1,98 @@
package mx.quest.demo;
import java.util.Locale;
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;
/**
* {@code ContentWidget} — a public "leave a message" form at a {@code data-widget="demo-feedback/<instance>"} anchor.
* It posts to the demo's <b>anonymous</b> route {@code POST /demo/feedback} ({@link DemoEndpoints}), which stores the
* message as a note and answers {@code 303} back to this page with a {@code ?demo-feedback=<outcome>} flag; the widget
* reads that flag from {@link WidgetView#query()} and shows the outcome (post/redirect/get, so a reload never
* resubmits).
*
* <p>The form carries <b>no CSRF token</b> on purpose: it sits on a page every visitor shares (and caches), and an
* anonymous visitor has no session. That is exactly the case the anonymous-route flag exists for — see
* {@link DemoEndpoints}. Its abuse guards are a honeypot field (hidden from people, filled by naive bots), a length
* cap and a per-address rate limit on the server.
*
* <p>A widget stays a pure function of its view: it only <i>reads</i> the query; storing the message is the
* endpoint's job. All text comes from {@link Messages#site} in the visitor's locale and is escaped here.
*/
public class DemoFeedbackWidget implements ContentWidget {
/** The query flag the endpoint redirects back with. */
static final String OUTCOME_PARAM = "demo-feedback";
private final PluginSettings settings;
private final Messages messages;
public DemoFeedbackWidget(PluginSettings settings, Messages messages) {
this.settings = settings;
this.messages = messages;
}
@Override
public String key() {
return "demo-feedback";
}
@Override
public RenderFragment render(WidgetView view) {
String siteId = view.site().id();
if (!settings.site(siteId).bool("feedback.enabled", true)) {
return RenderFragment.empty();
}
Locale locale = view.locale();
String fieldId = "rw-demo-feedback-" + view.instanceId().replaceAll("[^A-Za-z0-9_-]", "-");
String back = view.path().isBlank() ? "/" : view.path();
StringBuilder html = new StringBuilder()
.append("<link rel=\"stylesheet\" href=\"/__plugin/runway-demo/static/css/demo.css\">")
.append("<div class=\"rw-demo-feedback\">");
String outcome = outcomeText(siteId, locale, view.query().get(OUTCOME_PARAM));
if (!outcome.isEmpty()) {
html.append("<p class=\"rw-demo-notice rw-demo-notice-info\" role=\"status\">")
.append(Html.escape(outcome)).append("</p>");
}
html.append("<form method=\"post\" action=\"").append(DemoEndpoints.FEEDBACK_PATH).append("\">")
.append("<input type=\"hidden\" name=\"return\" value=\"").append(Html.escape(back)).append("\">")
.append("<label for=\"").append(fieldId).append("\">")
.append(Html.escape(text(siteId, locale, "runwaydemo.feedback.label", "Leave a message")))
.append("</label>")
.append("<textarea id=\"").append(fieldId).append("\" name=\"message\" rows=\"3\" maxlength=\"")
.append(DemoNotesStore.MAX_TEXT).append("\" required></textarea>")
// The honeypot: off-screen for people and assistive technology, tempting for a form-filling bot.
.append("<div class=\"rw-demo-hp\" aria-hidden=\"true\"><label>Website <input type=\"text\" ")
.append("name=\"website\" tabindex=\"-1\" autocomplete=\"off\"></label></div>")
.append("<button type=\"submit\">")
.append(Html.escape(text(siteId, locale, "runwaydemo.feedback.send", "Send")))
.append("</button></form></div>");
return RenderFragment.of(html.toString());
}
private String outcomeText(String siteId, Locale locale, String outcome) {
if (outcome == null) {
return "";
}
return switch (outcome) {
case "thanks" -> text(siteId, locale, "runwaydemo.feedback.thanks", "Thank you — your message was kept.");
case "invalid" -> text(siteId, locale, "runwaydemo.feedback.invalid", "Please write a message first.");
case "limited" -> text(siteId, locale, "runwaydemo.feedback.limited",
"Too many messages from your address — please try again in a minute.");
default -> "";
};
}
private String text(String siteId, Locale locale, String code, String fallback) {
return messages.site(siteId, locale, code, fallback);
}
@Override
public Capabilities capabilities() {
return Capabilities.of("widget.form");
}
}
@@ -0,0 +1,44 @@
package mx.quest.demo;
import mx.quest.runway.spi.RunwaySpi;
import mx.quest.runway.spi.model.PluginInfo;
import mx.quest.runway.spi.service.PluginLifecycle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@code PluginLifecycle} — the optional start/stop hook. <b>When to use it:</b> to run code once the platform is up
* (warm a cache, open an index, start your own executor) or when it shuts down (close what you opened). A plugin that
* only contributes beans needs none.
*
* <p>The host collects every {@code PluginLifecycle} bean by type and matches it to its plugin by the jar its class was
* loaded from — there is no {@code id()} to keep in sync with {@code plugin.yml}. {@link #started} runs once, after
* every singleton exists, in plugin load order; {@link #stopping} runs at shutdown in reverse order, only if
* {@code started} returned normally. Both block the host's startup/shutdown thread, so keep them short; a throw is
* logged and counted on the plugins screen and the platform keeps booting.
*
* <p>{@link PluginInfo} is this plugin's own identity — its id, the version from {@code plugin.yml} and its install
* folder. It arrives here and can also be injected into any bean.
*
* <p>{@link RunwaySpi#VERSION} is a compile-time constant, so in plugin code it is the SPI version the plugin was
* <b>built against</b>; {@link RunwaySpi#runtimeVersion()} is the SPI of the kernel it is <b>running on</b>.
*/
public class DemoLifecycle implements PluginLifecycle {
private static final Logger log = LoggerFactory.getLogger(DemoLifecycle.class);
private volatile PluginInfo self;
@Override
public void started(PluginInfo self) {
this.self = self;
log.info("{} {} started — install dir {}; built against SPI {}, running on SPI {}", self.id(),
self.version(), self.installDir(), RunwaySpi.VERSION, RunwaySpi.runtimeVersion());
}
@Override
public void stopping() {
PluginInfo info = self;
log.info("{} stopping", info == null ? "runway-demo" : info.id());
}
}
@@ -0,0 +1,70 @@
package mx.quest.demo;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import mx.quest.runway.spi.PageQualityCheck;
import mx.quest.runway.spi.model.Capabilities;
import mx.quest.runway.spi.model.Finding;
import mx.quest.runway.spi.model.PageView;
import mx.quest.runway.spi.model.SettingsView;
import mx.quest.runway.spi.service.PluginSettings;
/**
* {@code PageQualityCheck} — read-only SEO checks over a page as it would render. Tuned per site through
* {@link PluginSettings}: {@code quality.title-warn-ratio} (a {@code decimal}) scales the 60-character title threshold;
* {@code quality.ignore-codes} (a {@code list}) suppresses finding codes. Returns an empty list (never {@code null})
* for a clean page.
*
* <p>Severity is a decision with consequences: on a site set to <i>Enforced</i> or <i>Reviewed</i> any {@code ERROR}
* refuses publishing. This demo's {@code h1.missing} is an {@code ERROR} on purpose, to show that path; a real plugin
* keeps {@code ERROR} for something clearly broken and uses {@code WARNING} for advice.
*/
public class DemoMetaLengthCheck implements PageQualityCheck {
private static final int BASE_TITLE_LIMIT = 60;
private final PluginSettings settings;
public DemoMetaLengthCheck(PluginSettings settings) {
this.settings = settings;
}
@Override
public String key() {
return "runway-demo/meta-length";
}
@Override
public List<Finding> inspect(PageView page) {
SettingsView site = settings.site(page.site().id());
double ratio = site.decimal("quality.title-warn-ratio", BigDecimal.ONE).doubleValue();
int titleLimit = (int) Math.max(1, Math.round(BASE_TITLE_LIMIT * ratio));
List<String> ignore = site.list("quality.ignore-codes");
List<Finding> findings = new ArrayList<>();
String title = page.page().title();
if (title != null && title.length() > titleLimit) {
findings.add(Finding.warning("title.too-long",
"Title is " + title.length() + " chars; keep it under " + titleLimit + " for search results."));
}
if (page.page().description() == null || page.page().description().isBlank()) {
findings.add(Finding.info("description.missing",
"This page has no meta description; add one for better search snippets."));
}
if (!hasH1(page.resolvedHtml())) {
findings.add(Finding.error("h1.missing", "The rendered page has no <h1> heading."));
}
return findings.stream().filter(f -> !ignore.contains(f.code())).toList();
}
private static boolean hasH1(String html) {
return html != null && html.toLowerCase(Locale.ROOT).contains("<h1");
}
@Override
public Capabilities capabilities() {
return Capabilities.of("quality.seo");
}
}
@@ -0,0 +1,168 @@
package mx.quest.demo;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import mx.quest.runway.spi.service.PluginSiteFiles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.DeserializationFeature;
import tools.jackson.dataformat.yaml.YAMLMapper;
/**
* The demo's per-site "sticky notes" — data the plugin <b>generates for a site</b>, kept in the plugin's own per-site
* folder through the kernel's {@link PluginSiteFiles}: {@value #FILE} under {@code sites/<id>/plugins/runway-demo/}.
*
* <p><b>When to use {@code PluginSiteFiles}.</b> For anything your plugin stores per site. The folder lives inside the
* site's folder, so a full backup carries it, a deleted site takes it along, and nobody else's code can reach it — no
* {@code BackupParticipant} is needed (1.x kept the notes outside the site folder and needed one; 2.0.0 does not).
* The service is bound to <i>this</i> plugin by the jar the injecting class came from, so no method takes a plugin id.
*
* <p><b>Personal data.</b> The notes hold what people typed — an operator's notes from the console and a visitor's
* message from the public feedback form — so {@code plugin.yml} declares {@value #FILE} under
* {@code siteData.personal}: a transfer copy of the site leaves it out. Rule of thumb: any file holding visitor or
* user input is personal.
*
* <p><b>Concurrency.</b> Each kernel write is atomic (readers never see half a file), but an append is a
* read-modify-write, which the service leaves to the plugin: it is serialized here per site. The file is bounded to
* the newest {@value #MAX_NOTES} notes, far below the kernel's per-write cap.
*
* <p><b>A {@code GET} never writes.</b> A site with no notes yet shows a welcome note, but the welcome is not stored
* until something else is: the first {@link #append} (a console note, a visitor's message, the settings audit note)
* writes the welcome and the new note together, so the note an operator saw stays in the list. Until then the site
* has no {@value #FILE} at all. Reads ({@link #list}, {@link #count}, {@link #recent}) never create a file — opening
* a console screen or the settings page must not change a site.
*
* <p><b>Failure.</b> A read failure during {@link #append} aborts the append (rewriting the file from nothing would
* lose every note); the console reads ({@link #list}, {@link #count}) degrade to empty with a warning, so an
* unreadable file never takes a console screen down. The YAML goes through the plugin's own Jackson (a platform
* library), lenient about keys it does not know, so a later version can add fields without breaking this one.
*/
public class DemoNotesStore {
/** The notes file, relative to the plugin's per-site folder; declared personal in {@code plugin.yml}. */
static final String FILE = "notes.yml";
/** The most notes a site keeps (the oldest are dropped). */
static final int MAX_NOTES = 200;
/** The longest note text kept, in characters. */
static final int MAX_TEXT = 1000;
/**
* The welcome note's fixed id (never one {@code newId} makes), so the welcome a site shows is the note its first
* write keeps.
*/
static final String WELCOME_ID = "welcome";
private static final Logger log = LoggerFactory.getLogger(DemoNotesStore.class);
private final PluginSiteFiles files;
private final YAMLMapper yaml = YAMLMapper.builder()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.build();
private final ConcurrentMap<String, Object> locks = new ConcurrentHashMap<>();
public DemoNotesStore(PluginSiteFiles files) {
this.files = files;
}
private Object lockFor(String siteId) {
return locks.computeIfAbsent(siteId, k -> new Object());
}
/**
* The site's notes, oldest first. A site with no notes yet reads as the one {@linkplain #welcome() welcome note},
* which is <b>not written</b> (see the class comment). Empty, with a warning, when the file cannot be read.
*/
public List<Note> list(String siteId) {
synchronized (lockFor(siteId)) {
NotesFile file;
try {
file = read(siteId);
} catch (IOException | JacksonException e) {
log.warn("runway-demo notes of site {} could not be read: {}", siteId, e.toString());
return List.of();
}
return file.notes().isEmpty() ? List.of(welcome()) : file.notes();
}
}
/**
* The note a site with no notes shows. Its id is fixed and it has no time ({@code createdAt} is empty) while it is
* only shown; the first {@link #append} stores it with that write's time.
*/
static Note welcome() {
return new Note(WELCOME_ID, "Welcome — this note is data the runway-demo plugin keeps for this site in its "
+ "own folder; it travels in full backups and is left out of transfer copies.", "",
Note.ORIGIN_SYSTEM);
}
/**
* Appends a note (its text stripped and capped at {@value #MAX_TEXT} characters) and returns the new count. The
* first append to a site with no notes also stores the {@linkplain #welcome() welcome note}, before the new one.
*
* @param origin who wrote it: {@link Note#ORIGIN_CONSOLE}, {@link Note#ORIGIN_VISITOR} or {@link Note#ORIGIN_SYSTEM}
* @throws UncheckedIOException when the file cannot be read or written (an unreadable file is left untouched)
*/
public int append(String siteId, String text, String origin) {
String clean = text == null ? "" : text.strip();
if (clean.length() > MAX_TEXT) {
clean = clean.substring(0, MAX_TEXT);
}
synchronized (lockFor(siteId)) {
try {
List<Note> notes = new ArrayList<>(read(siteId).notes());
String now = Instant.now().toString();
if (notes.isEmpty()) {
// The first write keeps the welcome the site was showing, stamped with this write's time.
Note shown = welcome();
notes.add(new Note(shown.id(), shown.text(), now, shown.origin()));
}
notes.add(new Note(newId(), clean, now, origin));
if (notes.size() > MAX_NOTES) {
notes = new ArrayList<>(notes.subList(notes.size() - MAX_NOTES, notes.size()));
}
write(siteId, new NotesFile(notes));
return notes.size();
} catch (IOException e) {
throw new UncheckedIOException("storing a runway-demo note for site " + siteId, e);
} catch (JacksonException unparsable) {
// Jackson 3 exceptions are unchecked; an unparsable file is as unreadable as an I/O failure.
throw new UncheckedIOException("storing a runway-demo note for site " + siteId,
new IOException(unparsable));
}
}
}
/** The number of notes the site shows (1, the unsaved welcome, for a site with none yet; as {@link #list}). */
public int count(String siteId) {
return list(siteId).size();
}
/** The newest {@code limit} notes, newest first. */
public List<Note> recent(String siteId, int limit) {
List<Note> all = list(siteId);
return all.subList(Math.max(0, all.size() - limit), all.size()).reversed();
}
private NotesFile read(String siteId) throws IOException {
Optional<String> text = files.readText(siteId, FILE);
if (text.isEmpty() || text.get().isBlank()) {
return NotesFile.empty();
}
NotesFile parsed = yaml.readValue(text.get(), NotesFile.class);
return parsed == null ? NotesFile.empty() : parsed;
}
private void write(String siteId, NotesFile file) throws IOException {
files.writeText(siteId, FILE, yaml.writeValueAsString(file));
}
private static String newId() {
return "n-" + Long.toString(System.nanoTime(), 36);
}
}
@@ -0,0 +1,76 @@
package mx.quest.demo;
import java.util.Set;
import mx.quest.runway.spi.ContentWidget;
import mx.quest.runway.spi.model.Capabilities;
import mx.quest.runway.spi.model.RenderFragment;
import mx.quest.runway.spi.model.SettingsView;
import mx.quest.runway.spi.model.WidgetView;
import mx.quest.runway.spi.service.Messages;
import mx.quest.runway.spi.service.PluginSettings;
/**
* {@code ContentWidget} — renders a styled callout wherever a tenant page carries the anchor
* {@code <div id="..." data-widget="demo-notice/<instance>">} (the {@code id} AND {@code data-widget} on the same
* element). {@link #key()} {@code "demo-notice"} is the {@code <type>} half of that anchor.
*
* <p>Reads the per-site {@code notice.*} settings through {@link PluginSettings}: disabled →
* {@link RenderFragment#empty()}; {@code notice.style} picks the CSS class; {@code notice.max-chars} truncates (read
* with the clamped accessor, so a hand-edited out-of-range value can never break rendering). A chrome-scoped
* instance ({@link WidgetView#isChrome()}) shows the app-level {@code banner.text} instead.
*
* <p><b>{@code Messages.site}</b> is how visitor-facing text is localized: it resolves against the site's own bundle
* first, then every plugin's {@code i18n/} bundle, in the visitor's locale ({@code view.locale()}), and formats the
* arguments. Pure; never throws; owns its HTML escaping (the host splices the fragment unescaped).
*/
public class DemoNoticeWidget implements ContentWidget {
private static final Set<String> STYLES = Set.of("info", "warning", "danger");
private final DemoAppProps props;
private final PluginSettings settings;
private final Messages messages;
public DemoNoticeWidget(DemoAppProps props, PluginSettings settings, Messages messages) {
this.props = props;
this.settings = settings;
this.messages = messages;
}
@Override
public String key() {
return "demo-notice";
}
@Override
public RenderFragment render(WidgetView view) {
SettingsView site = settings.site(view.site().id());
if (!site.bool("notice.enabled", true)) {
return RenderFragment.empty();
}
String style = site.string("notice.style", "info");
if (!STYLES.contains(style)) {
style = "info";
}
int maxChars = (int) site.integer("notice.max-chars", 280, 1, 2000);
String body;
if (view.isChrome() && props.getBanner().isEnabled() && !props.getBanner().getText().isBlank()) {
body = props.getBanner().getText();
} else {
body = messages.site(view.site().id(), view.locale(), "runwaydemo.notice.body",
"This is the runway-demo notice widget (instance \"{0}\") on site \"{1}\".",
view.instanceId(), view.site().displayName());
}
if (body.length() > maxChars) {
body = body.substring(0, maxChars) + "…";
}
return RenderFragment.of("<div class=\"rw-demo-notice rw-demo-notice-" + style + "\" role=\"note\">"
+ Html.escape(body) + "</div>");
}
@Override
public Capabilities capabilities() {
return Capabilities.of("widget.configurable");
}
}
@@ -0,0 +1,139 @@
package mx.quest.demo;
import mx.quest.runway.spi.model.PluginInfo;
import mx.quest.runway.spi.service.AccessCheck;
import mx.quest.runway.spi.service.ContentCatalogView;
import mx.quest.runway.spi.service.ContentChanges;
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.RequestContext;
import mx.quest.runway.spi.service.SitePages;
import mx.quest.runway.spi.service.Sites;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
/**
* The plugin's {@code mainClass} — the single {@code @Configuration} the host registers into its context before
* refresh (as the bean {@code plugin:runway-demo}). Every bean is declared <b>explicitly</b> here; no
* {@code @ComponentScan} of the plugin's own package. The package ({@code mx.quest.demo}) lies outside
* {@code mx.quest.runway}, so the host never scans it.
*
* <h2>Everything from the kernel arrives as an SPI service</h2>
* The plugin links nothing of the host but {@code mx.quest.runway.spi} (a test proves it on the compiled classes).
* Services are ordinary Spring beans, received as {@code @Bean} method parameters:
* <ul>
* <li><b>plugin-scoped</b> — {@link PluginSettings}, {@link PluginSiteFiles}, {@link ContentChanges},
* {@link PluginInfo}: the host binds each to <i>this</i> plugin by the jar the injecting class
* ({@code DemoPluginConfig}) was loaded from. Inject them in a class of your own jar — never from a {@code lib/}
* jar, and never with a bare {@code getBean}, both of which fail at startup;</li>
* <li><b>kernel singletons</b> — {@link Sites}, {@link RequestContext}, {@link AccessCheck}, {@link Messages},
* {@link SitePages}, {@link ContentCatalogView}.</li>
* </ul>
*
* <h2>Rules the kernel checks</h2>
* <ul>
* <li><b>Bean names start with the plugin id in lowerCamelCase</b> ({@code runway-demo} → {@code runwayDemo…}):
* plugins share one bean namespace with the kernel and each other. The templates follow
* ({@code ${@runwayDemoAdminModel…}}).</li>
* <li><b>Allowed Spring surface</b>: SPI implementations, plain beans, and {@code @Controller}s mapped under
* {@code /__admin/runway-demo} or {@code /__app/runway-demo}. <b>Not allowed</b>: servlet {@code Filter}s (1.x's
* timing filter is gone — servlet filters are outside the 1.0 plugin contract), {@code SecurityFilterChain}s,
* bean (factory) post-processors, unrestricted {@code @ControllerAdvice}.</li>
* <li>Axis implementations ({@code HeadContributor}, {@code ContentWidget}, {@code EndpointContributor},
* {@code PageQualityCheck}, {@code ContentSource}) and callbacks ({@code SiteEventListener},
* {@code PluginLifecycle}) are collected <b>by type</b> — plain {@code @Bean}s, never {@code @Primary}. A bean
* method returns the <b>concrete</b> class, so Spring sees every interface it implements before creating it
* ({@link DemoShowcaseSource} is both a content source and a listener).</li>
* </ul>
*/
@Configuration(proxyBeanMethods = false)
public class DemoPluginConfig {
// --- app-level settings ---------------------------------------------------------------------------------
/** Bound from {@code runway.plugin.runway-demo.*} (the descriptor's {@code settings:}); applied on restart. */
@Bean
@ConfigurationProperties("runway.plugin.runway-demo")
public DemoAppProps runwayDemoAppProps() {
return new DemoAppProps();
}
// --- per-site data -----------------------------------------------------------------------------------------
@Bean
public DemoNotesStore runwayDemoNotesStore(PluginSiteFiles files) {
return new DemoNotesStore(files);
}
@Bean
public DemoShowcaseStore runwayDemoShowcaseStore(PluginSiteFiles files, ContentChanges changes) {
return new DemoShowcaseStore(files, changes);
}
// --- callbacks ---------------------------------------------------------------------------------------------
@Bean
public DemoLifecycle runwayDemoLifecycle() {
return new DemoLifecycle();
}
@Bean
public DemoActivity runwayDemoActivity(DemoNotesStore notes, Sites sites) {
return new DemoActivity(notes, sites);
}
// --- axis implementations ----------------------------------------------------------------------------------
@Bean
@Order(200) // after the kernel's SEO (@Order 100) and icon (@Order 90) head contributors
public DemoAnalyticsHead runwayDemoAnalyticsHead(DemoAppProps props, PluginSettings settings) {
return new DemoAnalyticsHead(props, settings);
}
@Bean
public DemoNoticeWidget runwayDemoNoticeWidget(DemoAppProps props, PluginSettings settings, Messages messages) {
return new DemoNoticeWidget(props, settings, messages);
}
@Bean
public DemoFeedbackWidget runwayDemoFeedbackWidget(PluginSettings settings, Messages messages) {
return new DemoFeedbackWidget(settings, messages);
}
@Bean
public DemoMetaLengthCheck runwayDemoMetaLengthCheck(PluginSettings settings) {
return new DemoMetaLengthCheck(settings);
}
@Bean
public DemoEndpoints runwayDemoEndpoints(AccessCheck access, DemoNotesStore notes, Messages messages,
PluginSettings settings) {
return new DemoEndpoints(access, notes, messages, settings);
}
/** A content source AND a SOURCE-phase listener (it drops its own cache before consumers re-read). */
@Bean
public DemoShowcaseSource runwayDemoShowcaseSource(DemoShowcaseStore store, Messages messages) {
return new DemoShowcaseSource(store, messages);
}
// --- console -------------------------------------------------------------------------------------------------
@Bean
public DemoAdminModel runwayDemoAdminModel(DemoNotesStore notes, DemoAppProps props, PluginSettings settings,
Sites sites, SitePages pages, PluginInfo self) {
return new DemoAdminModel(notes, props, settings, sites, pages, self);
}
@Bean
public DemoConsoleController runwayDemoConsoleController(RequestContext request, AccessCheck access,
Messages messages, SitePages pages,
ContentCatalogView catalog, DemoNotesStore notes,
DemoShowcaseStore showcase, DemoActivity activity,
PluginInfo self) {
return new DemoConsoleController(request, access, messages, pages, catalog, notes, showcase, activity, self);
}
}
@@ -0,0 +1,134 @@
package mx.quest.demo;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import mx.quest.runway.spi.ContentSource;
import mx.quest.runway.spi.model.Capabilities;
import mx.quest.runway.spi.model.CatalogChange;
import mx.quest.runway.spi.model.ContentBody;
import mx.quest.runway.spi.model.ContentRef;
import mx.quest.runway.spi.model.SiteLifecycleEvent;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.service.Messages;
import mx.quest.runway.spi.service.SiteEventListener;
/**
* {@code ContentSource} — serves the site's {@link Showcase} as a real public page at {@value #PATH}, through the
* kernel's own routing, the tenant's master chrome, the {@code <head>} treatment, {@code ETag}/{@code 304}, the
* sitemap/llms.txt listing and on-site search. Nothing is served until an operator publishes a showcase from the
* demo's console screen.
*
* <p>It is also a {@link SiteEventListener} in the {@link Phase#SOURCE SOURCE} phase. <b>When to use a
* {@code SOURCE} listener:</b> when you are a content source that keeps derived state of your own (here, the
* {@link DemoShowcaseStore}'s cached read). The kernel runs every {@code SOURCE} listener first, evicts its content
* listing again, and only then runs the {@code CONSUMER}s (sitemaps, search indexes) — so a consumer that re-reads
* the listing never sees a source's stale state. This one drops its cache on:
* <ul>
* <li>a {@code CONTENT} change of its own source — on this node the store already holds the new value, but a change
* <b>replayed from another node</b> ({@code local == false}) is the only way this node learns the file
* changed;</li>
* <li>a <b>wholesale</b> lifecycle event ({@code DELETED}, {@code RESTORED}): the site's files were replaced or
* removed under it.</li>
* </ul>
* A callback only evicts — cheap and synchronous, as the contract asks (heavy work belongs on your own executor).
*/
public class DemoShowcaseSource implements ContentSource, SiteEventListener {
/** This source's key: the namespace of its content ids ({@code runway-demo:showcase}). */
static final String SOURCE_KEY = "runway-demo";
/** The id of the one item this source serves per site. */
static final String ID = "showcase";
/** Where the showcase is served. */
static final String PATH = "/demo/showcase";
/** The body template: this plugin's {@code templates/showcase.html} + {@code .th.xml}. */
static final String BODY_TEMPLATE = "__plugin__/runway-demo/showcase";
private static final int DESCRIPTION_CHARS = 150;
private final DemoShowcaseStore store;
private final Messages messages;
public DemoShowcaseSource(DemoShowcaseStore store, Messages messages) {
this.store = store;
this.messages = messages;
}
@Override
public String key() {
return SOURCE_KEY;
}
/** Metadata only and published only — it runs on anonymous public requests (the sitemap). */
@Override
public List<ContentRef> enumerate(SiteView site) {
return store.current(site.id()).map(showcase -> List.of(ref(site, showcase))).orElse(List.of());
}
/** The cheap routing probe: one string comparison before anything is read. */
@Override
public Optional<ContentRef> resolve(SiteView site, String path, Locale locale) {
if (!PATH.equals(path)) {
return Optional.empty();
}
return enumerate(site).stream().filter(ref -> ref.hasLocale(locale, site.defaultLocale())).findFirst();
}
@Override
public ContentBody body(SiteView site, String id, Locale locale) {
if (!ID.equals(id)) {
return ContentBody.empty();
}
return store.current(site.id()).map(showcase -> ContentBody.of(html(showcase.text())))
.orElse(ContentBody.empty());
}
/** Declared with {@link #CAP_INDEXABLE_TEXT}, so on-site search indexes the showcase's text too. */
@Override
public String indexableText(SiteView site, String id, Locale locale) {
return ID.equals(id) ? store.current(site.id()).map(s -> html(s.text())).orElse("") : "";
}
@Override
public Capabilities capabilities() {
return Capabilities.of(CAP_INDEXABLE_TEXT);
}
private ContentRef ref(SiteView site, Showcase showcase) {
String language = site.defaultLocale().getLanguage();
String title = messages.site(site.id(), site.defaultLocale(), "runwaydemo.showcase.title", "Showcase");
String text = showcase.text().strip();
String description = text.length() > DESCRIPTION_CHARS ? text.substring(0, DESCRIPTION_CHARS) + "…" : text;
// No locales listed: the item exists in the site's default language only. updatedAt moves on every
// publish — the render ETag folds it, so a client revalidating gets the new text, not a stale 304.
return ContentRef.of(ID, PATH, Map.of(), List.of(), Map.of(language, title), Map.of(language, description),
BODY_TEMPLATE, showcase.updatedAt());
}
/** The plain text as HTML: escaped, one paragraph, line breaks kept. */
static String html(String text) {
return "<p>" + Html.escape(text.replace("\r\n", "\n")).replace("\n", "<br>\n") + "</p>";
}
// --- SiteEventListener (SOURCE phase) ----------------------------------------------------------------------
@Override
public Phase phase() {
return Phase.SOURCE;
}
@Override
public void onSiteLifecycle(SiteLifecycleEvent event) {
if (event.wholesale()) {
store.evict(event.siteId());
}
}
@Override
public void onCatalogChanged(CatalogChange change) {
if (change.cause() == CatalogChange.Cause.CONTENT && SOURCE_KEY.equals(change.sourceKey())) {
store.evict(change.siteId());
}
}
}
@@ -0,0 +1,179 @@
package mx.quest.demo;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Duration;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.LongSupplier;
import mx.quest.runway.spi.service.ContentChanges;
import mx.quest.runway.spi.service.PluginSiteFiles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.DeserializationFeature;
import tools.jackson.dataformat.yaml.YAMLMapper;
/**
* Reads and writes the site's {@link Showcase} ({@value #FILE} in the plugin's per-site folder) and — the point of
* this class — <b>announces every write with {@link ContentChanges}</b>.
*
* <p><b>When to use {@code ContentChanges}.</b> After every mutation of content your {@code ContentSource} serves:
* an item created, edited, deleted, published, unpublished, or the whole corpus replaced (pass a {@code null} id).
* The host cannot see your files change; the call evicts routing, the content listing, sitemaps and search indexes on
* every node of a cluster and notifies every {@code SiteEventListener} before it returns. Call it from the code that
* made the change, <b>after</b> the write and outside your own locks (listeners run synchronously on this thread),
* and never from a {@code SiteEventListener} callback — the kernel refuses that. It is plugin-scoped like
* {@code PluginSettings}: it only accepts a source key this plugin contributes.
*
* <p>The parsed file is cached per site, because {@code enumerate} runs on every catalog rebuild and routing miss.
* The cache is dropped by this store's own writes, by {@link DemoShowcaseSource}'s {@code SOURCE}-phase listener
* (a change replayed from another node, a restored or deleted site), and after {@link #TTL} at the latest — the
* backstop for a file edited by hand, which nobody announces.
*/
public class DemoShowcaseStore {
/** The showcase file, relative to the plugin's per-site folder. */
static final String FILE = "showcase.yml";
/** The longest showcase text kept, in characters. */
static final int MAX_TEXT = 2000;
/** How long a cached read is trusted without any announcement. */
static final Duration TTL = Duration.ofSeconds(60);
private static final Logger log = LoggerFactory.getLogger(DemoShowcaseStore.class);
/** The on-disk shape; the instant is written as ISO-8601 text. */
record ShowcaseFile(String text, String updatedAt) {
}
private record Cached(Optional<Showcase> value, long loadedAtNanos) {
}
private final PluginSiteFiles files;
private final ContentChanges changes;
private final LongSupplier nanoClock;
private final YAMLMapper yaml = YAMLMapper.builder()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.build();
private final ConcurrentMap<String, Cached> cache = new ConcurrentHashMap<>();
private final ConcurrentMap<String, Object> locks = new ConcurrentHashMap<>();
public DemoShowcaseStore(PluginSiteFiles files, ContentChanges changes) {
this(files, changes, System::nanoTime);
}
DemoShowcaseStore(PluginSiteFiles files, ContentChanges changes, LongSupplier nanoClock) {
this.files = files;
this.changes = changes;
this.nanoClock = nanoClock;
}
/** The site's published showcase; empty when none is published or the file cannot be read (logged). */
public Optional<Showcase> current(String siteId) {
Cached cached = cache.get(siteId);
if (fresh(cached)) {
return cached.value();
}
// Load under the site's lock, so a read racing a publish can never put the old file back into the cache.
synchronized (locks.computeIfAbsent(siteId, k -> new Object())) {
cached = cache.get(siteId);
if (fresh(cached)) {
return cached.value();
}
Optional<Showcase> loaded = load(siteId);
cache.put(siteId, new Cached(loaded, nanoClock.getAsLong()));
return loaded;
}
}
private boolean fresh(Cached cached) {
return cached != null && nanoClock.getAsLong() - cached.loadedAtNanos() < TTL.toNanos();
}
/**
* Publishes {@code text} (stripped, capped at {@value #MAX_TEXT} characters) as the site's showcase, replacing
* any previous one, then announces the change.
*
* @throws IllegalArgumentException when the text is blank
* @throws UncheckedIOException when the file cannot be written (nothing is announced)
*/
public Showcase publish(String siteId, String text) {
String clean = text == null ? "" : text.strip();
if (clean.isEmpty()) {
throw new IllegalArgumentException("the showcase text is blank");
}
if (clean.length() > MAX_TEXT) {
clean = clean.substring(0, MAX_TEXT);
}
Showcase showcase = new Showcase(clean, Instant.now());
synchronized (locks.computeIfAbsent(siteId, k -> new Object())) {
try {
files.writeText(siteId, FILE, yaml.writeValueAsString(
new ShowcaseFile(showcase.text(), showcase.updatedAt().toString())));
} catch (IOException e) {
throw new UncheckedIOException("publishing the runway-demo showcase of site " + siteId, e);
}
cache.put(siteId, new Cached(Optional.of(showcase), nanoClock.getAsLong()));
}
// Written; now tell the host — outside our lock, because every listener runs on this thread before it returns.
changes.changed(siteId, DemoShowcaseSource.SOURCE_KEY, DemoShowcaseSource.ID);
return showcase;
}
/**
* Unpublishes the site's showcase (deletes the file) and announces the change, so the page, the sitemap entry
* and any search hit disappear at once.
*
* @return {@code true} if a showcase was published; {@code false} (and nothing announced) when there was none
* @throws UncheckedIOException when the file cannot be deleted
*/
public boolean unpublish(String siteId) {
boolean deleted;
synchronized (locks.computeIfAbsent(siteId, k -> new Object())) {
try {
deleted = files.delete(siteId, FILE);
} catch (IOException e) {
throw new UncheckedIOException("unpublishing the runway-demo showcase of site " + siteId, e);
}
cache.put(siteId, new Cached(Optional.empty(), nanoClock.getAsLong()));
}
if (deleted) {
changes.changed(siteId, DemoShowcaseSource.SOURCE_KEY, DemoShowcaseSource.ID);
}
return deleted;
}
/** Drops the cached read of {@code siteId}, so the next {@link #current} reads the file again. */
public void evict(String siteId) {
cache.remove(siteId);
}
private Optional<Showcase> load(String siteId) {
try {
Optional<String> text = files.readText(siteId, FILE);
if (text.isEmpty() || text.get().isBlank()) {
return Optional.empty();
}
ShowcaseFile file = yaml.readValue(text.get(), ShowcaseFile.class);
if (file == null || file.text() == null || file.text().isBlank()) {
return Optional.empty();
}
return Optional.of(new Showcase(file.text(), parseInstant(file.updatedAt())));
} catch (IOException | JacksonException | IllegalArgumentException e) {
// IllegalArgumentException: an unsafe site id or a path escaping the folder. Serve nothing, never a 500.
log.warn("runway-demo showcase of site {} could not be read: {}", siteId, e.toString());
return Optional.empty();
}
}
private static Instant parseInstant(String value) {
try {
return value == null ? Instant.EPOCH : Instant.parse(value);
} catch (DateTimeParseException e) {
return Instant.EPOCH;
}
}
}
@@ -0,0 +1,23 @@
package mx.quest.demo;
/**
* Minimal HTML-text escaping. Every SPI that returns raw HTML (head markup, widget fragments) OWNS its
* escaping — the host splices the output unescaped. Sufficient for element-text and double-quoted-attribute
* contexts, which is all this demo emits.
*/
final class Html {
private Html() {
}
static String escape(String s) {
if (s == null || s.isEmpty()) {
return "";
}
return s.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;")
.replace("'", "&#39;");
}
}
@@ -0,0 +1,25 @@
package mx.quest.demo;
/**
* One per-site "sticky note". Immutable; serialized to {@code notes.yml} by {@link DemoNotesStore}.
*
* @param id stable note id (a timestamp-derived token)
* @param text the note body (plain text; escaped wherever it is rendered)
* @param createdAt ISO-8601 creation instant
* @param origin who wrote it: {@value #ORIGIN_CONSOLE}, {@value #ORIGIN_VISITOR} or {@value #ORIGIN_SYSTEM}
* ({@code null} in a file written before the field existed reads as {@value #ORIGIN_SYSTEM})
*/
public record Note(String id, String text, String createdAt, String origin) {
/** Written by an operator on the demo's console screen. */
public static final String ORIGIN_CONSOLE = "console";
/** Sent by a visitor through the public feedback form (the anonymous POST route). */
public static final String ORIGIN_VISITOR = "visitor";
/** Written by the plugin itself (the welcome note, the settings-saved audit note). */
public static final String ORIGIN_SYSTEM = "system";
public Note {
text = text == null ? "" : text;
origin = origin == null || origin.isBlank() ? ORIGIN_SYSTEM : origin;
}
}
@@ -0,0 +1,20 @@
package mx.quest.demo;
import java.util.List;
/**
* The on-disk shape of {@code notes.yml} — a wrapper around the note list so the format can grow new top-level keys
* without breaking older readers (the store reads with unknown keys ignored).
*
* @param notes the site's notes, oldest first; never {@code null}
*/
public record NotesFile(List<Note> notes) {
public NotesFile {
notes = (notes == null) ? List.of() : List.copyOf(notes);
}
public static NotesFile empty() {
return new NotesFile(List.of());
}
}
@@ -0,0 +1,20 @@
package mx.quest.demo;
import java.time.Instant;
/**
* The demo's one piece of <b>routable content</b> per site: a short message an operator publishes from the demo's
* console screen, served by {@link DemoShowcaseSource} as a page at {@value DemoShowcaseSource#PATH}. Stored as
* {@code showcase.yml} in the plugin's per-site folder (published content — not personal data).
*
* @param text the message (plain text; escaped when rendered)
* @param updatedAt when it was last published — the {@code ContentRef.updatedAt} the page's {@code ETag} folds, so a
* republished message is never answered with a stale {@code 304}
*/
public record Showcase(String text, Instant updatedAt) {
public Showcase {
text = text == null ? "" : text;
updatedAt = updatedAt == null ? Instant.EPOCH : updatedAt;
}
}
@@ -0,0 +1,133 @@
package mx.quest.demo;
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.util.List;
import java.util.Locale;
import java.util.Set;
import mx.quest.runway.spi.model.CatalogChange;
import mx.quest.runway.spi.model.LocalizedUrl;
import mx.quest.runway.spi.model.SettingsChange;
import mx.quest.runway.spi.model.SiteLifecycleEvent;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.service.SiteEventListener;
import mx.quest.runway.spi.testkit.EventDispatch;
import mx.quest.runway.spi.testkit.FakeSiteServices;
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/** The CONSUMER listener, driven by the testkit's {@link EventDispatch} in the kernel's order. */
class DemoActivityTest {
@TempDir
Path sites;
private DemoNotesStore notes;
private DemoActivity activity;
private EventDispatch events;
@BeforeEach
void setUp() throws IOException {
Files.createDirectories(sites.resolve("acme"));
notes = new DemoNotesStore(new TempDirSiteFiles(sites, "runway-demo"));
activity = new DemoActivity(notes, new FakeSiteServices()
.site(new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null)));
events = new EventDispatch("runway-demo", Set.of("runway-demo")).listener(activity);
}
private static LocalizedUrl url(String path) {
return new LocalizedUrl(Locale.ENGLISH, path, path);
}
@Test
void itIsAConsumer() {
assertEquals(SiteEventListener.Phase.CONSUMER, activity.phase());
}
@Test
void aSaveOfItsOwnSettingsAppendsOneAuditNote() {
int before = notes.count("acme");
events.settings("acme", "runway-demo");
List<Note> after = notes.list("acme");
assertEquals(before + 1, after.size());
assertTrue(after.getLast().text().startsWith("Per-site settings saved at "), after.getLast().text());
assertEquals(Note.ORIGIN_SYSTEM, after.getLast().origin());
assertTrue(events.failures().isEmpty());
}
@Test
void anotherPluginsSettingsSaveWritesNoNoteButIsRecordedAsACatalogChange() {
int before = notes.count("acme");
events.settings("acme", "contact");
assertEquals(before, notes.count("acme"), "onSettingsChanged is for this plugin's own settings only");
DemoActivity.Entry entry = activity.recent("acme").getFirst();
assertEquals("settings", entry.cause());
assertEquals("contact", entry.item());
}
@Test
void aChangeReplayedFromAnotherNodeWritesNoSecondNote() {
int before = notes.count("acme");
activity.onSettingsChanged(new SettingsChange("acme", "runway-demo", false));
assertEquals(before, notes.count("acme"), "the node where the save happened wrote the note");
}
@Test
void aPageChangeIsRecordedWithItsUrlsBeforeAndAfter() {
events.page("acme", "about", List.of(url("/about")), List.of(url("/about-us")));
DemoActivity.Entry entry = activity.recent("acme").getFirst();
assertEquals("page", entry.cause());
assertEquals("pages:about", entry.item());
assertEquals(List.of("/about"), entry.previousUrls());
assertEquals(List.of("/about-us"), entry.currentUrls());
assertTrue(entry.local());
}
@Test
void aDeletionStillNamesTheOldAddressAndAWholeSourceChangeShowsAStar() {
events.page("acme", "gone", List.of(url("/gone")), List.of());
events.catalog(new CatalogChange("acme", CatalogChange.Cause.CONTENT, "blog", null, "blog", null, null,
false));
List<DemoActivity.Entry> recent = activity.recent("acme");
assertEquals("blog:*", recent.get(0).item(), "newest first; a null id is the whole corpus");
assertFalse(recent.get(0).local());
assertEquals(List.of("/gone"), recent.get(1).previousUrls());
assertEquals(List.of(), recent.get(1).currentUrls());
}
@Test
void onlyTheNewestChangesAreKept() {
for (int i = 0; i < DemoActivity.KEEP + 4; i++) {
events.page("acme", "p" + i, List.of(), List.of());
}
List<DemoActivity.Entry> recent = activity.recent("acme");
assertEquals(DemoActivity.KEEP, recent.size());
assertEquals("pages:p" + (DemoActivity.KEEP + 3), recent.getFirst().item());
}
@Test
void aWholesaleEventDropsWhatWasRecordedForTheSite() {
events.page("acme", "about", List.of(), List.of());
events.lifecycle("acme", SiteLifecycleEvent.Kind.DELETED, false);
List<DemoActivity.Entry> recent = activity.recent("acme");
assertEquals(1, recent.size(), "only the deletion's own SITE change remains (lifecycle runs first)");
assertEquals("site", recent.getFirst().cause());
events.lifecycle("acme", SiteLifecycleEvent.Kind.SUSPENDED, false);
assertEquals(2, activity.recent("acme").size(), "a non-wholesale event keeps the record");
assertTrue(events.failures().isEmpty(), "an unknown site in Sites is handled: " + events.failures());
}
@Test
void anUnknownSiteHasNoActivityAndANoteFailureNeverPropagates() {
assertEquals(List.of(), activity.recent("nobody"));
activity.onSettingsChanged(new SettingsChange("ghost", "runway-demo", true)); // no folder: logged only
events.lifecycle("ghost", SiteLifecycleEvent.Kind.CREATED, false); // unknown to Sites
assertTrue(events.failures().isEmpty(), events.failures().toString());
}
}
@@ -0,0 +1,239 @@
package mx.quest.demo;
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.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import mx.quest.runway.spi.model.CatalogEntry;
import mx.quest.runway.spi.model.ContentRef;
import mx.quest.runway.spi.model.Finding;
import mx.quest.runway.spi.model.InstallResult;
import mx.quest.runway.spi.model.LocalizedUrl;
import mx.quest.runway.spi.model.PluginInfo;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.model.StarterPage;
import mx.quest.runway.spi.service.ConsoleScreen;
import mx.quest.runway.spi.service.SitePages;
import mx.quest.runway.spi.testkit.EventDispatch;
import mx.quest.runway.spi.testkit.FakeContentCatalog;
import mx.quest.runway.spi.testkit.FakeSiteServices;
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.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
/**
* The console screen driven through Spring MVC in-process (MockMvc), over the testkit's fakes. The
* {@code @PreAuthorize} gates are enforced by the host's method security, which a standalone MockMvc does not have:
* {@link DemoPluginConfigTest} proves every handler carries one, and the live verify script proves a request without
* the permission or the CSRF token is refused.
*/
class DemoConsoleControllerTest {
private static final SiteView SITE = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null);
private static final String BASE = "/__admin/runway-demo";
@TempDir
Path sites;
private FakeSiteServices kernel;
private FakeContentCatalog catalog;
private EventDispatch events;
private DemoNotesStore notes;
private DemoShowcaseStore showcase;
private DemoActivity activity;
private MockMvc mvc;
@BeforeEach
void setUp() throws IOException {
Files.createDirectories(sites.resolve("acme"));
kernel = new FakeSiteServices().site(SITE).current("acme");
catalog = new FakeContentCatalog().site("acme");
TempDirSiteFiles files = new TempDirSiteFiles(sites, "runway-demo");
events = new EventDispatch("runway-demo", Set.of("runway-demo"));
notes = new DemoNotesStore(files);
showcase = new DemoShowcaseStore(files, events);
activity = new DemoActivity(notes, kernel);
events.listener(new DemoShowcaseSource(showcase, kernel)).listener(activity);
mvc = mvcFor(kernel);
}
private MockMvc mvcFor(FakeSiteServices services) {
DemoConsoleController controller = new DemoConsoleController(services, services, services, services,
catalog, notes, showcase, activity, new PluginInfo("runway-demo", "2.0.1", sites));
return MockMvcBuilders.standaloneSetup(controller).build();
}
private DemoConsoleController.Screen screen(MvcResult result) {
return (DemoConsoleController.Screen) result.getModelAndView().getModel().get("rd");
}
@Test
void theScreenRendersInsideTheConsoleShell() throws Exception {
catalog.entry("acme", new CatalogEntry("pages", ContentRef.of("about", "/about", Map.of(), List.of(),
Map.of("en", "About"), Map.of(), "about", null), List.of(new LocalizedUrl(Locale.ENGLISH, "/about",
"/about")), "/about"));
MvcResult result = mvc.perform(get(BASE))
.andExpect(status().isOk())
.andExpect(view().name(ConsoleScreen.LAYOUT_VIEW))
.andExpect(model().attribute(ConsoleScreen.CONTENT_TEMPLATE, "__plugin__/runway-demo/console"))
.andExpect(model().attribute(ConsoleScreen.PAGE_TITLE_KEY, "runwaydemo.console.title"))
.andReturn();
DemoConsoleController.Screen screen = screen(result);
assertEquals("acme", screen.site().id(), "the site comes from RequestContext");
assertEquals("2.0.1", screen.pluginVersion());
assertEquals(1, screen.noteCount(), "the welcome note");
assertEquals(1, screen.catalogTotal());
assertEquals("/about", screen.catalog().getFirst().path());
assertNull(screen.showcaseText());
assertEquals("", screen.starterPath());
assertNull(screen.pathCheck());
}
@Test
void openingTheScreenWritesNothingAndTheFirstNoteKeepsTheWelcome() throws Exception {
Path pluginFolder = sites.resolve("acme").resolve("plugins").resolve("runway-demo");
mvc.perform(get(BASE)).andExpect(status().isOk());
mvc.perform(get(BASE)).andExpect(status().isOk());
assertFalse(Files.exists(pluginFolder), "a GET created no notes.yml, not even the plugin's folder");
mvc.perform(post(BASE + "/notes").param("text", "First")).andExpect(redirectedUrl(BASE));
List<Note> stored = notes.list("acme");
assertEquals(List.of(DemoNotesStore.WELCOME_ID, stored.get(1).id()), stored.stream().map(Note::id).toList(),
"the first POST writes the welcome the screen was showing, then the new note");
assertTrue(Files.isRegularFile(pluginFolder.resolve(DemoNotesStore.FILE)));
assertEquals(2, screen(mvc.perform(get(BASE)).andReturn()).noteCount());
}
@Test
void theApplicationConsoleHasNoSiteSoTheScreenIsNotFound() throws Exception {
mvcFor(new FakeSiteServices().site(SITE)).perform(get(BASE)).andExpect(status().isNotFound());
mvcFor(new FakeSiteServices().site(SITE)).perform(post(BASE + "/notes").param("text", "x"))
.andExpect(status().isNotFound());
assertEquals(1, notes.count("acme"), "nothing was written");
}
@Test
void addANote() throws Exception {
mvc.perform(post(BASE + "/notes").param("text", "Remember the milk"))
.andExpect(redirectedUrl(BASE))
.andExpect(flash().attribute(DemoConsoleController.FLASH, "Note added."));
Note last = notes.list("acme").getLast();
assertEquals("Remember the milk", last.text());
assertEquals(Note.ORIGIN_CONSOLE, last.origin());
mvc.perform(post(BASE + "/notes").param("text", " "))
.andExpect(redirectedUrl(BASE))
.andExpect(flash().attribute(DemoConsoleController.FLASH_ERROR, "Write something first."));
}
@Test
void publishAndUnpublishTheShowcaseAnnounceAndReachTheListener() throws Exception {
mvc.perform(post(BASE + "/showcase").param("text", "Fresh"))
.andExpect(flash().attribute(DemoConsoleController.FLASH, "Showcase published at /demo/showcase."));
assertEquals(1, events.announced().size(), "ContentChanges.changed was called");
assertEquals("content", activity.recent("acme").getFirst().cause(), "…and the CONSUMER listener saw it");
assertEquals("Fresh", screen(mvc.perform(get(BASE)).andReturn()).showcaseText());
mvc.perform(post(BASE + "/showcase/unpublish"))
.andExpect(flash().attribute(DemoConsoleController.FLASH, "Showcase unpublished."));
mvc.perform(post(BASE + "/showcase/unpublish"))
.andExpect(flash().attribute(DemoConsoleController.FLASH, "No showcase was published."));
assertEquals(2, events.announced().size(), "an unpublish of nothing announces nothing");
mvc.perform(post(BASE + "/showcase").param("text", ""))
.andExpect(flash().attribute(DemoConsoleController.FLASH_ERROR, "Write something first."));
}
@Test
void installingTheStarterPageNeedsEditPagesAndReportsTheOutcome() throws Exception {
mvc.perform(post(BASE + "/install-page"))
.andExpect(flash().attribute(DemoConsoleController.FLASH_ERROR,
"Installing a page needs the permission to edit pages."));
assertTrue(kernel.installs().isEmpty(), "nothing installed without EDIT_PAGES");
kernel.grant("EDIT_PAGES");
mvc.perform(post(BASE + "/install-page"))
.andExpect(flash().attribute(DemoConsoleController.FLASH, "Demo page published at /demo."));
StarterPage page = kernel.installs().getFirst();
assertEquals("runway-demo", page.slug());
assertEquals("/demo", page.path());
assertTrue(page.noindex(), "a demo page is kept out of search engines");
assertTrue(page.html().contains("data-widget=\"demo-notice/page\"")
&& page.html().contains("data-widget=\"demo-feedback/page\""), page.html());
assertTrue(page.logic().contains("~{${master} :: head}"), "chrome by the ${master} variable");
mvc.perform(post(BASE + "/install-page"))
.andExpect(flash().attribute(DemoConsoleController.FLASH,
"A demo page already exists at /demo; nothing changed."));
assertEquals("/demo", screen(mvc.perform(get(BASE)).andReturn()).starterPath());
}
@Test
void everyInstallOutcomeHasWords() {
DemoConsoleController controller = new DemoConsoleController(kernel, kernel, kernel, kernel, catalog, notes,
showcase, activity, new PluginInfo("runway-demo", "2.0.1", sites));
assertEquals("Demo page created at /demo and waiting in the review queue.", controller.describe(
new InstallResult(InstallResult.Outcome.PENDING_REVIEW, "/demo", List.of())));
assertEquals("Demo page created at /demo as a draft: the quality checks blocked publishing."
+ " h1.missing: No heading", controller.describe(new InstallResult(
InstallResult.Outcome.DRAFT_BLOCKED, "/demo", List.of(Finding.error("h1.missing", "No heading")))));
}
@Test
void aFailedInstallIsReportedNotThrown() throws Exception {
kernel.grant("EDIT_PAGES");
SitePages failing = new 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 /demo");
}
};
DemoConsoleController controller = new DemoConsoleController(kernel, kernel, kernel, failing, catalog, notes,
showcase, activity, new PluginInfo("runway-demo", "2.0.1", sites));
MockMvcBuilders.standaloneSetup(controller).build().perform(post(BASE + "/install-page"))
.andExpect(flash().attribute(DemoConsoleController.FLASH_ERROR, "The demo page could not be installed."));
}
@Test
void thePathCheckAsksTheCatalog() throws Exception {
catalog.page("acme", "/about", Locale.ENGLISH, "about").route("/sitemap.xml");
DemoConsoleController.PathCheck owned = screen(mvc.perform(get(BASE).param("path", " /about "))
.andReturn()).pathCheck();
assertEquals(new DemoConsoleController.PathCheck("/about", true, true, "about"), owned);
DemoConsoleController.PathCheck route = screen(mvc.perform(get(BASE).param("path", "/sitemap.xml"))
.andReturn()).pathCheck();
assertEquals(new DemoConsoleController.PathCheck("/sitemap.xml", true, false, null), route);
DemoConsoleController.PathCheck reserved = screen(mvc.perform(get(BASE).param("path", "/__admin"))
.andReturn()).pathCheck();
assertEquals(false, reserved.servable());
}
@Test
void refreshDropsTheCachedListing() throws Exception {
mvc.perform(post(BASE + "/catalog/refresh"))
.andExpect(flash().attribute(DemoConsoleController.FLASH, "Content listing refreshed."));
assertEquals(List.of("acme"), catalog.refreshed());
}
}
@@ -0,0 +1,134 @@
package mx.quest.demo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/** The notes store over the kernel's per-site files (the testkit's {@code TempDirSiteFiles}, with its confinement). */
class DemoNotesStoreTest {
@TempDir
Path sites;
private DemoNotesStore store;
@BeforeEach
void setUp() throws IOException {
Files.createDirectories(sites.resolve("acme"));
store = new DemoNotesStore(new TempDirSiteFiles(sites, "runway-demo"));
}
private Path file(String site) {
return sites.resolve(site).resolve("plugins").resolve("runway-demo").resolve(DemoNotesStore.FILE);
}
@Test
void theNotesLiveInThePluginsOwnFolderOfTheSite() {
store.append("acme", "hello", Note.ORIGIN_CONSOLE);
assertTrue(Files.isRegularFile(file("acme")), "sites/acme/plugins/runway-demo/notes.yml");
}
@Test
void readsShowTheWelcomeNoteButNeverWriteAFile() {
assertEquals(1, store.count("acme"));
Note welcome = store.list("acme").getFirst();
assertEquals(DemoNotesStore.WELCOME_ID, welcome.id());
assertEquals(Note.ORIGIN_SYSTEM, welcome.origin());
assertEquals("", welcome.createdAt(), "a note that is only shown has no time");
assertEquals(List.of(welcome), store.recent("acme", 10));
assertFalse(Files.exists(file("acme")), "a read wrote nothing");
assertFalse(Files.exists(file("acme").getParent()), "not even the plugin's folder");
}
@Test
void theFirstAppendKeepsTheWelcomeNoteTheSiteWasShowing() {
assertEquals(2, store.append("acme", "first", Note.ORIGIN_CONSOLE), "the welcome and the new note");
assertTrue(Files.isRegularFile(file("acme")));
List<Note> notes = store.list("acme");
assertEquals(2, notes.size());
Note welcome = notes.getFirst();
assertEquals(DemoNotesStore.WELCOME_ID, welcome.id(), "the same note the site was showing");
assertEquals(DemoNotesStore.welcome().text(), welcome.text());
assertFalse(welcome.createdAt().isEmpty(), "stored with the time of the first write");
assertEquals(welcome.createdAt(), notes.get(1).createdAt());
assertEquals("first", notes.get(1).text());
assertEquals(3, store.append("acme", "second", Note.ORIGIN_CONSOLE), "the welcome is written once");
}
@Test
void appendKeepsOrderOriginAndStripsAndCapsTheText() {
store.append("acme", " first ", Note.ORIGIN_CONSOLE);
store.append("acme", "x".repeat(DemoNotesStore.MAX_TEXT + 50), Note.ORIGIN_VISITOR);
List<Note> notes = store.list("acme");
assertEquals(3, notes.size(), "the welcome, then the two notes");
assertEquals("first", notes.get(1).text());
assertEquals(Note.ORIGIN_CONSOLE, notes.get(1).origin());
assertEquals(DemoNotesStore.MAX_TEXT, notes.get(2).text().length());
assertEquals(Note.ORIGIN_VISITOR, notes.get(2).origin());
assertEquals(List.of(notes.get(2), notes.get(1), notes.get(0)), store.recent("acme", 5),
"recent is newest first");
assertEquals(List.of(notes.get(2)), store.recent("acme", 1));
}
@Test
void theFileIsBoundedToTheNewestNotes() {
for (int i = 0; i < DemoNotesStore.MAX_NOTES + 3; i++) {
store.append("acme", "note " + i, Note.ORIGIN_CONSOLE);
}
List<Note> notes = store.list("acme");
assertEquals(DemoNotesStore.MAX_NOTES, notes.size());
assertEquals("note 3", notes.getFirst().text(), "the oldest were dropped");
}
@Test
void sitesAreIsolated() throws IOException {
Files.createDirectories(sites.resolve("other"));
store.append("acme", "only acme", Note.ORIGIN_CONSOLE);
assertFalse(store.list("other").stream().anyMatch(n -> n.text().equals("only acme")));
}
@Test
void anUnknownKeyInTheFileIsIgnoredAndAMissingOriginReadsAsSystem() throws IOException {
Files.createDirectories(file("acme").getParent());
Files.writeString(file("acme"), "notes:\n- id: n-1\n text: old\n createdAt: '2026-01-01T00:00:00Z'\n"
+ " colour: blue\nfutureKey: 1\n", StandardCharsets.UTF_8);
List<Note> notes = store.list("acme");
assertEquals(1, notes.size());
assertEquals("old", notes.getFirst().text());
assertEquals(Note.ORIGIN_SYSTEM, notes.getFirst().origin());
}
@Test
void anUnreadableFileDegradesReadsButNeverLetsAnAppendOverwriteIt() throws IOException {
Files.createDirectories(file("acme").getParent());
Files.writeString(file("acme"), "notes: [ this is: not: valid", StandardCharsets.UTF_8);
assertEquals(List.of(), store.list("acme"), "a console read degrades to empty");
assertEquals(0, store.count("acme"));
assertThrows(UncheckedIOException.class, () -> store.append("acme", "x", Note.ORIGIN_CONSOLE),
"an append refuses rather than rewriting the file from nothing");
assertEquals("notes: [ this is: not: valid", Files.readString(file("acme")), "the file is untouched");
}
@Test
void aSiteWhoseFolderIsGoneCannotBeWrittenAndReadsTheUnsavedWelcome() {
assertThrows(UncheckedIOException.class, () -> store.append("ghost", "x", Note.ORIGIN_CONSOLE));
assertEquals(List.of(DemoNotesStore.welcome()), store.list("ghost"), "the welcome is shown, unsaved");
assertFalse(Files.exists(sites.resolve("ghost")), "nothing was created for a site that does not exist");
}
@Test
void anUnsafeSiteIdIsRefusedBeforeAnyIo() {
assertThrows(IllegalArgumentException.class, () -> store.append("../acme", "x", Note.ORIGIN_CONSOLE));
}
}
@@ -0,0 +1,369 @@
package mx.quest.demo;
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.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
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.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashSet;
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.ContentSource;
import mx.quest.runway.spi.ContentWidget;
import mx.quest.runway.spi.EndpointContributor;
import mx.quest.runway.spi.HeadContributor;
import mx.quest.runway.spi.PageQualityCheck;
import mx.quest.runway.spi.model.PluginInfo;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.service.ConsoleScreen;
import mx.quest.runway.spi.service.ContentChanges;
import mx.quest.runway.spi.service.PluginLifecycle;
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.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 org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.yaml.snakeyaml.Yaml;
/**
* The plugin's contract with the host, checked at build time — the same things the kernel's load-time checks warn
* about (and refuse from Runway 1.0): wiring over SPI services only, the bean-name rule, the allowed Spring surface,
* the console controller's mappings and gates, the bean names the templates reference, the descriptor (SPI floor,
* release version, personal data), the i18n bundles, and that the compiled classes link nothing of the host but the
* SPI.
*/
class DemoPluginConfigTest {
private static final String PREFIX = "runwayDemo";
private static Set<String> beanMethodNames() {
return Arrays.stream(DemoPluginConfig.class.getDeclaredMethods())
.filter(m -> m.isAnnotationPresent(Bean.class))
.map(Method::getName)
.collect(Collectors.toCollection(TreeSet::new));
}
@SuppressWarnings("unchecked")
private static Map<String, Object> descriptor() throws IOException {
try (Reader in = Files.newBufferedReader(Path.of("plugin.yml"), StandardCharsets.UTF_8)) {
return (Map<String, Object>) new Yaml().load(in);
}
}
@Test
void wiresEverythingFromSpiServicesAlone(@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", DemoConsoleController.STARTER_SLUG, "/demo-moved");
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
ctx.registerBean(PluginSettings.class, () -> new FakePluginSettings()
.secret("acme", "analytics.site-token", "t0k3n"));
ctx.registerBean(PluginSiteFiles.class, () -> new TempDirSiteFiles(sites, "runway-demo"));
ctx.registerBean(ContentChanges.class, () -> new EventDispatch("runway-demo", Set.of("runway-demo")));
ctx.registerBean(PluginInfo.class, () -> new PluginInfo("runway-demo", "2.0.1", sites));
ctx.registerBean(FakeSiteServices.class, () -> kernel);
ctx.registerBean(FakeContentCatalog.class, () -> new FakeContentCatalog().site("acme"));
ctx.register(DemoPluginConfig.class);
ctx.refresh();
assertEquals(Set.of("runwayDemoAnalyticsHead"), ctx.getBeansOfType(HeadContributor.class).keySet());
assertEquals(Set.of("runwayDemoNoticeWidget", "runwayDemoFeedbackWidget"),
ctx.getBeansOfType(ContentWidget.class).keySet());
assertEquals(Set.of("runwayDemoMetaLengthCheck"), ctx.getBeansOfType(PageQualityCheck.class).keySet());
assertEquals(Set.of("runwayDemoEndpoints"), ctx.getBeansOfType(EndpointContributor.class).keySet());
assertEquals(Set.of("runwayDemoShowcaseSource"), ctx.getBeansOfType(ContentSource.class).keySet());
assertEquals(Set.of("runwayDemoShowcaseSource", "runwayDemoActivity"),
ctx.getBeansOfType(SiteEventListener.class).keySet(), "one SOURCE and one CONSUMER listener");
assertEquals(Set.of("runwayDemoLifecycle"), ctx.getBeansOfType(PluginLifecycle.class).keySet());
assertNotNull(ctx.getBean("runwayDemoConsoleController", DemoConsoleController.class));
assertNotNull(ctx.getBean("runwayDemoAppProps", DemoAppProps.class));
DemoAdminModel model = ctx.getBean("runwayDemoAdminModel", DemoAdminModel.class);
assertEquals(1, model.noteCount("acme"), "the notes store works over the injected site files");
assertEquals("Acme", model.siteName("acme"), "…the site name comes from Sites");
assertEquals("/demo-moved", model.demoPagePath("acme"), "…the page path from SitePages");
assertTrue(model.siteTokenConfigured("acme"), "…the secret's presence from PluginSettings");
assertEquals("2.0.1", model.pluginVersion(), "…the version from PluginInfo");
}
}
@Test
void theAdminModelIsNullSafeForTheApplicationConsole(@TempDir Path sites) {
DemoAdminModel model = new DemoAdminModel(new DemoNotesStore(new TempDirSiteFiles(sites, "runway-demo")),
new DemoAppProps(), new FakePluginSettings(), new FakeSiteServices(), new FakeSiteServices(),
new PluginInfo("runway-demo", "2.0.1", sites));
assertEquals(0, model.noteCount(null));
assertEquals(List.of(), model.recentNotes(" "));
assertEquals("", model.siteName(null));
assertEquals("", model.demoPagePath(null));
assertFalse(model.siteTokenConfigured(null));
assertEquals("ghost", model.siteName("ghost"), "an unknown site shows its id");
assertEquals(mx.quest.runway.spi.RunwaySpi.VERSION, model.builtSpi());
assertEquals(mx.quest.runway.spi.RunwaySpi.runtimeVersion(), model.runningSpi());
}
@Test
void everyBeanNameStartsWithThePluginIdInLowerCamelCase() {
Set<String> names = beanMethodNames();
assertEquals(Set.of("runwayDemoAppProps", "runwayDemoNotesStore", "runwayDemoShowcaseStore",
"runwayDemoLifecycle", "runwayDemoActivity", "runwayDemoAnalyticsHead", "runwayDemoNoticeWidget",
"runwayDemoFeedbackWidget", "runwayDemoMetaLengthCheck", "runwayDemoEndpoints",
"runwayDemoShowcaseSource", "runwayDemoAdminModel", "runwayDemoConsoleController"), names);
for (Method m : DemoPluginConfig.class.getDeclaredMethods()) {
Bean bean = m.getAnnotation(Bean.class);
if (bean != null) {
assertEquals(0, bean.name().length + bean.value().length, "the method name is the bean name: " + m);
}
}
assertFalse(AnnotatedElementUtils.hasAnnotation(DemoPluginConfig.class,
org.springframework.boot.context.properties.EnableConfigurationProperties.class),
"@EnableConfigurationProperties would register a '<prefix>-<class>' bean name");
}
/** Servlet filters, security chains and post-processors are outside what a plugin may contribute. */
@Test
void noBeanIsOfAForbiddenSpringType() {
Set<String> forbidden = Set.of("jakarta.servlet.Filter", "org.springframework.security.web.SecurityFilterChain",
"org.springframework.boot.web.servlet.FilterRegistrationBean",
"org.springframework.beans.factory.config.BeanPostProcessor",
"org.springframework.beans.factory.config.BeanFactoryPostProcessor");
for (Method m : DemoPluginConfig.class.getDeclaredMethods()) {
if (!m.isAnnotationPresent(Bean.class)) {
continue;
}
Deque<Class<?>> queue = new ArrayDeque<>(List.of(m.getReturnType()));
Set<Class<?>> seen = new HashSet<>();
while (!queue.isEmpty()) {
Class<?> type = queue.pop();
if (!seen.add(type)) {
continue;
}
assertFalse(forbidden.contains(type.getName()), m.getName() + " is a " + type.getName());
if (type.getSuperclass() != null) {
queue.add(type.getSuperclass());
}
queue.addAll(List.of(type.getInterfaces()));
}
assertFalse(AnnotatedElementUtils.hasAnnotation(m.getReturnType(),
org.springframework.web.bind.annotation.ControllerAdvice.class), "no @ControllerAdvice needed");
}
}
@Test
void theConsoleControllerIsAConsoleScreenGatedAndMappedUnderItsOwnPrefix() {
Class<?> type = DemoConsoleController.class;
assertTrue(AnnotatedElementUtils.hasAnnotation(type, Controller.class));
assertTrue(type.isAnnotationPresent(ConsoleScreen.class), "the kernel fills the console shell for it");
assertEquals(List.of("/__admin/runway-demo"),
List.of(AnnotatedElementUtils.findMergedAnnotation(type, RequestMapping.class).path()));
int handlers = 0;
int gets = 0;
for (Method m : type.getDeclaredMethods()) {
RequestMapping mapping = AnnotatedElementUtils.findMergedAnnotation(m, RequestMapping.class);
if (mapping == null) {
continue;
}
handlers++;
PreAuthorize gate = m.getAnnotation(PreAuthorize.class);
assertNotNull(gate, m.getName() + " must be gated");
assertEquals("@authz.may('runway-demo|manage-notes')", gate.value());
for (String path : mapping.path()) {
assertTrue(path.isEmpty() || path.startsWith("/"), path);
}
if (m.isAnnotationPresent(GetMapping.class)) {
gets++;
assertEquals("screen", m.getName(), "only the read-only screen answers GET");
}
}
assertEquals(6, handlers, "the screen and five POST actions");
assertEquals(1, gets);
}
@Test
void theTemplatesReferenceOnlyOurOwnBeansAndAuthz() 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("authz", "runwayDemoAdminModel"), referenced);
assertTrue(beanMethodNames().contains("runwayDemoAdminModel"));
}
@Test
void theDescriptorDeclaresTheSpiFloorTheReleaseVersionAndTheConsoleMenu() 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-runway-demo</artifactId>\\s*<version>([^<]+)")
.matcher(pom);
assertTrue(version.find());
assertEquals("2.1.0", version.group(1));
assertEquals(version.group(1), String.valueOf(yml.get("version")), "plugin.yml and pom.xml agree");
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>"));
@SuppressWarnings("unchecked")
List<Map<String, Object>> menu = (List<Map<String, Object>>) yml.get("menu");
assertEquals(DemoConsoleController.BASE, menu.get(0).get("path"), "the menu opens the console screen");
assertEquals(DemoEndpoints.PERMISSION, menu.get(0).get("permission"), "the FULL namespaced key");
}
@Test
void theReleaseZipIsNamedAfterThePluginIdLikeEveryOtherPluginAndTheJarKeepsItsName() throws IOException {
String id = String.valueOf(descriptor().get("id"));
String pom = Files.readString(Path.of("pom.xml"), StandardCharsets.UTF_8).replaceAll("(?s)<!--.*?-->", "");
// publish-plugin-release.sh uploads target/runway-plugin-<id>-<version>.zip under the tag <id>-<version>.
assertTrue(pom.contains("<artifactId>runway-plugin-" + id + "</artifactId>"), "artifactId runway-plugin-" + id);
assertTrue(pom.contains("<zip destfile=\"${project.build.directory}/${project.artifactId}-${project.version}"
+ ".zip\">"), "the zip is named after the artifactId");
// The kernel loads every *.jar in the plugin's folder: a renamed jar copied over a 2.0.0 folder would load
// beside the old one. So the jar keeps the name 2.0.0 shipped.
assertTrue(pom.contains("<finalName>runway-plugin-demo</finalName>"), "the jar keeps its 2.0.0 name");
}
@Test
@SuppressWarnings("unchecked")
void theNotesFileIsDeclaredPersonalDataSoTransferCopiesLeaveItOut() throws IOException {
Map<String, Object> siteData = (Map<String, Object>) descriptor().get("siteData");
assertNotNull(siteData, "plugin.yml declares siteData");
assertEquals(List.of(DemoNotesStore.FILE), siteData.get("personal"),
"exactly the file holding what people typed; the showcase is published content");
}
@Test
@SuppressWarnings("unchecked")
void theSiteTokenIsDeclaredASecretAndEveryReadSettingIsDeclared() throws IOException {
List<Map<String, Object>> schema = (List<Map<String, Object>>) descriptor().get("siteSettings");
Map<String, Object> types = schema.stream()
.collect(Collectors.toMap(s -> (String) s.get("key"), s -> s.get("type")));
assertEquals("secret", types.get("analytics.site-token"),
"PluginSettings.secret hands out only keys declared type: secret");
String code = readAll(Path.of("src/main/java"));
Matcher reads = Pattern.compile("\\.(?:bool|string|integer|decimal|list)\\(\"([a-z.-]+)\"").matcher(code);
int count = 0;
while (reads.find()) {
count++;
assertTrue(types.containsKey(reads.group(1)), "read but not declared: " + reads.group(1));
}
assertTrue(count >= 8, "the per-site reads were found (" + count + ")");
}
private static String readAll(Path root) throws IOException {
StringBuilder all = new StringBuilder();
try (Stream<Path> files = Files.walk(root)) {
for (Path f : files.filter(Files::isRegularFile).toList()) {
all.append(Files.readString(f, StandardCharsets.UTF_8)).append('\n');
}
}
return all.toString();
}
@Test
void theEnglishAndSpanishBundlesDefineTheSameKeysAndEveryKeyUsedExists() throws IOException {
Set<String> en = keys("i18n/messages.properties");
assertEquals(en, keys("i18n/messages_es.properties"));
Set<String> used = new TreeSet<>();
Matcher code = Pattern.compile("\"(runwaydemo\\.[A-Za-z.]+)\"").matcher(readAll(Path.of("src/main/java")));
while (code.find()) {
used.add(code.group(1));
}
Matcher template = Pattern.compile("#\\{(runwaydemo\\.[A-Za-z.]+)").matcher(readAll(Path.of("templates")));
while (template.find()) {
used.add(template.group(1));
}
Matcher descriptor = Pattern.compile("label: (runwaydemo\\.[A-Za-z.]+)")
.matcher(Files.readString(Path.of("plugin.yml"), StandardCharsets.UTF_8));
while (descriptor.find()) {
used.add(descriptor.group(1));
}
used.removeIf(en::contains);
assertEquals(Set.of(), used, "keys used but missing from the bundle");
}
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 theRemovedSeamsAreGone() {
for (String gone : List.of("DemoTimingFilter", "DemoNotesBackup", "DemoConfigReactor", "SiteConfig")) {
assertNull(classOrNull("mx.quest.demo." + gone), gone + " was removed in 2.0.0");
}
assertInstanceOf(PluginLifecycle.class, new DemoLifecycle());
}
private static Class<?> classOrNull(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
}
@@ -0,0 +1,202 @@
package mx.quest.demo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
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.Set;
import java.util.concurrent.atomic.AtomicLong;
import mx.quest.runway.spi.ContentSource;
import mx.quest.runway.spi.model.CatalogChange;
import mx.quest.runway.spi.model.ContentRef;
import mx.quest.runway.spi.model.SiteLifecycleEvent;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.service.SiteEventListener;
import mx.quest.runway.spi.testkit.EventDispatch;
import mx.quest.runway.spi.testkit.FakeSiteServices;
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* The showcase content source and its store: writes are announced with {@code ContentChanges} (the testkit's
* {@link EventDispatch}, which applies the kernel's refusal rules and phase order), the source serves what was
* published, and its {@code SOURCE}-phase listener drops the cache on the events that mean the file changed under it.
*/
class DemoShowcaseTest {
private static final SiteView SITE = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null);
@TempDir
Path sites;
private EventDispatch events;
private AtomicLong nanos;
private DemoShowcaseStore store;
private DemoShowcaseSource source;
private FakeSiteServices kernel;
@BeforeEach
void setUp() throws IOException {
Files.createDirectories(sites.resolve("acme"));
events = new EventDispatch("runway-demo", Set.of(DemoShowcaseSource.SOURCE_KEY));
nanos = new AtomicLong();
store = new DemoShowcaseStore(new TempDirSiteFiles(sites, "runway-demo"), events, nanos::get);
kernel = new FakeSiteServices().site(SITE);
source = new DemoShowcaseSource(store, kernel);
events.listener(source);
}
private Path file() {
return sites.resolve("acme/plugins/runway-demo").resolve(DemoShowcaseStore.FILE);
}
@Test
void nothingIsServedUntilAShowcaseIsPublished() {
assertEquals(List.of(), source.enumerate(SITE));
assertTrue(source.resolve(SITE, DemoShowcaseSource.PATH, Locale.ENGLISH).isEmpty());
assertTrue(source.body(SITE, DemoShowcaseSource.ID, Locale.ENGLISH).bodyHtml().isEmpty());
}
@Test
void publishWritesTheFileThenAnnouncesTheChangeOfItsOwnSource() {
store.publish("acme", " Hello <world> ");
assertTrue(Files.isRegularFile(file()));
List<CatalogChange> announced = events.announced();
assertEquals(1, announced.size());
assertEquals(CatalogChange.Cause.CONTENT, announced.getFirst().cause());
assertEquals("runway-demo", announced.getFirst().sourceKey());
assertEquals("showcase", announced.getFirst().id());
assertEquals("runway-demo", announced.getFirst().pluginId());
assertTrue(events.failures().isEmpty(), events.failures().toString());
}
@Test
void thePublishedShowcaseIsServedAsAPageOfTheSite() {
kernel.message("acme", "runwaydemo.showcase.title", "Our showcase");
store.publish("acme", "Line one\r\nLine <two> & three");
List<ContentRef> refs = source.enumerate(SITE);
assertEquals(1, refs.size());
ContentRef ref = refs.getFirst();
assertEquals("showcase", ref.id());
assertEquals("/demo/showcase", ref.path());
assertEquals("__plugin__/runway-demo/showcase", ref.bodyTemplate());
assertTrue(ref.published());
assertEquals("Our showcase", ref.titleFor(Locale.ENGLISH), "the title comes from Messages.site");
assertEquals("Line one\r\nLine <two> & three", ref.descriptionFor(Locale.ENGLISH));
assertEquals(ref, source.resolve(SITE, "/demo/showcase", Locale.ENGLISH).orElseThrow());
assertTrue(source.resolve(SITE, "/demo/showcase", Locale.of("es")).isEmpty(), "default language only");
assertTrue(source.resolve(SITE, "/demo/other", Locale.ENGLISH).isEmpty());
assertEquals("<p>Line one<br>\nLine &lt;two&gt; &amp; three</p>",
source.body(SITE, "showcase", Locale.ENGLISH).bodyHtml(), "escaped; line breaks kept");
assertEquals("", source.body(SITE, "other", Locale.ENGLISH).bodyHtml());
assertTrue(source.indexableText(SITE, "showcase", Locale.ENGLISH).contains("Line &lt;two&gt;"));
assertTrue(source.capabilities().has(ContentSource.CAP_INDEXABLE_TEXT), "search indexes it");
}
@Test
void aRepublishMovesUpdatedAtSoTheEtagChanges() throws InterruptedException {
store.publish("acme", "one");
ContentRef first = source.enumerate(SITE).getFirst();
Thread.sleep(5);
store.publish("acme", "two");
ContentRef second = source.enumerate(SITE).getFirst();
assertTrue(second.updatedAt().isAfter(first.updatedAt()), first.updatedAt() + " → " + second.updatedAt());
}
@Test
void aLongDescriptionIsCutAndALongTextCapped() {
store.publish("acme", "y".repeat(DemoShowcaseStore.MAX_TEXT + 10));
ContentRef ref = source.enumerate(SITE).getFirst();
assertEquals(151, ref.descriptionFor(Locale.ENGLISH).length(), "150 chars and an ellipsis");
assertEquals(DemoShowcaseStore.MAX_TEXT + 7,
source.body(SITE, "showcase", Locale.ENGLISH).bodyHtml().length(), "<p>…</p> around the capped text");
}
@Test
void aBlankShowcaseIsRefusedAndAnnouncesNothing() {
assertThrows(IllegalArgumentException.class, () -> store.publish("acme", " "));
assertTrue(events.announced().isEmpty());
}
@Test
void unpublishDeletesAndAnnouncesOnlyWhenSomethingWasPublished() {
assertFalse(store.unpublish("acme"), "nothing to unpublish");
assertTrue(events.announced().isEmpty(), "and nothing announced");
store.publish("acme", "live");
assertTrue(store.unpublish("acme"));
assertEquals(2, events.announced().size());
assertFalse(Files.exists(file()));
assertEquals(List.of(), source.enumerate(SITE));
}
@Test
void theCacheServesWithinTheTtlAndRereadsAfterIt() throws IOException {
store.publish("acme", "cached");
store.current("acme"); // the own announcement evicted the cache; this read fills it again
Files.writeString(file(), "text: edited by hand\nupdatedAt: '2026-01-01T00:00:00Z'\n", StandardCharsets.UTF_8);
source.onCatalogChanged(noChange()); // an unrelated change does not evict
assertEquals("cached", store.current("acme").orElseThrow().text(), "no announcement: the cache holds");
nanos.addAndGet(DemoShowcaseStore.TTL.toNanos());
assertEquals("edited by hand", store.current("acme").orElseThrow().text(), "the TTL is the backstop");
}
private static CatalogChange noChange() {
return new CatalogChange("acme", CatalogChange.Cause.PAGE, "pages", "about", null, null, null, true);
}
@Test
void aChangeReplayedFromAnotherNodeEvictsThisNodesCache() throws IOException {
store.publish("acme", "before");
Files.writeString(file(), "text: from the peer\nupdatedAt: '2026-01-01T00:00:00Z'\n", StandardCharsets.UTF_8);
events.catalog(new CatalogChange("acme", CatalogChange.Cause.CONTENT, "runway-demo", "showcase",
"runway-demo", null, null, false));
assertEquals("from the peer", store.current("acme").orElseThrow().text());
}
@Test
void aWholesaleLifecycleEventEvictsAndOthersDoNot() throws IOException {
store.publish("acme", "before");
store.current("acme");
Files.writeString(file(), "text: restored\nupdatedAt: '2026-01-01T00:00:00Z'\n", StandardCharsets.UTF_8);
source.onSiteLifecycle(new SiteLifecycleEvent("acme", SiteLifecycleEvent.Kind.UPDATED, false, true));
assertEquals("before", store.current("acme").orElseThrow().text(), "an UPDATED site keeps its files");
events.lifecycle("acme", SiteLifecycleEvent.Kind.RESTORED, true);
assertEquals("restored", store.current("acme").orElseThrow().text(), "a RESTORED site replaced them");
}
@Test
void theSourceListensInTheSourcePhase() {
assertEquals(SiteEventListener.Phase.SOURCE, source.phase());
}
@Test
void aCorruptOrForeignFileServesNothing() throws IOException {
Files.createDirectories(file().getParent());
Files.writeString(file(), "text: [ unclosed", StandardCharsets.UTF_8);
assertTrue(store.current("acme").isEmpty());
assertTrue(store.current("../x").isEmpty(), "an unsafe id answers nothing rather than throwing on a request");
}
@Test
void announcingFromInsideACallbackIsRefusedByTheKernelRule() {
EventDispatch strict = new EventDispatch("runway-demo", Set.of("runway-demo"));
DemoShowcaseStore inner = new DemoShowcaseStore(new TempDirSiteFiles(sites, "runway-demo"), strict);
strict.listener(new SiteEventListener() {
@Override
public void onSiteLifecycle(SiteLifecycleEvent event) {
inner.publish("acme", "from a callback");
}
});
strict.lifecycle("acme", SiteLifecycleEvent.Kind.UPDATED, false);
assertEquals(1, strict.failures().size());
assertTrue(strict.failures().getFirst() instanceof IllegalStateException);
}
}
@@ -0,0 +1,352 @@
package mx.quest.demo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import mx.quest.runway.spi.model.Finding;
import mx.quest.runway.spi.model.HeadContext;
import mx.quest.runway.spi.model.PageMeta;
import mx.quest.runway.spi.model.PageView;
import mx.quest.runway.spi.model.RenderFragment;
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.SiteView;
import mx.quest.runway.spi.model.WidgetView;
import mx.quest.runway.spi.testkit.FakePluginSettings;
import mx.quest.runway.spi.testkit.FakeSiteServices;
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* The demo's axis implementations as pure functions of their SPI inputs: no Spring, no host — the services come from
* {@code runway-spi-testkit}, whose fakes apply the kernel's input rules.
*/
class DemoSpiUnitTest {
private static final SiteView SITE = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH),
"https://acme.test");
private static final PageMeta PAGE = new PageMeta("about", "About us", "A description",
List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
@TempDir
Path sites;
private DemoNotesStore notes;
private FakeSiteServices kernel;
@BeforeEach
void setUp() throws IOException {
Files.createDirectories(sites.resolve("acme"));
notes = new DemoNotesStore(new TempDirSiteFiles(sites, "runway-demo"));
kernel = new FakeSiteServices().site(SITE);
}
private static FakePluginSettings settings(Map<String, ?> stored) {
return new FakePluginSettings().site("acme", stored);
}
// --- HeadContributor -------------------------------------------------------------------------------
@Test
void headEmitsGeneratorAndGatesAnalyticsOnTheSiteFlagAndTheAppKey() {
DemoAppProps props = new DemoAppProps();
props.getGenerator().setLabel("My Site");
props.getAnalytics().setWriteKey("ENC(opaque)");
HeadContext ctx = new HeadContext(SITE, PAGE, Locale.ENGLISH, "https://acme.test/about", null,
List.of(), false, false);
String on = new DemoAnalyticsHead(props, settings(Map.of("analytics.enabled", true))).render(ctx);
assertTrue(on.contains("<meta name=\"generator\" content=\"My Site\">"), on);
assertTrue(on.contains("data-demo-analytics") && on.contains("demo-analytics.js"), on);
assertFalse(on.contains("ENC(opaque)"), "the key never reaches the page");
String off = new DemoAnalyticsHead(props, settings(Map.of())).render(ctx);
assertFalse(off.contains("data-demo-analytics"), "analytics script absent when the site flag is off");
assertTrue(off.contains("demo.css"), "stylesheet linked (the notice defaults on)");
DemoAppProps noKey = new DemoAppProps();
assertFalse(new DemoAnalyticsHead(noKey, settings(Map.of("analytics.enabled", true))).render(ctx)
.contains("data-demo-analytics"), "no app-level key, no script");
assertFalse(new DemoAnalyticsHead(props, settings(Map.of("notice.enabled", false))).render(ctx)
.contains("demo.css"), "notice off, no stylesheet");
}
@Test
void headEscapesTheGeneratorLabelAndDeclaresItsSettingsFile() {
DemoAppProps props = new DemoAppProps();
props.getGenerator().setLabel("<script>x</script>");
HeadContext ctx = new HeadContext(SITE, PAGE, Locale.ENGLISH, null, null, List.of(), false, false);
DemoAnalyticsHead head = new DemoAnalyticsHead(props, settings(Map.of()));
String out = head.render(ctx);
assertTrue(out.contains("&lt;script&gt;"), "label escaped");
assertFalse(out.contains("<script>x</script>"), "raw label not emitted");
assertEquals(List.of("plugins/runway-demo.yml"), head.headInputs("acme"));
}
// --- ContentWidget: notice -------------------------------------------------------------------------
@Test
void noticeRendersWhenEnabledAndIsEmptyWhenDisabled() {
WidgetView view = new WidgetView(SITE, PAGE, Locale.ENGLISH, "n1", false, Map.of());
RenderFragment f = new DemoNoticeWidget(new DemoAppProps(),
settings(Map.of("notice.enabled", true, "notice.style", "warning")), kernel).render(view);
assertFalse(f.isEmpty());
assertTrue(f.html().contains("rw-demo-notice-warning"), f.html());
assertTrue(f.html().contains("instance &quot;n1&quot;") && f.html().contains("site &quot;Acme&quot;"),
"the fallback text formats its arguments: " + f.html());
assertTrue(new DemoNoticeWidget(new DemoAppProps(), settings(Map.of("notice.enabled", false)), kernel)
.render(view).isEmpty(), "disabled notice renders empty");
}
@Test
void noticeUsesTheSitesMessageInTheVisitorsLocaleAndEscapesIt() {
kernel.message("acme", "runwaydemo.notice.body", "<b>Aviso</b> {0} en {1}");
WidgetView view = new WidgetView(SITE, PAGE, Locale.of("es"), "n1", false, Map.of());
String html = new DemoNoticeWidget(new DemoAppProps(), settings(Map.of()), kernel).render(view).html();
assertTrue(html.contains("&lt;b&gt;Aviso&lt;/b&gt; n1 en Acme"), html);
}
@Test
void noticeFallsBackToInfoForAnUnknownStyleAndClampsMaxChars() {
WidgetView view = new WidgetView(SITE, PAGE, Locale.ENGLISH, "n1", false, Map.of());
String bad = new DemoNoticeWidget(new DemoAppProps(), settings(Map.of("notice.style", "x\" onclick=\"y")),
kernel).render(view).html();
assertTrue(bad.contains("rw-demo-notice-info\""), bad);
String truncated = new DemoNoticeWidget(new DemoAppProps(), settings(Map.of("notice.max-chars", 10L)), kernel)
.render(view).html();
assertTrue(truncated.contains(">This is th…<"), "truncated with an ellipsis: " + truncated);
String clamped = new DemoNoticeWidget(new DemoAppProps(), settings(Map.of("notice.max-chars", -5L)), kernel)
.render(view).html();
assertTrue(clamped.contains(">T…<"), "a hand-edited negative cap is clamped to 1: " + clamped);
}
@Test
void aChromeNoticeShowsTheAppLevelBanner() {
DemoAppProps props = new DemoAppProps();
props.getBanner().setText("Maintenance tonight");
WidgetView chrome = new WidgetView(SITE, PAGE, Locale.ENGLISH, "top", true, Map.of());
assertTrue(new DemoNoticeWidget(props, settings(Map.of()), kernel).render(chrome).html()
.contains("Maintenance tonight"));
props.getBanner().setEnabled(false);
assertFalse(new DemoNoticeWidget(props, settings(Map.of()), kernel).render(chrome).html()
.contains("Maintenance tonight"), "a disabled banner leaves the ordinary notice text");
}
// --- ContentWidget: feedback form ------------------------------------------------------------------
private static WidgetView feedbackView(Map<String, String> query, String path) {
return new WidgetView(SITE, PAGE, Locale.ENGLISH, "page", false, Map.of(), query, path);
}
@Test
void feedbackFormPostsToTheAnonymousRouteWithReturnPathHoneypotAndNoCsrfField() {
String html = new DemoFeedbackWidget(settings(Map.of()), kernel).render(feedbackView(Map.of(), "/demo"))
.html();
assertTrue(html.contains("<form method=\"post\" action=\"/demo/feedback\">"), html);
assertTrue(html.contains("name=\"return\" value=\"/demo\""), html);
assertTrue(html.contains("name=\"message\""), html);
assertTrue(html.contains("name=\"website\"") && html.contains("rw-demo-hp"), "honeypot present");
assertFalse(html.contains("_csrf"), "a shared, cacheable page carries no per-session token");
assertFalse(html.contains("role=\"status\""), "no outcome without the flag");
}
@Test
void feedbackShowsTheOutcomeFlagAndEscapesTheReturnPath() {
DemoFeedbackWidget widget = new DemoFeedbackWidget(settings(Map.of()), kernel);
assertTrue(widget.render(feedbackView(Map.of("demo-feedback", "thanks"), "/x")).html()
.contains("Thank you"));
assertTrue(widget.render(feedbackView(Map.of("demo-feedback", "invalid"), "/x")).html()
.contains("Please write a message first."));
assertTrue(widget.render(feedbackView(Map.of("demo-feedback", "limited"), "/x")).html()
.contains("Too many messages"));
assertFalse(widget.render(feedbackView(Map.of("demo-feedback", "<b>"), "/x")).html()
.contains("role=\"status\""), "an unknown flag shows nothing");
String html = widget.render(feedbackView(Map.of(), "/a\"b")).html();
assertTrue(html.contains("value=\"/a&quot;b\""), html);
assertTrue(widget.render(feedbackView(Map.of(), "")).html().contains("name=\"return\" value=\"/\""),
"an unknown path returns to the home page");
}
@Test
void feedbackIsEmptyWhenTheSiteTurnedItOff() {
assertTrue(new DemoFeedbackWidget(settings(Map.of("feedback.enabled", false)), kernel)
.render(feedbackView(Map.of(), "/demo")).isEmpty());
}
// --- PageQualityCheck ------------------------------------------------------------------------------
@Test
void qualityFlagsLongTitleMissingDescriptionAndMissingH1() {
PageMeta longTitle = new PageMeta("p", "x".repeat(80), "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
PageView page = new PageView(SITE, longTitle, Locale.ENGLISH, "u", "<html><body>no heading</body></html>");
List<String> codes = new DemoMetaLengthCheck(settings(Map.of())).inspect(page).stream()
.map(Finding::code).toList();
assertEquals(List.of("title.too-long", "description.missing", "h1.missing"), codes);
}
@Test
void qualityRatioScalesTheTitleLimitAndIgnoreCodesSuppress() {
PageMeta title70 = new PageMeta("p", "x".repeat(70), "d", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
PageView page = new PageView(SITE, title70, Locale.ENGLISH, "u", "<h1>t</h1>");
assertTrue(new DemoMetaLengthCheck(settings(Map.of("quality.title-warn-ratio", "1.5"))).inspect(page)
.isEmpty(), "70 chars is under 60 × 1.5");
assertEquals(1, new DemoMetaLengthCheck(settings(Map.of())).inspect(page).size());
PageView noH1 = new PageView(SITE, title70, Locale.ENGLISH, "u", "<p>no h1</p>");
List<String> codes = new DemoMetaLengthCheck(settings(Map.of("quality.ignore-codes",
"title.too-long, h1.missing"))).inspect(noH1).stream().map(Finding::code).toList();
assertTrue(codes.isEmpty(), "a comma-separated ignore list (with spaces) suppresses both: " + codes);
}
@Test
void qualityCleanPageHasNoFindings() {
PageView page = new PageView(SITE, PAGE, Locale.ENGLISH, "u", "<html><H1>About</H1></html>");
assertTrue(new DemoMetaLengthCheck(settings(Map.of())).inspect(page).isEmpty());
}
// --- EndpointContributor ---------------------------------------------------------------------------
private DemoEndpoints endpoints(FakePluginSettings settings, AtomicLong clock) {
return new DemoEndpoints(kernel, notes, kernel, settings, clock::get);
}
private static RouteRequest get(String path) {
return new RouteRequest(SITE, Locale.ENGLISH, "GET", path, Map.of("q", List.of("1")),
Map.of("X-Test", "yes"), null, null, "203.0.113.9", "https://acme.test");
}
private static RouteRequest post(String path, Map<String, List<String>> form, String clientIp) {
return new RouteRequest(SITE, Locale.ENGLISH, "POST", path, Map.of(), Map.of(), null, form, clientIp,
"https://acme.test");
}
private static String body(RouteResponse r) {
return new String(r.body(), StandardCharsets.UTF_8);
}
@Test
void routesAreThreeGetsAndOneAnonymousPost() {
List<Route> routes = endpoints(settings(Map.of()), new AtomicLong()).routes();
assertEquals(List.of("GET /demo/hello.txt", "GET /demo/echo.json", "GET /demo/notes.json",
"POST /demo/feedback"), routes.stream().map(r -> r.method() + " " + r.pathPattern()).toList());
assertEquals(List.of(false, false, false, true), routes.stream().map(Route::anonymous).toList(),
"only the visitor form is anonymous");
}
@Test
void helloIsLocalizedForTheRequestLocale() {
kernel.message("acme", "runwaydemo.hello", "¡Hola!");
RouteResponse hello = endpoints(settings(Map.of()), new AtomicLong()).handle(get("/demo/hello.txt"));
assertEquals(200, hello.status());
assertTrue(body(hello).startsWith("¡Hola!\nsite: Acme (acme)"), body(hello));
assertTrue(body(hello).contains("origin: https://acme.test"), body(hello));
}
@Test
void echoShowsWhatTheHostPutInTheRequestWithLowercaseHeaderNames() {
RouteResponse echo = endpoints(settings(Map.of()), new AtomicLong()).handle(get("/demo/echo.json"));
assertEquals(200, echo.status());
String json = body(echo);
assertTrue(json.contains("\"path\":\"/demo/echo.json\""), json);
// Since SPI 0.5.0 the host hands header names in lower case (lookups ignore case).
assertTrue(json.contains("\"x-test\":\"yes\""), "headers echoed by their lowercase name: " + json);
assertFalse(json.contains("X-Test"), json);
assertTrue(json.contains("\"clientIp\":\"203.0.113.9\"") && json.contains("\"origin\":\"https://acme.test\""),
json);
assertTrue(json.contains("\"form\":{}") && json.contains("\"param.q\":\"1\""), json);
}
@Test
void notesEndpointIsPermissionGated() {
DemoEndpoints ep = endpoints(settings(Map.of()), new AtomicLong());
assertEquals(403, ep.handle(get("/demo/notes.json")).status(), "denied without the permission");
kernel.grant("runway-demo|manage-notes");
RouteResponse ok = ep.handle(get("/demo/notes.json"));
assertEquals(200, ok.status());
assertTrue(body(ok).contains("\"count\":1"), "the welcome note: " + body(ok));
}
@Test
void aWrongMethodOrUnknownPathIsNotFound() {
DemoEndpoints ep = endpoints(settings(Map.of()), new AtomicLong());
assertEquals(404, ep.handle(post("/demo/hello.txt", Map.of(), null)).status());
assertEquals(404, ep.handle(get("/demo/feedback")).status(), "a GET submits nothing");
assertEquals(404, ep.handle(get("/demo/other")).status());
}
@Test
void feedbackStoresTheMessageAsAVisitorNoteAndRedirectsWithOnlyTheOutcome() {
DemoEndpoints ep = endpoints(settings(Map.of()), new AtomicLong());
RouteResponse r = ep.handle(post("/demo/feedback", Map.of("message", List.of(" Nice site! "),
"return", List.of("/demo"), "website", List.of("")), "198.51.100.1"));
assertEquals(303, r.status());
assertEquals("/demo?demo-feedback=thanks", r.headers().get("Location"));
Note last = notes.list("acme").getLast();
assertEquals("Nice site!", last.text());
assertEquals(Note.ORIGIN_VISITOR, last.origin());
}
@Test
void feedbackHoneypotBlankAndForeignReturnAreHandled() {
DemoEndpoints ep = endpoints(settings(Map.of()), new AtomicLong());
int before = notes.count("acme");
RouteResponse bot = ep.handle(post("/demo/feedback", Map.of("message", List.of("spam"),
"website", List.of("http://spam")), "198.51.100.2"));
assertEquals("/?demo-feedback=thanks", bot.headers().get("Location"), "a bot is told it worked");
RouteResponse blank = ep.handle(post("/demo/feedback", Map.of("message", List.of(" "),
"return", List.of("//evil.example/x")), "198.51.100.2"));
assertEquals("/?demo-feedback=invalid", blank.headers().get("Location"), "never an off-site redirect");
assertEquals(before, notes.count("acme"), "neither was stored");
}
@Test
void feedbackReadsTheBodyOnlyNeverTheQueryString() {
DemoEndpoints ep = endpoints(settings(Map.of()), new AtomicLong());
RouteRequest viaQuery = new RouteRequest(SITE, Locale.ENGLISH, "POST", "/demo/feedback",
Map.of("message", List.of("in the URL")), Map.of(), null, Map.of(), "198.51.100.3", "");
assertEquals("/?demo-feedback=invalid", ep.handle(viaQuery).headers().get("Location"));
}
@Test
void feedbackIsRateLimitedPerClientAddressWithASlidingWindow() {
AtomicLong clock = new AtomicLong(1_000_000);
DemoEndpoints ep = endpoints(settings(Map.of()), clock);
Map<String, List<String>> form = Map.of("message", List.of("hi"));
for (int i = 0; i < DemoEndpoints.FEEDBACK_PER_WINDOW; i++) {
assertEquals("/?demo-feedback=thanks", ep.handle(post("/demo/feedback", form, "192.0.2.7"))
.headers().get("Location"));
}
assertEquals("/?demo-feedback=limited", ep.handle(post("/demo/feedback", form, "192.0.2.7"))
.headers().get("Location"), "the sixth in the window is refused");
assertEquals("/?demo-feedback=thanks", ep.handle(post("/demo/feedback", form, "192.0.2.8"))
.headers().get("Location"), "another address has its own budget");
clock.addAndGet(DemoEndpoints.WINDOW_MILLIS);
assertEquals("/?demo-feedback=thanks", ep.handle(post("/demo/feedback", form, "192.0.2.7"))
.headers().get("Location"), "the window slides");
}
@Test
void feedbackIsNotFoundWhenTheSiteTurnedItOff() {
RouteResponse r = endpoints(settings(Map.of("feedback.enabled", false)), new AtomicLong())
.handle(post("/demo/feedback", Map.of("message", List.of("hi")), "192.0.2.9"));
assertEquals(404, r.status());
}
@Test
void safeLocalPathRefusesEverythingButALocalPath() {
assertEquals("/a/b?c=1", DemoEndpoints.safeLocalPath("/a/b?c=1"));
for (String bad : new String[] {null, "", "a", "//x", "/x://y", "/a b", "/a\\b", "/a\nb", "https://x"}) {
assertEquals("/", DemoEndpoints.safeLocalPath(bad), String.valueOf(bad));
}
}
}
@@ -0,0 +1,120 @@
package mx.quest.demo;
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.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.springframework.web.bind.annotation.PostMapping;
/**
* The shipped templates as files: every state-changing action of the console screen is reached by a
* {@code <form method="post">} that carries the console session's CSRF token, no link points at one (a link is a
* {@code GET}), every form action is a real handler, and no decoupled template repeats an {@code id} (a hard
* Thymeleaf error that would 500 the screen).
*/
class DemoTemplatesTest {
private static final Pattern FORM = Pattern.compile("(?s)<form\\b([^>]*)>(.*?)</form>");
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 Set<String> postActions() {
Set<String> paths = new TreeSet<>();
for (Method m : DemoConsoleController.class.getDeclaredMethods()) {
PostMapping post = m.getAnnotation(PostMapping.class);
if (post != null) {
for (String p : post.value()) {
paths.add(DemoConsoleController.BASE + p);
}
}
}
return paths;
}
@Test
void everyPostActionHasAPostFormCarryingTheCsrfToken() throws IOException {
assertEquals(Set.of("/__admin/runway-demo/notes", "/__admin/runway-demo/showcase",
"/__admin/runway-demo/showcase/unpublish", "/__admin/runway-demo/install-page",
"/__admin/runway-demo/catalog/refresh"), postActions());
String html = read("console.html");
Set<String> formed = new HashSet<>();
Matcher form = FORM.matcher(html);
while (form.find()) {
String attrs = form.group(1);
Matcher action = Pattern.compile("action=\"([^\"]+)\"").matcher(attrs);
assertTrue(action.find(), "every form names its action: " + attrs);
if (attrs.contains("method=\"get\"")) {
assertEquals(DemoConsoleController.BASE, action.group(1), "the only GET form is the read-only check");
assertFalse(form.group(2).contains("_csrf"), "a GET form must not put the token in a URL");
continue;
}
assertTrue(attrs.contains("method=\"post\""), attrs);
assertTrue(postActions().contains(action.group(1)), "a form posts to a real handler: " + action.group(1));
assertTrue(form.group(2).contains("class=\"rd-csrf\" type=\"hidden\" name=\"_csrf\""),
action.group(1) + "'s form carries the hidden CSRF field");
formed.add(action.group(1));
}
assertEquals(postActions(), formed, "every action is reachable from the screen");
assertTrue(read("console.th.xml").contains("<attr sel=\".rd-csrf\"\n " + TOKEN_BINDING + "/>"),
"the .rd-csrf fields are bound to the console session's token");
}
@Test
void noLinkPointsAtAnAction() throws IOException {
try (Stream<Path> files = Files.list(Path.of("templates"))) {
for (Path file : files.filter(p -> p.toString().endsWith(".html")).toList()) {
String html = read(file.getFileName().toString());
for (String action : postActions()) {
assertFalse(html.contains("href=\"" + action), file + " links to " + action);
}
}
}
}
@Test
void noTemplateRepeatsAnId() throws IOException {
try (Stream<Path> files = Files.list(Path.of("templates"))) {
for (Path file : files.filter(p -> p.toString().endsWith(".html")).toList()) {
Matcher ids = Pattern.compile("\\bid=\"([^\"]+)\"").matcher(read(file.getFileName().toString()));
Set<String> seen = new HashSet<>();
while (ids.find()) {
assertTrue(seen.add(ids.group(1)), file + ": duplicate id " + ids.group(1));
}
}
}
}
@Test
void everySelectorInTheLogicMatchesTheMarkup() throws IOException {
try (Stream<Path> files = Files.list(Path.of("templates"))) {
for (Path logic : files.filter(p -> p.toString().endsWith(".th.xml")).toList()) {
String name = logic.getFileName().toString().replace(".th.xml", "");
String html = read(name + ".html");
Matcher sel = Pattern.compile("sel=\"([^\"]+)\"").matcher(read(name + ".th.xml"));
while (sel.find()) {
for (String part : sel.group(1).split("//")) {
String token = part.startsWith("#") ? "id=\"" + part.substring(1) + "\""
: part.startsWith(".") ? part.substring(1) : "<" + part;
assertTrue(html.contains(token), name + ": selector " + sel.group(1) + " matches nothing");
}
}
}
}
}
}
+59
View File
@@ -0,0 +1,59 @@
/*
* runway-demo plugin styles — served at /__plugin/runway-demo/static/css/demo.css.
* Injected into tenant pages by the DemoAnalyticsHead HeadContributor (when the notice is enabled) and linked by
* the feedback form itself; styles the notice and feedback widgets. Served from the plugin's own namespace — never copied
* into a tenant.
*/
.rw-demo-notice {
border-radius: 6px;
padding: 0.75rem 1rem;
margin: 0.75rem 0;
border: 1px solid transparent;
font: 0.95rem/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
}
.rw-demo-notice-info {
background: #e7f5ff;
border-color: #a5d8ff;
color: #1864ab;
}
.rw-demo-notice-warning {
background: #fff9db;
border-color: #ffe066;
color: #997404;
}
.rw-demo-notice-danger {
background: #fff5f5;
border-color: #ffc9c9;
color: #c92a2a;
}
/* The public feedback form (DemoFeedbackWidget). */
.rw-demo-feedback form {
display: grid;
gap: 0.5rem;
max-width: 36rem;
font: 0.95rem/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
}
.rw-demo-feedback textarea {
font: inherit;
padding: 0.5rem;
}
.rw-demo-feedback button {
justify-self: start;
font: inherit;
padding: 0.4rem 1rem;
}
/* The honeypot: off-screen for people (and aria-hidden for assistive technology); a naive bot still fills it. */
.rw-demo-hp {
position: absolute;
left: -10000px;
width: 1px;
height: 1px;
overflow: hidden;
}
+13
View File
@@ -0,0 +1,13 @@
/*
* runway-demo — an inert demo script served at /__plugin/runway-demo/static/js/demo-analytics.js.
* Referenced by the DemoAnalyticsHead <script> tag (only when per-site analytics is enabled AND the app-level write
* key is set) purely to demonstrate the per-plugin static-asset seam. It does nothing but log; a real analytics
* plugin would emit the vendor snippet here. A plain <script src> is all a plugin emits: the kernel stamps the CSP
* nonce on it at the response edge.
*/
(function () {
"use strict";
var el = document.currentScript;
var site = el && el.getAttribute("data-site");
console.debug("[runway-demo] analytics placeholder loaded for site:", site || "(unknown)");
})();
+51
View File
@@ -0,0 +1,51 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Runway Demo — help</title>
<link rel="stylesheet" href="/__plugin/runway-demo/static/css/demo.css">
<style>
body { font: 1rem/1.6 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; max-width: 44rem;
margin: 2rem auto; padding: 0 1rem; color: #333; }
code { background: #f1f3f5; padding: 0.1em 0.35em; border-radius: 4px; }
h1 { font-size: 1.4rem; }
h2 { font-size: 1.1rem; margin-top: 1.5rem; }
</style>
</head>
<body>
<h1>Runway Demo — help</h1>
<div class="rw-demo-notice rw-demo-notice-info">
This page is a <strong>static asset</strong> served from the plugin's own namespace at
<code>/__plugin/runway-demo/static/notes-help.html</code>. Runway Demo is the reference plugin: everything it does
is there to show plugin authors how a feature is built.
</div>
<h2>The demo screen</h2>
<p>The <em>Runway demo</em> entry of the console menu opens the plugin's own screen (it needs the
<code>manage-notes</code> permission). From there you can add notes, install a ready-made demo page, publish a
short <em>showcase</em> page, look at the site's published content and check whether a path is free, and see the
changes the plugin has been told about.</p>
<h2>Notes</h2>
<p>The demo keeps a small set of per-site notes in its own folder of the site. Notes are:</p>
<ul>
<li>seeded with a welcome note the first time a site's notes are read;</li>
<li>added from the demo screen, and by visitors through the public feedback form;</li>
<li>appended automatically whenever this plugin's per-site settings are saved;</li>
<li>readable as JSON at <code>/demo/notes.json</code> — only with the <code>manage-notes</code> permission (anyone
else gets <code>403</code>);</li>
<li>kept in full backups, and <strong>left out of transfer copies</strong>: they hold what people typed, so the
plugin declares them personal data.</li>
</ul>
<h2>Pages and endpoints</h2>
<ul>
<li><code>/demo</code> — the demo page, once installed from the demo screen. It is an ordinary site page: edit,
move or delete it under Pages.</li>
<li><code>/demo/showcase</code> — the showcase page, while one is published.</li>
<li><code>/demo/hello.txt</code> — a per-site greeting in the visitor's language.</li>
<li><code>/demo/echo.json</code> — echoes what the platform tells the plugin about your request.</li>
</ul>
</body>
</html>
+17
View File
@@ -0,0 +1,17 @@
<div id="rd-admin" class="card mt-3">
<div class="card-header">
<h3 id="rd-admin-title" class="card-title">Runway Demo — status &amp; notes</h3>
</div>
<div class="card-body">
<p id="rd-admin-count" class="mb-1">Notes: 0</p>
<p id="rd-admin-banner" class="text-secondary mb-1">Banner: —</p>
<p id="rd-admin-key" class="text-secondary mb-1">Analytics key: —</p>
<p id="rd-admin-token" class="text-secondary mb-1">Site token: —</p>
<p id="rd-admin-page" class="text-secondary mb-2">Demo page: —</p>
<ul id="rd-admin-list" class="mb-2">
<li id="rd-admin-note">note</li>
</ul>
<a id="rd-admin-console" href="/__admin/runway-demo" class="btn btn-sm btn-primary">Open the demo screen</a>
<a id="rd-admin-api" href="/demo/notes.json" class="btn btn-sm btn-outline-primary">Open /demo/notes.json</a>
</div>
</div>
+17
View File
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Decoupled logic for the admin fragment. The host renders it automatically BELOW the per-site settings form because
templates/admin.html exists (a filename convention — no descriptor entry). Fed by the plugin's own bean; tenantSiteId
comes from the console. The link to the demo screen shows only to a user who may open it: ${@authz.may(..)} is the
AccessCheck bean, the same check the screen's @PreAuthorize makes (hiding a link is UX; the screen still checks).
-->
<thlogic>
<attr sel="#rd-admin-title" th:text="#{runwaydemo.admin.title}"/>
<attr sel="#rd-admin-count" th:text="#{runwaydemo.admin.notes(${@runwayDemoAdminModel.noteCount(tenantSiteId)})}"/>
<attr sel="#rd-admin-banner" th:text="#{runwaydemo.admin.banner(${@runwayDemoAdminModel.bannerEnabled()})}"/>
<attr sel="#rd-admin-key" th:text="#{runwaydemo.admin.writeKey(${@runwayDemoAdminModel.analyticsKeyConfigured()})}"/>
<attr sel="#rd-admin-token" th:text="#{runwaydemo.admin.siteToken(${@runwayDemoAdminModel.siteTokenConfigured(tenantSiteId)})}"/>
<attr sel="#rd-admin-page" th:text="${@runwayDemoAdminModel.demoPagePath(tenantSiteId).isEmpty()} ? #{runwaydemo.admin.page.none} : #{runwaydemo.admin.page(${@runwayDemoAdminModel.demoPagePath(tenantSiteId)})}"/>
<attr sel="#rd-admin-note" th:each="n : ${@runwayDemoAdminModel.recentNotes(tenantSiteId)}" th:text="${n.text()}"/>
<attr sel="#rd-admin-console" th:if="${@authz.may('runway-demo|manage-notes')}" th:text="#{runwaydemo.card.console}"/>
</thlogic>
+194
View File
@@ -0,0 +1,194 @@
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><title>Runway demo</title></head>
<body>
<!-- The demo's console screen content (@ConsoleScreen). The kernel's shell layout pulls in #content by name. Markup
only: every binding is in console.th.xml. Every state-changing action is a POST form carrying the console's CSRF
token (.rd-csrf); the path check is a GET form because it only reads. -->
<div id="content">
<div class="page-header d-print-none mb-3">
<div class="row align-items-center">
<div class="col">
<div class="page-pretitle" id="rd-pretitle">Site</div>
<h2 class="page-title" id="rd-heading">Runway demo</h2>
</div>
</div>
</div>
<div id="rd-flash" class="alert alert-success" role="status"><span id="rd-flash-text">done</span></div>
<div id="rd-error" class="alert alert-danger" role="alert"><span id="rd-error-text">error</span></div>
<div class="row row-cards">
<!-- PluginInfo + RunwaySpi: who am I, built against what, running on what. -->
<div class="col-md-6">
<div class="card">
<div class="card-header"><h3 class="card-title" id="rd-about-title">This plugin</h3></div>
<div class="card-body">
<p class="mb-1"><span id="rd-version-label">Version</span>: <code id="rd-version">2.0.1</code></p>
<p class="mb-1"><span id="rd-built-label">Built against SPI</span>: <code id="rd-built">0.6.0</code></p>
<p class="mb-0"><span id="rd-running-label">Running on SPI</span>: <code id="rd-running">0.6.0</code></p>
</div>
</div>
</div>
<!-- SitePages: the starter page, installed through the site's editorial rules. -->
<div class="col-md-6">
<div class="card">
<div class="card-header"><h3 class="card-title" id="rd-page-title">Demo page</h3></div>
<div class="card-body">
<p class="text-secondary" id="rd-page-desc">A ready-made page carrying the notice and feedback
widgets.</p>
<p id="rd-page-installed" class="mb-0"><span id="rd-page-at">Installed at</span>
<a id="rd-page-link" href="/demo"><code id="rd-page-path">/demo</code></a></p>
<form id="rd-page-form" method="post" action="/__admin/runway-demo/install-page" class="m-0">
<input class="rd-csrf" type="hidden" name="_csrf" value="">
<button type="submit" class="btn btn-primary" id="rd-page-install">Install the demo page</button>
</form>
</div>
</div>
</div>
<!-- PluginSiteFiles (+ siteData.personal): the per-site notes. -->
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h3 class="card-title" id="rd-notes-title">Notes</h3>
<span class="ms-auto text-secondary" id="rd-notes-count">0</span>
</div>
<div class="card-body">
<p class="text-secondary small" id="rd-notes-desc">Kept in the plugin's own folder of this site;
declared personal data, so transfer copies leave them out.</p>
<form id="rd-note-form" method="post" action="/__admin/runway-demo/notes" class="mb-3">
<input class="rd-csrf" type="hidden" name="_csrf" value="">
<label class="form-label" for="rd-note-text" id="rd-note-label">New note</label>
<textarea class="form-control mb-2" id="rd-note-text" name="text" rows="2"
maxlength="1000"></textarea>
<button type="submit" class="btn btn-outline-primary" id="rd-note-add">Add note</button>
</form>
<ul class="list-unstyled mb-0" id="rd-note-list">
<li id="rd-note-row" class="mb-2">
<span class="badge bg-secondary-lt rd-note-origin">console</span>
<span class="rd-note-text">text</span>
<div class="text-secondary small rd-note-at">time</div>
</li>
</ul>
</div>
</div>
</div>
<!-- ContentSource + ContentChanges: the showcase page. -->
<div class="col-md-6">
<div class="card">
<div class="card-header"><h3 class="card-title" id="rd-show-title">Showcase page</h3></div>
<div class="card-body">
<p class="text-secondary small" id="rd-show-desc">Served by the plugin's content source. Publishing
or unpublishing announces the change, so routing, sitemaps and search follow at once.</p>
<div id="rd-show-live" class="mb-3">
<p class="mb-1"><span id="rd-show-at">Published at</span>
<a id="rd-show-link" href="/demo/showcase"><code id="rd-show-path">/demo/showcase</code></a></p>
<blockquote class="text-secondary" id="rd-show-text">text</blockquote>
<form id="rd-show-unpublish" method="post" action="/__admin/runway-demo/showcase/unpublish"
class="m-0">
<input class="rd-csrf" type="hidden" name="_csrf" value="">
<button type="submit" class="btn btn-outline-danger btn-sm" id="rd-show-unpublish-btn">Unpublish</button>
</form>
</div>
<p class="text-secondary" id="rd-show-none">Nothing is published.</p>
<form id="rd-show-form" method="post" action="/__admin/runway-demo/showcase" class="m-0">
<input class="rd-csrf" type="hidden" name="_csrf" value="">
<label class="form-label" for="rd-show-input" id="rd-show-label">Showcase text</label>
<textarea class="form-control mb-2" id="rd-show-input" name="text" rows="2"
maxlength="2000"></textarea>
<button type="submit" class="btn btn-outline-primary" id="rd-show-publish">Publish</button>
</form>
</div>
</div>
</div>
<!-- ContentCatalogView: the site's published content surface, the path check, the manual refresh. -->
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title" id="rd-cat-title">Content surface</h3>
<span class="ms-auto text-secondary" id="rd-cat-total">0</span>
</div>
<div class="card-body">
<form id="rd-check-form" method="get" action="/__admin/runway-demo" class="row g-2 mb-3">
<div class="col-auto">
<label class="visually-hidden" for="rd-check-path" id="rd-check-label">Path</label>
<input class="form-control" id="rd-check-path" name="path" placeholder="/about">
</div>
<div class="col-auto">
<button type="submit" class="btn btn-outline-secondary" id="rd-check-btn">Check a path</button>
</div>
</form>
<p id="rd-check-result" class="mb-3"><code id="rd-check-echo">/about</code>
<span id="rd-check-unsafe" class="badge bg-red-lt">unsafe</span>
<span id="rd-check-servable" class="badge bg-green-lt">servable</span>
<span id="rd-check-reserved" class="badge bg-yellow-lt">not servable</span>
<span id="rd-check-owner">owned by page</span>
<span id="rd-check-free">no published page owns it</span></p>
<div class="table-responsive">
<table class="table table-sm">
<thead>
<tr>
<th id="rd-cat-h-source">Source</th>
<th id="rd-cat-h-id">Item</th>
<th id="rd-cat-h-path">Path</th>
</tr>
</thead>
<tbody>
<tr id="rd-cat-row">
<td class="rd-cat-source">pages</td>
<td class="rd-cat-id">about</td>
<td class="rd-cat-path">/about</td>
</tr>
</tbody>
</table>
</div>
<form id="rd-cat-refresh" method="post" action="/__admin/runway-demo/catalog/refresh" class="m-0">
<input class="rd-csrf" type="hidden" name="_csrf" value="">
<button type="submit" class="btn btn-sm btn-outline-secondary" id="rd-cat-refresh-btn">Refresh the listing</button>
</form>
</div>
</div>
</div>
<!-- SiteEventListener: what this node saw change, with the URLs before and after. -->
<div class="col-12">
<div class="card">
<div class="card-header"><h3 class="card-title" id="rd-act-title">Recent changes</h3></div>
<div class="card-body">
<p class="text-secondary" id="rd-act-empty">No change seen since the platform started.</p>
<div class="table-responsive" id="rd-act-table">
<table class="table table-sm">
<thead>
<tr>
<th id="rd-act-h-at">When</th>
<th id="rd-act-h-cause">Cause</th>
<th id="rd-act-h-item">Item</th>
<th id="rd-act-h-before">URLs before</th>
<th id="rd-act-h-after">URLs after</th>
<th id="rd-act-h-local">Here</th>
</tr>
</thead>
<tbody>
<tr id="rd-act-row">
<td class="rd-act-at text-nowrap">time</td>
<td class="rd-act-cause">page</td>
<td class="rd-act-item">pages:about</td>
<td class="rd-act-before">/about</td>
<td class="rd-act-after">/about</td>
<td class="rd-act-local">yes</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<p class="mt-3"><a id="rd-help" href="/__plugin/runway-demo/static/notes-help.html" target="_blank" rel="noopener">Help</a></p>
</div>
</body>
</html>
+108
View File
@@ -0,0 +1,108 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Decoupled logic of the demo's console screen. `rd` is the Screen record the controller put in the model; besides it,
the template uses only what a console screen may rely on: tenantSiteId, _csrf, ${@authz.may(..)} and #{..} messages.
`//` reaches nested elements of an iterated row. Form actions are constants in the markup (th:action and th:attr run
in a restricted context); every POST form's hidden .rd-csrf field carries the console session's CSRF token.
-->
<thlogic>
<attr sel="#rd-pretitle" th:text="${rd.site().displayName()}"/>
<attr sel="#rd-heading" th:text="#{runwaydemo.console.heading}"/>
<attr sel="#rd-flash" th:if="${runwayDemoFlash != null}"/>
<attr sel="#rd-flash-text" th:text="${runwayDemoFlash}"/>
<attr sel="#rd-error" th:if="${runwayDemoError != null}"/>
<attr sel="#rd-error-text" th:text="${runwayDemoError}"/>
<attr sel=".rd-csrf"
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
<!-- This plugin -->
<attr sel="#rd-about-title" th:text="#{runwaydemo.console.about}"/>
<attr sel="#rd-version-label" th:text="#{runwaydemo.console.version}"/>
<attr sel="#rd-version" th:text="${rd.pluginVersion()}"/>
<attr sel="#rd-built-label" th:text="#{runwaydemo.console.builtSpi}"/>
<attr sel="#rd-built" th:text="${rd.builtSpi()}"/>
<attr sel="#rd-running-label" th:text="#{runwaydemo.console.runningSpi}"/>
<attr sel="#rd-running" th:text="${rd.runningSpi()}"/>
<!-- Demo page (SitePages) -->
<attr sel="#rd-page-title" th:text="#{runwaydemo.console.page}"/>
<attr sel="#rd-page-desc" th:text="#{runwaydemo.console.page.desc}"/>
<attr sel="#rd-page-installed" th:if="${!rd.starterPath().isEmpty()}"/>
<attr sel="#rd-page-at" th:text="#{runwaydemo.console.page.at}"/>
<attr sel="#rd-page-link" th:href="${rd.starterPath()}"/>
<attr sel="#rd-page-path" th:text="${rd.starterPath()}"/>
<attr sel="#rd-page-form" th:if="${rd.starterPath().isEmpty()}"/>
<attr sel="#rd-page-install" th:text="#{runwaydemo.console.page.install}"/>
<!-- Notes (PluginSiteFiles) -->
<attr sel="#rd-notes-title" th:text="#{runwaydemo.console.notes}"/>
<attr sel="#rd-notes-count" th:text="${rd.noteCount()}"/>
<attr sel="#rd-notes-desc" th:text="#{runwaydemo.console.notes.desc}"/>
<attr sel="#rd-note-label" th:text="#{runwaydemo.console.note.new}"/>
<attr sel="#rd-note-add" th:text="#{runwaydemo.console.note.add}"/>
<attr sel="#rd-note-row" th:each="n : ${rd.notes()}"/>
<attr sel="#rd-note-row//.rd-note-origin" th:text="${n.origin()}"/>
<attr sel="#rd-note-row//.rd-note-text" th:text="${n.text()}"/>
<attr sel="#rd-note-row//.rd-note-at" th:text="${n.createdAt()}"/>
<!-- Showcase (ContentSource + ContentChanges) -->
<attr sel="#rd-show-title" th:text="#{runwaydemo.console.showcase}"/>
<attr sel="#rd-show-desc" th:text="#{runwaydemo.console.showcase.desc}"/>
<attr sel="#rd-show-live" th:if="${rd.showcaseText() != null}"/>
<attr sel="#rd-show-at" th:text="#{runwaydemo.console.showcase.at}"/>
<attr sel="#rd-show-path" th:text="${rd.showcasePath()}"/>
<attr sel="#rd-show-text" th:text="${rd.showcaseText()}"/>
<attr sel="#rd-show-unpublish-btn" th:text="#{runwaydemo.console.showcase.unpublish}"/>
<attr sel="#rd-show-none" th:if="${rd.showcaseText() == null}" th:text="#{runwaydemo.console.showcase.empty}"/>
<attr sel="#rd-show-label" th:text="#{runwaydemo.console.showcase.text}"/>
<attr sel="#rd-show-publish" th:text="#{runwaydemo.console.showcase.publish}"/>
<!-- Content surface (ContentCatalogView) -->
<attr sel="#rd-cat-title" th:text="#{runwaydemo.console.catalog}"/>
<attr sel="#rd-cat-total" th:text="${rd.catalogTotal()}"/>
<attr sel="#rd-check-label" th:text="#{runwaydemo.console.check.path}"/>
<attr sel="#rd-check-path" th:value="${rd.pathCheck() != null ? rd.pathCheck().path() : ''}"/>
<attr sel="#rd-check-btn" th:text="#{runwaydemo.console.check}"/>
<attr sel="#rd-check-result" th:if="${rd.pathCheck() != null}"/>
<attr sel="#rd-check-echo" th:text="${rd.pathCheck() != null ? rd.pathCheck().path() : ''}"/>
<attr sel="#rd-check-unsafe" th:if="${rd.pathCheck() != null and !rd.pathCheck().safe()}"
th:text="#{runwaydemo.console.check.unsafe}"/>
<attr sel="#rd-check-servable" th:if="${rd.pathCheck() != null and rd.pathCheck().servable()}"
th:text="#{runwaydemo.console.check.servable}"/>
<attr sel="#rd-check-reserved" th:if="${rd.pathCheck() != null and rd.pathCheck().safe() and !rd.pathCheck().servable()}"
th:text="#{runwaydemo.console.check.reserved}"/>
<attr sel="#rd-check-owner" th:if="${rd.pathCheck() != null and rd.pathCheck().ownerSlug() != null}"
th:text="#{runwaydemo.console.check.owner(${rd.pathCheck() != null ? rd.pathCheck().ownerSlug() : ''})}"/>
<attr sel="#rd-check-free" th:if="${rd.pathCheck() != null and rd.pathCheck().safe() and rd.pathCheck().ownerSlug() == null}"
th:text="#{runwaydemo.console.check.free}"/>
<attr sel="#rd-cat-h-source" th:text="#{runwaydemo.console.catalog.source}"/>
<attr sel="#rd-cat-h-id" th:text="#{runwaydemo.console.catalog.item}"/>
<attr sel="#rd-cat-h-path" th:text="#{runwaydemo.console.catalog.path}"/>
<attr sel="#rd-cat-row" th:each="c : ${rd.catalog()}" th:classappend="${c.own() ? 'table-active' : ''}"/>
<attr sel="#rd-cat-row//.rd-cat-source" th:text="${c.source()}"/>
<attr sel="#rd-cat-row//.rd-cat-id" th:text="${c.id()}"/>
<attr sel="#rd-cat-row//.rd-cat-path" th:text="${c.path()}"/>
<attr sel="#rd-cat-refresh-btn" th:text="#{runwaydemo.console.catalog.refresh}"/>
<!-- Recent changes (SiteEventListener) -->
<attr sel="#rd-act-title" th:text="#{runwaydemo.console.activity}"/>
<attr sel="#rd-act-empty" th:if="${rd.activity().isEmpty()}" th:text="#{runwaydemo.console.activity.empty}"/>
<attr sel="#rd-act-table" th:if="${!rd.activity().isEmpty()}"/>
<attr sel="#rd-act-h-at" th:text="#{runwaydemo.console.activity.at}"/>
<attr sel="#rd-act-h-cause" th:text="#{runwaydemo.console.activity.cause}"/>
<attr sel="#rd-act-h-item" th:text="#{runwaydemo.console.activity.item}"/>
<attr sel="#rd-act-h-before" th:text="#{runwaydemo.console.activity.before}"/>
<attr sel="#rd-act-h-after" th:text="#{runwaydemo.console.activity.after}"/>
<attr sel="#rd-act-h-local" th:text="#{runwaydemo.console.activity.local}"/>
<attr sel="#rd-act-row" th:each="a : ${rd.activity()}"/>
<attr sel="#rd-act-row//.rd-act-at" th:text="${a.at()}"/>
<attr sel="#rd-act-row//.rd-act-cause" th:text="${a.cause()}"/>
<attr sel="#rd-act-row//.rd-act-item" th:text="${a.item()}"/>
<attr sel="#rd-act-row//.rd-act-before" th:text="${#strings.listJoin(a.previousUrls(), ', ')}"/>
<attr sel="#rd-act-row//.rd-act-after" th:text="${#strings.listJoin(a.currentUrls(), ', ')}"/>
<attr sel="#rd-act-row//.rd-act-local" th:text="${a.local()} ? #{runwaydemo.console.yes} : #{runwaydemo.console.no}"/>
<attr sel="#rd-help" th:text="#{runwaydemo.console.help}"/>
</thlogic>
+9
View File
@@ -0,0 +1,9 @@
<div id="rd-card" class="card">
<div class="card-body">
<h3 id="rd-card-title" class="card-title">Runway Demo</h3>
<p id="rd-card-notes" class="mb-1">Notes: 0</p>
<p id="rd-card-spi" class="text-secondary small mb-2">SPI —</p>
<a id="rd-card-console" href="/__admin/runway-demo" class="btn btn-sm btn-primary">Open the demo screen</a>
<a id="rd-card-link" href="/demo/hello.txt" class="btn btn-sm btn-outline-primary">Try /demo/hello.txt</a>
</div>
</div>
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Decoupled logic for the tenant dashboard card (gated in plugin.yml by "runway-demo|manage-notes"). A fragment may rely
on tenantSiteId, _csrf, ${@<own bean>…}, ${@authz.may('…')} and #{…} messages — nothing else in the console's model —
so everything it shows comes from this plugin's own bean, ${@runwayDemoAdminModel…}. Zero Thymeleaf in the .html.
-->
<thlogic>
<attr sel="#rd-card-title" th:text="|Runway Demo · ${@runwayDemoAdminModel.siteName(tenantSiteId)}|"/>
<attr sel="#rd-card-notes" th:text="#{runwaydemo.card.notes(${@runwayDemoAdminModel.noteCount(tenantSiteId)})}"/>
<attr sel="#rd-card-spi" th:text="#{runwaydemo.card.versions(${@runwayDemoAdminModel.pluginVersion()},${@runwayDemoAdminModel.builtSpi()},${@runwayDemoAdminModel.runningSpi()})}"/>
<attr sel="#rd-card-console" th:text="#{runwaydemo.card.console}"/>
</thlogic>
+22
View File
@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Showcase</title>
<!-- Static preview head only — replaced at render by the TENANT's master head (the seam contract). -->
</head>
<body>
<header id="site-header">Site header (from the master at render)</header>
<main id="content">
<article class="rw-demo-showcase">
<h1 id="showcase-title">Showcase</h1>
<div id="showcase-body">
<p>The showcase text renders here.</p>
</div>
</article>
</main>
<footer id="site-footer">Site footer (from the master at render)</footer>
</body>
</html>
+16
View File
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
The body template of the demo's ContentSource (ContentRef.bodyTemplate = __plugin__/runway-demo/showcase). It may rely
on exactly the documented render model: ${master} (the tenant's master to wrap in), ${content.*} (id, sourceKey,
title, description, bodyHtml, attributes, updatedAt), ${locale} and ${urls[..]}. The tenant's chrome comes from the
master through its seams, by the ${master} VARIABLE (never a literal __plugin__/… or master name), so this file is
byte-identical for every tenant. bodyHtml is already escaped by DemoShowcaseSource, hence th:utext.
-->
<thlogic>
<attr sel="head" th:replace="~{${master} :: head}"/>
<attr sel="#site-header" th:replace="~{${master} :: #site-header}"/>
<attr sel="#site-footer" th:replace="~{${master} :: #site-footer}"/>
<attr sel="#showcase-title" th:text="${content.title}"/>
<attr sel="#showcase-body" th:utext="${content.bodyHtml}"/>
</thlogic>
+721
View File
@@ -0,0 +1,721 @@
# Writing a Runway plugin — the authoring guide
> **Audience:** a developer starting a **new Runway plugin from scratch**.
> **Scope:** the complete plugin contract of the Runway kernel at **SPI `1.0.0`** (Runway `1.0.0`; frozen —
> within `1.x` it changes only additively, see the kernel's `docs/SPI-STABILITY.md`) — the descriptor, every extension
> axis, the **service tier** through which a plugin reaches the kernel, the `POST`/CSRF rules, the build, the
> install, how to verify, and the traps. Everything here is grounded in the kernel as built and verified against the
> packaged host jar; a gap is called a gap.
>
> **A plugin links only the Runway SPI** (`mx.quest.runway.spi.*`). The kernel **blocks** a plugin that links its
> internal classes, breaks the Spring-context rules (§5) or declares no `requiresSpi` floor of at least `0.4.0` (§4)
> — the plugin is skipped with the reason in the log and on the Plugins screen; the platform still boots. Every
> first-party plugin under `plugins/` is on the service tier; this guide describes only that contract.
>
> The **`demo`** plugin (`../demo/`, walkthrough in `../demo/docs/DEMO-PLUGIN.md`) is the worked reference: it uses
> every axis and every service once, where a real plugin would, with a comment saying when to use it. Copying
> `demo/` and deleting what you don't need is the fastest correct start. The kernel's own developer guide is
> [`docs/PLUGIN-DEVELOPMENT.md`](../../docs/PLUGIN-DEVELOPMENT.md) at the root of the repository.
---
## 1. What a Runway plugin *is*
- **A folder**, deployed under the host's external tree at `external/plugins/<id>/`, containing:
- `plugin.yml` — the declarative descriptor (required, at the folder root);
- one **thin** `*.jar` — only *your* classes (never the kernel, never Spring; see §3);
- optional `lib/` (bundled third-party jars, scanned one level deep), `static/`, `templates/`, `i18n/`.
- **Trusted first-party code, not a sandbox.** Plugin jars load into one shared child classloader whose parent is the
application classloader; your `mainClass` `@Configuration` is registered into the host Spring context *before*
refresh, so your beans wire like the kernel's — and receive the kernel's **services** (§7) by ordinary injection.
- **Restart-to-install, degrade-don't-crash.** Install / upgrade / remove = change the folder and **restart** (no hot
reload). A malformed, disabled or broken plugin is logged and skipped; a plugin that breaks the boot is
**quarantined** (the kernel writes `external/plugin-quarantine/<id>.yml`, relaunches, and the next boot shows it
Blocked); the platform always comes up.
- **Your package MUST live outside `mx.quest.runway`** (e.g. `com.acme.myplugin`): the host would scan it, and the
kernel treats a plugin class under `mx.quest.runway` as host linkage.
---
## 2. Prerequisites
- **JDK 25**.
- **Maven**.
- **`mx.quest:runway-spi` and `mx.quest:runway-spi-testkit` in your `~/.m2`**, at the version of the kernel you build
for (`ls ~/.m2/repository/mx/quest/runway-spi/`). That is all of Runway a plugin compiles against. Their Maven
version is the **kernel's release version**, not the SPI level: `1.0.0` carries SPI `1.0.0` (the jar's
`RunwaySpi.VERSION` says which), and a later kernel such as `1.0.1` may carry the same SPI.
- **Where those jars come from: the kernel release's assets.** No Maven repository serves them. Every kernel
release on the releases page (<https://g.quest.mx/quest/runway/releases>)
attaches, for its version `<ver>`, `runway-spi-<ver>.jar`, `runway-spi-testkit-<ver>.jar`, their `-sources.jar`
and a standalone pom for each (no parent, versions resolved — the testkit's names `runway-spi` at the same
version), all listed in that release's `SHA256SUMS`. Install them once per kernel version you build against:
```sh
V=1.0.0
# Download the six runway-spi* files and SHA256SUMS from the v$V release page.
sha256sum -c --ignore-missing SHA256SUMS # each of the six must print OK; fails if none was verified
mvn install:install-file -Dfile=runway-spi-$V.jar -DpomFile=runway-spi-$V.pom \
-Dsources=runway-spi-$V-sources.jar
mvn install:install-file -Dfile=runway-spi-testkit-$V.jar -DpomFile=runway-spi-testkit-$V.pom \
-Dsources=runway-spi-testkit-$V-sources.jar
```
**Do not skip the checksum:** a download that returns an HTML page (a sign-in or error page) with HTTP 200 instead
of the asset passes `curl -f`, and `install:install-file` would install it as a "jar". **Install with the pom**
(`-DpomFile`), not `-DgroupId/-DartifactId`, so Maven knows the testkit needs `runway-spi`. A local build of the
kernel's source puts the same artifacts in `~/.m2` too — but a release of your plugin is built
against a **released** kernel version, never the kernel's `-SNAPSHOT` (§3, point 4). The kernel's
`docs/PLUGIN-DEVELOPMENT.md` §3, *Getting the jars*, says the same.
---
## 3. The project (pom.xml)
A plugin is an ordinary Maven `jar` project:
1. **Depend on `runway-spi` (`provided`) and `runway-spi-testkit` (`test`) — never on `runway-app`, in any scope.**
A host import then does not compile, which is the point. `provided` says what is true: the kernel supplies the
SPI at runtime and the plugin never ships it (the kernel docs recommend the same). The plugins in this repo
declare it with the default `compile` scope, which is harmless here: `runway-spi` is resolved parent-first at
runtime, and their zips are built from an explicit file list that never includes a dependency jar.
2. **Platform libraries are `provided`.** The host supplies Spring Framework 7, Spring Boot 4, Spring MVC, Spring
Security, Thymeleaf, Jackson 3 (incl. `jackson-dataformat-yaml`) and the Jakarta EE 11 APIs; the kernel's MAJOR
line pins their MAJOR lines. Compile against the ones you use; never bundle them (a second copy is a second
`Class` identity, and by-type collection of your beans silently breaks).
3. **No `spring-boot-maven-plugin` repackage** — `mvn package` produces a thin jar of only your classes. Inherit
`spring-boot-starter-parent` to get the host's managed versions.
4. **Reproducible builds**: set `project.build.outputTimestamp` (bump it per release) so two builds are
byte-identical. Build a release against a **released** kernel artifact, never a `-SNAPSHOT`: a snapshot changes
under the same version, and so does your jar — compile-time constants such as `RunwaySpi.VERSION` are copied into
your classes, and the jar embeds your `pom.xml` (`META-INF/maven/…`). The same holds for any pom edit, the kernel
version included: a rebuild with it no longer matches the published archive, so it ships as a new version.
```xml
<parent>
<groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId>
<version>4.0.6</version><relativePath/>
</parent>
<groupId>com.acme</groupId><artifactId>runway-plugin-myplugin</artifactId><version>1.0.0</version>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.outputTimestamp>2026-10-18T00:00:00Z</project.build.outputTimestamp>
<runway.version>1.0.0</runway.version> <!-- the kernel RELEASE you build against (SPI 1.0.0) -->
</properties>
<dependencies>
<dependency><groupId>mx.quest</groupId><artifactId>runway-spi</artifactId><version>${runway.version}</version></dependency>
<dependency><groupId>mx.quest</groupId><artifactId>runway-spi-testkit</artifactId><version>${runway.version}</version>
<scope>test</scope></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId>
<scope>provided</scope></dependency>
<!-- only what you use, all provided: spring-webmvc (a @ConsoleScreen controller), spring-security-core
(@PreAuthorize), tools.jackson.dataformat:jackson-dataformat-yaml (your own files), … -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope></dependency>
</dependencies>
<build>
<finalName>runway-plugin-myplugin</finalName>
<!-- an antrun step that assembles target/<id>/ and target/<artifactId>-<version>.zip — copy demo/pom.xml.
The artifactId is runway-plugin-<id> (here the id is myplugin): the release asset is
runway-plugin-<id>-<version>.zip. -->
</build>
```
(A plugin release pins a **released** kernel in `runway.version` — one published on the kernel's releases page —
never a `-SNAPSHOT` (point 4). Moving the pin is a new plugin version; a plugin that needs nothing new from the kernel
keeps its pin until its next release. When you copy a first-party pom, `demo/pom.xml` included, set `runway.version`
to the release you build against.)
---
## 4. The descriptor (plugin.yml)
Parsed with unknown keys ignored (forward/backward compatible). The **install folder name MUST equal `id`**.
```yaml
id: myplugin # REQUIRED. Path-safe (/[A-Za-z0-9][A-Za-z0-9._-]*/). == install-dir name.
name: My Plugin # REQUIRED. Shown in the management UI.
version: 1.0.0 # REQUIRED. STRICT plain MAJOR.MINOR.PATCH — no qualifiers.
mainClass: com.acme.myplugin.MyPluginConfig # the @Configuration; omit for a code-less library/asset plugin.
# The LOWEST SPI level whose types you use (the newest type decides): ">=0.4.0" PluginSettings/PluginInfo/
# PluginLifecycle; ">=0.5.0" PluginSiteFiles, Sites, RequestContext, AccessCheck, Messages, SitePages, anonymous
# routes, siteData; ">=0.6.0" ContentCatalogView, ContentChanges, SiteEventListener, @ConsoleScreen; ">=1.0.0"
# HeadContext.origin(). All four are 1.x floors: a plugin declaring any of them loads on every 1.x kernel. A kernel
# below it BLOCKS the plugin with a reason. A plugin with a mainClass MUST declare a floor >= 0.4.0: without one it is
# blocked as "built for the pre-1.0 plugin contract" (a code-less library plugin is exempt).
requiresSpi: ">=0.6.0"
enabled: true # optional (default true) — the operator's disable switch.
essential: false # honored ONLY for kernel security-floor ids on the allowlist ('protection').
requires: [ other >= 1.2.0 ] # optional. Forms: `id`, `id >= v`, `id == v` (single space). Never an essential id.
conflicts: [ legacy ] # optional. The declaring plugin steps aside if a listed id is installed and enabled.
# Personal data in your per-site folder (sites/<id>/plugins/<pluginId>/): left OUT of a site's transfer copy and
# listed in its manifest; full backups keep it. A trailing "/" names a folder. Rule: any file holding visitor or
# user input is personal.
siteData:
personal:
- submissions.tsv
# Grantable control points, namespaced <id>|<declId>. defaultRoles: leave EMPTY — a control point starts ungranted;
# administrators hold it via the wildcard tier and a superadmin grants it explicitly. A reserved/master tier in
# defaultRoles is a hard startup failure. The reserved id `settings` gates the per-site settings form.
permissions:
- { id: settings, realm: tenant, label: myplugin.perm.settings, defaultRoles: [] }
- { id: manage, realm: tenant, label: myplugin.perm.manage, defaultRoles: [] }
# App-level settings (PLATFORM concerns): bound as runway.plugin.<id>.<key> from external/plugin-settings/<id>.yml,
# applied on RESTART, read through your own @ConfigurationProperties bean (§7.2).
settings:
- { key: some.flag, type: boolean, default: true, label: myplugin.settings.flag }
# Per-site settings (tenant-owned BEHAVIOUR): sites/<siteId>/plugins/<id>.yml, applied IMMEDIATELY, read with
# PluginSettings (§7.2). `settings` gates the form.
siteSettings:
- { key: enabled, type: boolean, default: true, label: myplugin.settings.enabled }
- { key: style, type: enum, default: info, range: "info,warning,danger", label: myplugin.settings.style }
- { key: apiKey, type: secret, label: myplugin.settings.apiKey }
# Per-placement widget settings, keyed by the ContentWidget key(): sites/<siteId>/widget-instances.yml; the values
# reach the widget as WidgetView.config(). Keep defaults in code.
widgetSettings:
myhero:
- { key: heading, type: string, label: myplugin.widget.heading }
# Console menu entry. `permission` is the FULL key; visibility is UX only. `icon`: a Font Awesome class.
menu:
- { realm: tenant, region: menu, order: 60, label: myplugin.menu.link,
path: "/__admin/myplugin", permission: "myplugin|manage", icon: "fa-solid fa-feather-pointed" }
# Dashboard card: `fragment` resolves to __plugin__/<id>/<fragment> = templates/<fragment>.html.
dashboardCards:
- { realm: tenant, order: 20, fragment: dashboard, permission: "myplugin|manage" }
```
Also understood: `settingGroups` (titled sections of the settings forms) and `helpUrl` — see the kernel's
PLUGIN-DEVELOPMENT §5.
### 4.1 Setting types (and their traps)
| `type` | Java value | Notes / trap |
|-----------|-------------------|--------------|
| `string` | `String` | trimmed; blank ⇒ null. Also the fallback for an unknown/misspelled `type` (silent!). |
| `secret` | `String` | stored **encrypted** `ENC(...)`. Per-site: absent from `PluginSettings.site()`, read in clear only with `PluginSettings.secret(site, key)`. App-level: the property map carries the ciphertext. |
| `text` | `String` | **verbatim** — NOT trimmed, blank NOT nulled (whitespace significant). The only such type. |
| `int` | `Long` | `range: "min..max"` / `"min.."` / `"..max"` enforced by the form. Read with `SettingsView.integer(key, fallback, min, max)` to clamp a hand-edited value too. |
| `decimal` | `BigDecimal` | **`range` is IGNORED** for decimal. Non-numeric ⇒ form error. |
| `boolean` | `Boolean` | truthy iff value ∈ {`true`,`on`,`yes`,`1`} (case-insensitive). |
| `enum` | `String` | `range: "a,b,c"` or `"a|b|c"`; value must be a member. |
| `list` | `List<String>` | split on comma **or** newline; trimmed; empties dropped. |
---
## 5. The mainClass @Configuration
Register **every** bean **explicitly** with `@Bean` — no `@ComponentScan` of your own package. The kernel's services
(§7) arrive as `@Bean` method parameters:
```java
package com.acme.myplugin; // OUTSIDE mx.quest.runway
@Configuration(proxyBeanMethods = false)
public class MyPluginConfig {
@Bean
@ConfigurationProperties("runway.plugin.myplugin") // app-level settings (not @EnableConfigurationProperties)
public MyAppProps myPluginAppProps() { return new MyAppProps(); }
@Bean
public MyWidget myPluginWidget(PluginSettings settings, Messages messages) { // plugin-scoped + kernel singleton
return new MyWidget(settings, messages);
}
@Bean
public MyEndpoints myPluginEndpoints(AccessCheck access, PluginSiteFiles files) {
return new MyEndpoints(access, files);
}
}
```
The kernel checks these rules **before and after refresh**. Before refresh a violation **blocks** the plugin
(`plugin '<id>' is blocked: breaks the plugin rules for Runway's shared Spring context (SPI 1.0): bean name '…' does
not start with '<prefix>' …`); one that only shows after refresh (a bean the pre-check cannot see) **quarantines** it
(§1) with the same reason:
- **Bean names start with your id in lowerCamelCase** (`my-plugin` → `myPlugin…`). Plugins share one bean namespace
with the kernel and each other. The host registers `mainClass` itself as `plugin:<id>`. Use the method name as
the bean name. `@EnableConfigurationProperties(X.class)` names its bean `<prefix>-<class name>` and breaks the rule
— declare the properties bean with `@Bean @ConfigurationProperties(...)` instead. Templates follow the names
(`${@myPluginAdminModel…}`).
- **Allowed Spring surface:** SPI implementations and plain beans; `@Controller`s whose every mapping lies under
`/__admin/<id>` or `/__app/<id>`; `@ControllerAdvice` restricted to your own packages, types or annotations.
**Not allowed:** servlet `Filter`s / `FilterRegistrationBean`s (§6.6), `SecurityFilterChain`s,
`BeanPostProcessor`s / `BeanFactoryPostProcessor`s, an unrestricted `@ControllerAdvice`.
- **No host linkage.** At startup the kernel reads the constant pool of every class in your jars and **blocks** the
plugin, before wiring, for any reference to an `mx.quest.runway` class outside `mx.quest.runway.spi` or a class of
yours under `mx.quest.runway` (`plugin '<id>' linkage scan: uses Runway's internal classes, which the plugin
contract (SPI 1.0) does not allow (links N kernel classes: …)`), and for a reference to an **SPI type this kernel
does not have** (`… needs SPI types this Runway does not have: …`) — then `plugin '<id>' is blocked: …`.
- **Collected contributions are plain `@Bean`s — never `@Primary`.** `@Primary` is only for the singleton kernel
seams the essential `protection` plugin arms. Return the **concrete** class from a `@Bean` method, so Spring sees
every interface it implements before creating it (a class that is both a `ContentSource` and a
`SiteEventListener` is collected as both).
---
## 6. The extension axes
All live in `mx.quest.runway.spi`; their immutable model records in `mx.quest.runway.spi.model`. Each has a
**`String key()`** that must be **unique and namespaced** (`"myplugin/thing"`): a blank or colliding plugin key is
**refused** (logged as an ERROR naming both sides, the plugin marked degraded; its other contributions load). Each
has a `default Capabilities capabilities()` — lowercase-dotted flags the host may branch on. Implementations are
**functions of their immutable inputs plus the services they were given**: thread-safe, no request objects, return
plain values.
**Containment.** A `RuntimeException`/`LinkageError` from your code on a request path is caught, logged (the first
time with the stack, then at most once a minute) and counted on the plugins screen: a head or widget failure yields
empty output and the page is served `no-store`; a quality check yields one `WARNING` `check.failed`; an endpoint
answers `500` `no-store`; a listener or lifecycle callback is skipped. `BackupParticipant.export` is **not**
contained: its failure fails the backup.
### 6.1 `HeadContributor` — edge `<head>` injection
```java
String key();
String render(HeadContext ctx); // "" (never null) for nothing
default List<String> headInputs(String siteId) // site-relative files you read: "plugins/<id>.yml"
```
Collected (`@Order`-honored), spliced before `</head>` on every rendered page — no tenant template edit. Order after
the kernel's own (SEO `@Order(100)`, icons `@Order(90)`) with e.g. `@Order(200)`. You own HTML escaping. Head markup
is spliced *after* the page `ETag` is computed: list the per-site files you read in `headInputs` so a change to them
moves the validator. Emit plain `<script src>` tags — the kernel stamps the CSP nonce. For an absolute URL (a
JSON-LD `@id`, an `og:url`) use **`HeadContext.origin()`** (SPI `1.0.0` — declare `requiresSpi: ">=1.0.0"`): the
trusted `scheme://host[:port]` the page is served under — the site's base URL, or, on a host-less site, the request's
origin as the trusted-proxy gate left it. Never read the `Host` header.
### 6.2 `ContentWidget` — a body-content render block
```java
String key(); // the <type> half of data-widget="<type>/<instance>"
RenderFragment render(WidgetView view); // RenderFragment.of(html) / RenderFragment.empty()
```
Rendered wherever a page carries `<div id="x" data-widget="<key>/<instance>">` (the `id` **and** `data-widget` on the
**same** element). `WidgetView` gives `site()`, `page()`, `locale()`, `instanceId()`, `isChrome()`, `config()` (the
placement's `widgetSettings:` values; absent key = your default), `query()` (first value per name — read a
`?sent`-style flag) and `path()` (the public path being rendered — use it for a return path, never the slug). A
widget only *reads*; storing a submission is an endpoint's job.
### 6.3 `EndpointContributor` — HTTP routes (servlet-free)
```java
String key();
List<Route> routes(); // new Route("GET", "/my/path", Realm.TENANT, SurfacePosture.discoverable())
RouteResponse handle(RouteRequest r);
```
Dispatched on a site's public host. A route is an **exact** path (`*`, `{`, `}` reserved), realm `TENANT`, and must
avoid the kernel's surface (`/__app`, `/__admin`, `/__plugin`, `/__assets`, `/__preview`, `/__csp-report`,
`/__ui-lang`, `/__health`, `/actuator`, `/app/`, `/login`, `/logout`, `/error`, `/forgot-password`, `/reset`); a
route that breaks a rule is refused on its own. `RouteRequest` (frozen) carries:
- `site()` (a `SiteView`), `locale()` (negotiated: `?lang` → the site's language cookie → `Accept-Language` → site
default; always a site locale), `method()`, `path()`;
- `query()` — the URL query string only; `form()` — the fields of an `application/x-www-form-urlencoded` body;
`param(name)` — query first, then form (`Optional`);
- `headers()` — **lowercase** names (lookups ignore case); forwarded headers never reach you;
- `clientIp()` — the client address **after** the kernel's trusted-proxy gate (use it for rate limits; never read an
`X-Forwarded-For`); `origin()` — `scheme://host[:port]` after the same gate (absolute URLs when the site has no base
URL); `body()`.
Answer with `RouteResponse.text(...)`, `RouteResponse.notFound()` or `new RouteResponse(status, headers, bytes)`.
There is no principal in the request; the dispatch runs inside the security chain, so check a permission with
`AccessCheck` (§8).
**`POST` routes and CSRF** (the full rules are §8.1):
- A **`GET`** route must not change anything. Anything that changes state is a `POST`.
- An ordinary (non-anonymous) `POST` route is **CSRF-checked** by the tenant chain: the caller must send the
session's token. From your console fragment that is a `<form method="post">` with a hidden field bound to
`${_csrf}` (§8.1). `form()` carries **every** body field, whether the token travels as that form field or in
the `X-CSRF-TOKEN` header (the `_csrf` field itself is in `form()` too; ignore it), and never a query-string value
of the same name. Both a route like this and a `@ConsoleScreen` controller (§7.11) can take an operator's form fields.
- A **public form any visitor may submit without an account** (contact, feedback, newsletter) declares an
**anonymous** route: `Route.anonymousPost("/my/submit", SurfacePosture.safeDefault())` (§8.1).
### 6.4 `PageQualityCheck` — content/SEO checks
```java
String key();
List<Finding> inspect(PageView page); // Finding.info/warning/error(code, message); empty list = clean
```
Never mutates. **Severity has consequences:** on a site set to *Enforced* or *Reviewed* any `ERROR` refuses
publishing; keep `ERROR` for something clearly broken the author can fix, `WARNING` for advice. The `PageView` may be
a candidate not yet live — judge only the view. `Finding.code()` is looked up as the console message
`quality.<code>` (ship it in your `i18n/` to localize).
### 6.5 `BackupParticipant` — only for data outside the site folder
```java
String key();
void export(BackupWriter out, SiteRef site) throws IOException;
void importInto(BackupReader in, SiteRef site) throws IOException;
```
**You almost certainly do not need it.** Data you keep with `PluginSiteFiles` (§7.3) lives in the site folder,
which full backups already carry. The axis stays for data a plugin keeps elsewhere (none of the first-party plugins
in 1.0). If you use it: `importInto` must be idempotent and tolerate a missing entry; read and write whole byte arrays
(never let a serializer auto-close the archive stream); a failing `export` fails the whole backup.
### 6.6 Servlet filters — not a plugin seam
**A plugin cannot contribute a servlet filter.** Servlet filters are outside the Runway 1.0 plugin contract: a
filter needs servlet types the SPI does not carry, runs on every request of every site ahead of the kernel's own
handling, and no feature plugin needs one. The kernel's `FilterContribution` and its `FilterBand` placement stay
kernel concepts (they place the kernel's filters and the essential `protection` plugin's floor). A plugin `Filter`,
`FilterRegistrationBean` or `FilterContribution` bean blocks the plugin (§5). To shape a
response, use an axis: `<head>` markup (§6.1), a widget (§6.2), an endpoint (§6.3). (A separate
`runway-spi-servlet` module could add a filter seam in a later 1.x if a real consumer appears.)
### 6.7 `ContentSource` — routable content ("virtual pages")
```java
String key(); // stable; namespaces ids
List<ContentRef> enumerate(SiteView site); // published-only, METADATA-ONLY, cheap
ContentBody body(SiteView site, String id, Locale locale); // lazy — only for a 200 render
default Optional<ContentRef> resolve(SiteView, String path, Locale); // override with an O(1) probe
default String indexableText(SiteView, String id, Locale); // HTML/plain text for search (CAP_INDEXABLE_TEXT)
default Capabilities capabilities();
```
Your plugin serves **whole pages at site URLs** (blog entries, product pages) as peers of kernel pages: the
locale-dispatch ladder, the tenant's master chrome around your body template, `<head>` treatment, `ETag`/`304`,
**sitemap.xml + llms.txt**, by-id links (`${urls['<key>:<id>']}`) and — with `CAP_INDEXABLE_TEXT` — on-site search.
The host re-filters your output fail-closed (unpublished items, unsafe paths and reserved URLs are dropped).
- **`enumerate()` never reads bodies** and returns published content only — it runs on anonymous requests.
- **Announce every change with `ContentChanges.changed(siteId, key, id)`** (§7.9) after each mutation (`id` `null`
= the whole corpus). It evicts routing, the listing, sitemaps and search on every node.
- **`updatedAt` is load-bearing for HTTP caching**: the render `ETag` folds the ref's metadata, never the body —
bump `updatedAt` whenever what `body()` returns changes.
- **If you cache, drop it from a `SOURCE`-phase `SiteEventListener`** (§7.10): on your own `CONTENT` changes (a
replay from another node is how this node learns), on wholesale lifecycle events (`DELETED`, `RESTORED`), on your
own settings changes if they reshape URLs. The kernel runs sources before consumers and re-evicts in between.
- **`resolve()` must be cheap** — keep an in-memory `path|lang → id` index (printable `|`, never a control char).
- **Validate a custom prefix with `ContentCatalogView.servablePath`, and before publishing at a path ask
`pageAt`** (§7.8): a real page always wins a contested URL.
- **The body template** (`ContentRef.bodyTemplate`, `__plugin__/<id>/<name>`) may rely on exactly: `${master}` (the
master to wrap in — pull the chrome with `~{${master} :: head}`, `#site-header`, `#site-footer`, never a literal),
`${content.*}` (`id`, `sourceKey`, `title`, `description`, `bodyHtml`, `attributes`, `updatedAt`), `${locale}`,
`${urls[…]}`. The file must be byte-identical for every tenant.
- **Read only your own data**: your per-site folder (`PluginSiteFiles`) and your per-site settings.
---
## 7. The service tier — how a plugin reaches the kernel
Package `mx.quest.runway.spi.service`: narrow interfaces the **kernel implements** and your plugin **receives by
ordinary Spring injection**. They are the only way to reach what the host's own classes hold; a plugin never injects
those classes themselves (`SitePluginConfigService`, `SecretCipher`, `StorageLayout`/`SiteFileStore`, `SiteResolver`,
`AuthzExpressions`, `SiteAwareMessageSource`, `PageWriteService`, `ContentCatalog`, the host's Spring events,
`OperatorShellModel`, `RunwayPlugin`/`PluginContext`) — the linkage scan blocks a jar that links them (§5).
Rules for all: no method returns `null`; an unsafe site id, slug or path throws `IllegalArgumentException` before any
I/O (a well-formed unknown id is not an error); every service is thread-safe; enums may grow in a MINOR release (give
a `switch` a `default`).
### 7.1 How you get one, and the binding
| Kind | Services | Bound to |
|---|---|---|
| **plugin-scoped** | `PluginSettings`, `PluginSiteFiles`, `ContentChanges`, `PluginInfo` | **your plugin, by the jar the injecting class was loaded from** — no method takes a plugin id, so you can only reach your own settings, files and sources |
| **kernel singletons** | `Sites`, `RequestContext`, `AccessCheck`, `Messages`, `SitePages`, `ContentCatalogView` | — |
| **callbacks you implement** | `PluginLifecycle`, `SiteEventListener` | collected by type; matched to your plugin by jar |
Inject a plugin-scoped service into a class from your **own top-level jar** (a `@Bean` parameter, a constructor, a
field, or an `ObjectProvider<…>`). Injection **fails at startup** from a class in your `lib/` folder (a library is
shared by every plugin that bundles it), from kernel code, and through a bare `getBean(PluginSettings.class)`.
### 7.2 `PluginSettings` — your per-site settings (0.4.0)
```java
SettingsView site = settings.site(siteId); // defaults overlaid by saved values; secrets absent
boolean on = site.bool("enabled", true);
long n = site.integer("interval", 5, 1, 60); // clamped
Optional<String> key = settings.secret(siteId, "apiKey"); // a type: secret value in clear (ENC decrypted)
```
Precedence: saved value › descriptor `default` › your code fallback (which matters only for undeclared keys — keep
them equal). Accessors never throw: a value that does not parse yields the fallback. A save applies **immediately**
on every node. Nested structures: parse `values()` yourself. **Three settings surfaces:**
- **App-level (`settings:`)** — platform concerns, `runway.plugin.<id>.*`, applied on **restart**, read through your
own `@ConfigurationProperties` bean (§5). A `secret` there is ciphertext.
- **Per-site (`siteSettings:`)** — `PluginSettings`; react to a save with `SiteEventListener.onSettingsChanged`.
- **Per-placement (`widgetSettings:`)** — nothing to read: they arrive as `WidgetView.config()`.
### 7.3 `PluginSiteFiles` — your per-site data, and personal data (0.5.0)
```java
Optional<String> text = files.readText(siteId, "notes.yml");
files.writeText(siteId, "notes.yml", yaml); // atomic; creates parent folders
files.delete(siteId, "x.tsv"); files.deleteTree(siteId, "entries/old"); files.list(siteId, ""); files.stat(...);
```
Your folder `sites/<id>/plugins/<yourId>/`: inside the site, so full backups carry it and a deleted site takes it
along. Paths are relative with `/`; `..`, empty segments, backslashes and symlink escapes are refused. One write is
capped (`runway.plugins.site-files.max-write-bytes`, 16 MiB); `readText` refuses a bigger file. Each write is atomic
but a **read-modify-write is yours to serialize** (a lock per site). A write for a site whose folder does not exist
fails. YAML/JSON go through your own Jackson (a platform library) — read leniently (unknown keys ignored) so a later
version can add fields. Writing a file announces nothing: if it shapes routable content, call `ContentChanges`.
**Declare personal data** in `siteData.personal` (§4): any file holding visitor or user input.
### 7.4 `Sites` and `RequestContext` (0.5.0)
- `Sites.find(siteId)` → `Optional<SiteView>` (suspended sites included), **off-request too**: the way a listener, a
background task or a console fragment (which only has `tenantSiteId`) gets a site's name, locales or base URL.
- `RequestContext.site()` → the site the **current request** is bound to (a public page or the tenant console);
**empty on the application console** and off a request. A console screen uses it to learn which site it manages;
an endpoint does not need it (`RouteRequest.site()`).
### 7.5 `AccessCheck` (0.5.0)
`access.may("myplugin|manage")` (or a kernel permission: `may("EDIT_PAGES")`) for the current principal, in its realm
and tenancy; fail-closed. The same bean is `@authz` in `@PreAuthorize("@authz.may('…')")` and in templates
(`${@authz.may('…')}`). See §8.
### 7.6 `Messages` (0.5.0)
- `messages.site(siteId, locale, code, fallback, args…)` — **visitor-facing** text: the site's own bundle first,
then every plugin's `i18n/` (add-only), in the visitor's locale. Works off-request.
- `messages.console(code, fallback, args…)` — **console** text in the **operator's** UI language (the fallback off a
request).
With arguments the text is a `MessageFormat` pattern (write `''` for an apostrophe). A `null` fallback yields the code.
### 7.7 `SitePages` — install a starter page (0.5.0)
```java
InstallResult r = pages.install(siteId, new StarterPage(slug, "/contact", Map.of("en", "Contact"), html, logic, false));
Optional<String> where = pages.pathOf(siteId, slug); // any state; follows an operator's move
```
Idempotent, **never overwrites**, and follows the site's editorial level: `PUBLISHED`, `PENDING_REVIEW` (Reviewed
site, no `APPROVE_PAGES`), `DRAFT_BLOCKED` (the quality checks blocked it; `blocking()` has the findings),
`ALREADY_EXISTS`. Tell the operator which, in words, with a `default` branch. **Check the caller's permission first**
(`AccessCheck`) — `SitePages` does not. An unsafe or reserved path throws `IllegalArgumentException`; a path another
page serves, an unknown site or a write failure throws `IllegalStateException` (no stray draft is left). The page's
logic pulls the chrome through `${master}`.
### 7.8 `ContentCatalogView` — the site's published content surface (0.6.0)
```java
List<CatalogEntry> entries = catalog.entries(siteId); // pages ("pages" source; id = slug) + every source's items
String path = entry.pathFor(locale); // the URL to link in that locale (never builds one yourself)
Optional<String> owner = catalog.pageAt(siteId, "/blog", locale); // the published page that owns a path
boolean ok = catalog.servablePath(siteId, "/blog"); // may content live there at all?
catalog.refresh(siteId); // a manual reindex only
```
What a sitemap, an llms.txt or a search index reads. Each `CatalogEntry` carries its `ContentRef`, one
`LocalizedUrl(locale, path, canonical)` per available locale (`absolute(origin)`, `alternate(origin)`) and an
`xDefaultPath` — computed by the same code as the page `<head>`, so they cannot disagree. Cached per site, evicted
by every change that can reshape it (30-second backstop). Metadata only — safe on anonymous paths.
### 7.9 `ContentChanges` — announce that your content changed (0.6.0)
`changes.changed(siteId, yourSourceKey, id)` after every mutation of content your `ContentSource` serves (`id`
`null` = the whole corpus). Call it **after** the write, outside your own locks (listeners run on your thread before
it returns). Refused (`IllegalArgumentException`) for a source key your plugin does not contribute, and
(`IllegalStateException`) from inside a `SiteEventListener` callback. It does not refresh HTTP validators — bump
`updatedAt`.
### 7.10 `SiteEventListener` — react to changes (0.6.0)
```java
public class MyIndex implements SiteEventListener {
@Override public Phase phase() { return Phase.CONSUMER; } // SOURCE if you are a content source
@Override public void onSiteLifecycle(SiteLifecycleEvent e) { if (e.wholesale()) drop(e.siteId()); }
@Override public void onSettingsChanged(SettingsChange c) { … } // YOUR plugin's settings only
@Override public void onCatalogChanged(CatalogChange c) { … } // PAGE, CONTENT, SITE, SETTINGS
}
```
- **Order:** all `SOURCE` listeners, then the kernel evicts its listing again, then all `CONSUMER`s; per listener and
event: lifecycle, settings, catalog.
- **URLs before and after:** a `PAGE`/`CONTENT` change with an id carries `previousUrls` (where the item was — a
deleted item still names its old address) and `currentUrls` (where it is now; always empty for `SOURCE`
listeners). A notifier submits the union.
- **`local`:** `false` for a change replayed from another node. Do external side effects (an e-mail, an IndexNow
POST, a file append) only when `local`; evict caches either way.
- **Guarantees:** every kernel cache is already evicted; no host lock is held (calling any service is safe); a throw
is logged and counted, never propagated. **Duty:** evict, record or enqueue on the writer's thread — slow work goes
to your own executor. Changes nobody announces and changes before startup completes are not delivered.
### 7.11 `@ConsoleScreen` — your own screen in the console (0.6.0)
```java
@Controller
@ConsoleScreen
@RequestMapping("/__admin/myplugin")
public class MyAdminController {
@GetMapping
@PreAuthorize("@authz.may('myplugin|manage')")
public String list(Model model) {
model.addAttribute(ConsoleScreen.CONTENT_TEMPLATE, "__plugin__/myplugin/admin-list");
model.addAttribute(ConsoleScreen.PAGE_TITLE_KEY, "myplugin.admin.title");
return ConsoleScreen.LAYOUT_VIEW; // "operator/op-layout"
}
}
```
The kernel fills the shell (topbar, menus, language switcher, footer) — no `@ControllerAdvice`, no host class. Every
mapping under `/__admin/<id>` (tenant console) or `/__app/<id>` (application console), each handler gated with
`@authz.may(…)`, every state change a CSRF-checked `POST` (§8.1). Use `RequestContext.site()` for the managed site.
The content template's root is `#content`; it may rely on `tenantSiteId`, `_csrf`, `${@<own bean>…}`,
`${@authz.may('…')}`, `#{…}`, and what your controller put in the model — nothing else of the shell's model is
promised (render your own flash attribute rather than relying on the shell's).
### 7.12 `PluginInfo` and `PluginLifecycle` (0.4.0)
`PluginInfo(id, version, installDir)` is your identity — injectable anywhere, and handed to
`PluginLifecycle.started(self)`. `started` runs once the platform is up, in plugin load order; `stopping()` at
shutdown, reverse order, only if `started` returned. Both block the host's thread: keep them short. Use them to start
and stop your own executor, open an index, warm a cache. `RunwaySpi.VERSION` is the SPI you **built against** (a
compile-time constant); `RunwaySpi.runtimeVersion()` the kernel's you **run on**.
### 7.13 Testing with `runway-spi-testkit`
In-memory fakes with the kernel's input rules, so plugin tests need no kernel and no Spring Boot:
| Fake | For |
|---|---|
| `FakePluginSettings` | `.defaults(…)`, `.site(id, values)`, `.secret(id, key, clear)` |
| `TempDirSiteFiles(sitesRoot, pluginId)` | `PluginSiteFiles` over a temp folder, with the kernel's three confinement layers, the caps and the missing-site rule |
| `FakeSiteServices` | `Sites`, `RequestContext` (`.current(id)`), `AccessCheck` (`.grant(key)`), `Messages` (`.message(…)`), `SitePages` (`.page(…)`, `.nextInstall(outcome)`, `.installs()`) |
| `FakeContentCatalog` | `ContentCatalogView`: `.entry(…)`, `.page(…)`, `.route(…)`, `.refreshed()` |
| `EventDispatch(pluginId, ownSourceKeys)` | delivers lifecycle/settings/page/catalog events to your listeners in the kernel's phase order with its isolation, and **is** your `ContentChanges` (refusing what the kernel refuses; `.announced()`) |
Wire your `mainClass` in a plain `AnnotationConfigApplicationContext` with these beans registered to prove the wiring
uses services only; drive a `@ConsoleScreen` controller with a standalone `MockMvc`. Add a test that scans your
compiled classes for `mx/quest/runway/` outside `spi/` (see `demo`'s `DemoPluginConfigTest`).
---
## 8. Control points (permissions) and the `POST` rules
Declared in `plugin.yml` `permissions:`, merged into the catalog as the **full key `<id>|<declId>`**. Enforce in code
with `AccessCheck` — there is no `hasControl(...)`:
```java
if (!access.may("myplugin|manage")) { return RouteResponse.text(403, "Forbidden\n"); } // endpoint
@PreAuthorize("@authz.may('myplugin|manage')") // console handler
<attr sel="#link" th:if="${@authz.may('myplugin|manage')}"/> // template (UX only)
```
- **Menu/card `permission:` fields must be the FULL key**; a bare decl id resolves to nothing and **hides the entry
from everyone**. Menu/card gating is **UX only** — the handler still checks.
- `defaultRoles` stays **empty**; a reserved/wildcard tier there is a hard startup failure.
- If you declare the reserved `settings` permission (tenant realm), the kernel requires it to open your per-site
settings form.
### 8.1 The `POST` rules
1. **A `GET` never changes anything.** A link or an `<img>` on another web site can make a signed-in user's browser
send any `GET`; the CSRF defence does not cover `GET`.
2. **Every state change is a `POST` the kernel CSRF-checks.** Operator actions go in a `@ConsoleScreen` controller
(§7.11) — Spring MVC binds the fields — or, for an action on your admin fragment, a non-anonymous endpoint
route, which reads the fields with `form()` (§6.3). Either way
the console page submits a form carrying the session's token:
```html
<!-- .html (markup only) -->
<form id="mp-run-form" method="post" action="/__admin/myplugin/run">
<input class="mp-csrf" type="hidden" name="_csrf" value="">
<button type="submit" id="mp-run">Run</button>
</form>
```
```xml
<!-- .th.xml (logic) -->
<attr sel=".mp-csrf"
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
```
Keep the `action` a constant in the markup (`th:action`/`th:attr` run in a restricted context that forbids
`${@bean}`). Answer with a redirect (post/redirect/get) so a reload never repeats the action.
3. **A public form that any visitor may submit without an account** — and that sits on a page every visitor shares,
so it cannot carry a per-session token — declares an **anonymous** route:
`Route.anonymousPost("/myplugin/submit", SurfacePosture.safeDefault())`. The kernel exempts exactly that method
and path from CSRF and takes away what a forged submission could use: the handler runs with **no principal**
(`AccessCheck.may` is `false`), and only an `application/x-www-form-urlencoded` body is accepted (`415`
otherwise). Your duties: read fields from `form()` only (personal text never in a URL); keep abuse guards — a
honeypot field, a length cap, a rate limit keyed by `req.clientIp()`, a CAPTCHA through `CaptchaService` when the
site has one; answer `303` back with an outcome flag, never a submitted value; declare what you store as personal
data. **Never** use it for an action on something a signed-in user owns.
---
## 9. Resources — static, templates, admin fragment, i18n
- **Static assets** — `static/`, served at `/__plugin/<id>/static/**`. Reference by that URL; never copied into
tenants.
- **Templates** — `templates/`, Thymeleaf **decoupled logic**: `<name>.html` with **zero `th:*`** and a sibling
`<name>.th.xml` with every binding; resolved as `__plugin__/<id>/<name>`. A **repeated `id`** in a `.html` is a hard
error (a 500); iterated rows use classes and `//` selectors. Fragments (dashboard card, admin fragment) are
**bare** — a root element, no `<html>`/`<body>`. A fragment may rely on `tenantSiteId` (null on the application
console), `_csrf`, `${@<own bean>…}`, `${@authz.may('…')}` and `#{…}` — nothing else in the console model.
- **Admin fragment** — a filename convention: ship `templates/admin.html` and the host renders it **below** your
per-site settings form.
- **i18n** — `i18n/messages[_xx].properties`, appended (add-only) to the console's **and** every site's message
source. Console labels (menu, settings, permissions) and `#{…}` resolve automatically; public text through
`Messages.site` (§7.6). Keys live with the plugin; keep every bundle's keys in step.
---
## 10. Capabilities
`Capabilities.of("thing.flag")` from each axis's `capabilities()`. Only host-recognised flags do anything (today
`ContentSource.CAP_INDEXABLE_TEXT`; `CAP_ARBITRARY_PATHS` is reserved); the vocabulary is open. The lifecycle hook is
§7.12.
---
## 11. Build → install → verify
```bash
mvn -o verify # JAVA_HOME on a JDK 25 (§2)
# target/<id>/ the install-ready FOLDER
# target/<artifactId>-<version>.zip the UI-uploadable ARCHIVE (antrun step; build twice → identical)
```
- **Filesystem install:** `cp -r target/<id> <runway-external>/plugins/`, then **restart** the host. To upgrade,
delete the old `<runway-external>/plugins/<id>/` first: `cp -r` over it keeps files the new version no longer
has, and the kernel loads **every** `*.jar` in the folder (`plugin.yml` names no jar), so an old jar left beside
the new one loads too. The console upload replaces the whole folder.
- **Management-UI install:** app console → `/__app/plugins` → install → upload the `.zip` (`plugin.yml` at the root
or under one wrapping directory); applied on restart.
**Verify against the PACKAGED host jar, never `spring-boot:run`** (DevTools' restart classloader loads ZERO plugins),
in **ACTIVE** mode (plugins are skipped in WIZARD mode). Each plugin ships `scripts/verify-against-host.sh`
(`demo`'s is the model): build offline (never `mvn install`), install into a throwaway deployment
(`VERIFY_TMPDIR`), boot the kernel named by `HOST_JAR`, run the first-run wizard,
reboot ACTIVE, then check — and keep the logs (`VERIFY_LOG_DIR`):
1. **Loads cleanly:** `plugins: N registered, 0 blocked`; **no** `plugin '<id>' linkage scan:` line, no
`plugin '<id>' is blocked:` line (linkage, `requiresSpi` floor, or `breaks the plugin rules for Runway's shared
Spring context`), no `QUARANTINED`, no collision (`contribution refused`) or degraded warning.
2. **Serves:** your endpoints, `/__plugin/<id>/static/**`, head injection, widgets on a page, the console screen and
card as a signed-in user, permission refusals (`403`), `POST`s refused without the CSRF token, an anonymous route
accepting a form with none, a transfer copy omitting your personal data.
---
## 12. Pitfalls (paid for already)
1. **WIZARD mode = ZERO plugins.** Before first-run setup completes, discovery is skipped entirely.
2. **Never depend on or bundle `runway-app`; never repackage.** Only `runway-spi` (+ the testkit for tests); platform
libraries `provided`; jar thin. A plugin linking host classes is blocked.
3. **Plugin-scoped services bind by jar.** Inject `PluginSettings`/`PluginSiteFiles`/`ContentChanges`/`PluginInfo`
in your own top-level classes — not from `lib/`, not with `getBean`.
4. **Bean names start with your id** (lowerCamelCase); no `@EnableConfigurationProperties`; no `@Primary` on collected
contributions; a colliding or blank `key()` is refused.
5. **No servlet filters, security chains or post-processors** — not part of the plugin contract.
6. **Two config surfaces differ:** app-level = property source, restart-only, your `@ConfigurationProperties`;
per-site = `PluginSettings`, immediate, `onSettingsChanged`.
7. **Setting-type traps:** `text` isn't trimmed; `decimal` ignores `range`; an unknown `type` is silently `string`.
8. **`POST` rules:** a `GET` changes nothing; state changes are CSRF-checked `POST`s from forms carrying `${_csrf}`
(§8.1); a non-anonymous endpoint `POST` reads every form field with `form()` (§6.3);
`Route.anonymousPost` only for public visitor forms, with your own abuse guards.
9. **Announce content changes** with `ContentChanges` after every write — never from a listener callback — and bump
`updatedAt` when a body changes.
10. **Listeners:** side effects only when `local`; evict on wholesale events; never heavy work on the writer's thread.
11. **Thymeleaf:** decoupled `.th.xml`; no repeated `id`; fragments bare; `id` + `data-widget` on one element; never
a literal `__plugin__/…` inside `~{…}` (pass it through a variable, e.g. `${master}`).
12. **Menu/card `permission` = full namespaced key**, or the entry is hidden from everyone; handlers still check.
13. **Personal data is declared** (`siteData.personal`), or a transfer copy hands it to an outsider.
14. **Install/upgrade/remove is RESTART-ONLY**; declare `requiresSpi` so an older kernel blocks you with a reason
instead of failing at the first request.
---
*Grounded in the Runway kernel at SPI `1.0.0` (Runway `1.0.0`: the log lines quoted in §5 and §11 are its
`HostLinkageScanner`, `PluginContextInitializer` and `PluginResolution` texts) and verified against the packaged host
jar. When the kernel
adds or changes a seam, update this guide in the same change.*
+10
View File
@@ -0,0 +1,10 @@
# Changelog
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
## [10.4.0] — 2026-10-21
First public release of `lucene-provider`: one deployment-wide copy of Apache Lucene 10.4.0 for the plugins that use
it (`search-lucene`). Its version is the Lucene version it ships. The plugin's packaging is licensed under the GNU
AGPL v3.0 with an additional permission for plugins (`LICENSE`, `LICENSE-EXCEPTION`); the bundled Lucene jars stay
under the Apache License 2.0, each with its own LICENSE and NOTICE.
+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.
+98
View File
@@ -0,0 +1,98 @@
# Runway Lucene Libraries Provider (`lucene-provider`)
A **code-less library-provider plugin** for [Runway](../README.md). It ships **no Java code and no `mainClass`** —
only the **Apache Lucene** stack under `lib/`, so it loads **once** onto the shared plugin classloader as the
**single, deployment-wide** copy of Lucene. Any plugin that needs full-text search (e.g.
[`search-lucene`](../search-lucene)) compiles Lucene as `provided` and declares a hard dependency on this provider.
- **Plugin id:** `lucene-provider` — install folder `external/plugins/lucene-provider/`
- **Version:** `10.4.0` — the plugin version **IS** the Lucene version (the *version tracks the principal
library* convention taken literally: a `lucene-provider 10.4.0` *is* Apache Lucene 10.4.0).
- **Bundled jars (`lib/`):**
- `lucene-core-10.4.0.jar` — the Lucene core (index, `IndexWriter`/`IndexSearcher`, the query classes:
`TermQuery`, `PhraseQuery`, `FuzzyQuery`, `BooleanQuery`, `ConstantScoreQuery`, `BoostQuery`; the
directories: `ByteBuffersDirectory` (heap) and `MMapDirectory` (disk); BM25 similarity).
- `lucene-analysis-common-10.4.0.jar` — analysis: the per-language `Analyzer`s and stemmers
(`EnglishAnalyzer`, `SpanishAnalyzer`, …), `StandardAnalyzer`, `CustomAnalyzer`, the token-filter factories.
- `lucene-highlighter-10.4.0.jar` — query-focused highlighting (`UnifiedHighlighter`,
`DefaultPassageFormatter`) for `<mark>`-wrapped result snippets.
- `lucene-memory-10.4.0.jar` — the in-memory index used by the highlighter (transitive of highlighter).
- `lucene-queries-10.4.0.jar` — extra query support used by the highlighter (transitive of highlighter).
## Why a standalone provider
Lucene ships as a **first-class shared provider** rather than following the default
"a bundled library stays private until a *second* consumer exists" rule. The reasoning: the shared plugin
classloader holds exactly **one** version of any library deployment-wide, so every plugin that needs full-text
search binds to **one agreed** Lucene version here, never its own private (and possibly clashing) copy.
`search-lucene` (currently the only consumer) binds to this provider: its `pom.xml` marks Lucene `provided` and
it declares:
```yaml
requires: [ "lucene-provider == 10.4.0" ]
```
`==` (exact) rather than `>=` because a consumer is **compiled against these binaries** — a Lucene major/minor
can move or rename internal classes, so a consumer must run against the very version it was built with. If
`lucene-provider` is missing, disabled, or a different version, the consumer is **not loaded** (skipped with a
precise reason and shown "Blocked" in the management UI) — so it never wires against a class the classloader
can't supply.
## Consuming it (for plugin authors)
1. In your `plugin.yml`: `requires: [ "lucene-provider == 10.4.0" ]` (pin the exact version you compiled against).
2. In your `pom.xml`: depend on the Lucene artifacts you use (`org.apache.lucene:lucene-core`,
`lucene-analysis-common`, `lucene-highlighter`, …) at **`provided`** scope — the provider supplies them at
runtime. **Never** bundle Lucene into your own plugin's `lib/` (that would be a second copy on the shared
classloader).
3. At runtime, use plain Lucene (`IndexWriter`, `IndexSearcher`, the query classes, the analyzers, the
`UnifiedHighlighter`). All five bundled jars are on the shared classloader.
## Build
```bash
export JAVA_HOME=<path to a JDK 25>
mvn -DskipTests package
# → target/lucene-provider/ the install-ready FOLDER (plugin.yml + lib/)
# → target/runway-plugin-lucene-provider-10.4.0.zip the UI-uploadable ARCHIVE (/__app/plugins)
```
The first build downloads its Maven dependencies, the Lucene jars included. It needs nothing of Runway in `~/.m2`.
- **Filesystem install:** `cp -r target/lucene-provider <runway-external>/plugins/` then **restart** the host.
- **Management-UI install:** `/__app/plugins` → install → upload the `.zip`, then restart.
There are no tests: a code-less bundle has nothing to unit-test. Its correctness is "the five jars are present
and the descriptor has no `mainClass`" — verified by the `package` output above.
## Bumping the Lucene version
Edit `pom.xml`: change `lucene.version`, then set **both** the `<version>` element **and** `plugin.yml`'s
`version:` to the new Lucene version (they must stay identical). Rebuild. Every consumer pinned with
`== <version>` must be **recompiled and re-cut** against the new version — that is the deliberate cost of the
exact pin, and the price of a single shared Lucene copy.
## Log messages you can ignore
Once per start of the host, the first time a consumer (`search-lucene`) uses Lucene, the log shows:
```
WARN … o.a.l.i.v.VectorizationProvider : Java vector incubator module is not readable. For optimal vector performance, pass '--add-modules jdk.incubator.vector' to enable Vector API.
```
It comes from the Lucene jars in this bundle. Nothing is wrong. **Leave it off**:
the flag only speeds up Lucene's vector maths, which serves mainly k-nearest-neighbour vector search, and Runway's
search is keyword search over small indexes; and `jdk.incubator.vector` is an incubator module, so the JVM would
print `WARNING: Using incubator modules: jdk.incubator.vector` at every start and depend on a JDK API that is not
final. To turn it on anyway, use a `JAVA_OPTS` drop-in, never the main unit: the steps are in
[`search-lucene`'s README](../search-lucene/README.md#log-messages-you-can-ignore).
## 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.
The zip bundles Apache Lucene, which stays under the Apache License 2.0: each Lucene jar in `lib/` carries its own
`LICENSE` and `NOTICE` (under `META-INF/`). The AGPL applies to this plugin's own packaging.
@@ -0,0 +1,97 @@
# Runway Lucene Libraries Provider — design & reference
> A **code-less library-provider plugin**: a `plugin.yml` with **no `mainClass`** plus `lib/*.jar`, whose only
> job is to place Apache Lucene **once** on the shared plugin classloader for other plugins to consume. Grounded
> in the Runway kernel as built — the reference code-less library provider.
## 1. What it is
`lucene-provider` ships **no Java code**. Its bundle is exactly:
```
lucene-provider/
├── plugin.yml # id, name, version — NO mainClass
└── lib/
├── lucene-core-10.4.0.jar # index + queries + directories + BM25 (the principal library)
├── lucene-analysis-common-10.4.0.jar # per-language analyzers + stemmers + token filters
├── lucene-highlighter-10.4.0.jar # UnifiedHighlighter → <mark>-wrapped query-focused snippets
├── lucene-memory-10.4.0.jar # in-memory index the highlighter needs (transitive)
└── lucene-queries-10.4.0.jar # extra query support the highlighter needs (transitive)
```
The kernel scans `lib/` one level deep and loads every jar into the **one** shared child classloader, so the
Lucene stack is available deployment-wide as a single copy. A code-less plugin (no `mainClass`) is first-class:
nothing is registered into the Spring context; it only contributes libraries.
## 2. Why a standalone provider (a deliberate divergence)
The general rule is "a bundled library stays **private** inside its one consumer until a **second** consumer
exists, then it graduates to a provider plugin." Here Lucene is a **standalone provider** even though
`search-lucene` is still the only consumer. The reasoning holds regardless of
consumer count: the shared classloader permits exactly **one** version of any library deployment-wide, so Lucene
belongs in **one agreed place** that every full-text plugin binds to with `requires:` — never a private copy per
plugin that could clash. (`search-lucene` binds here.)
## 3. Version tracks the principal library — literally
The plugin `version` is **`10.4.0`**: the plugin version *is* the Lucene version. Consumers gate on it with the
**exact** operator:
- `requires: [ "lucene-provider == 10.4.0" ]` — the only correct form for a Lucene consumer.
Why `==` and not `>=`: a consumer is **compiled against these binaries**. Lucene does not promise cross-version
binary stability for the internal classes plugins touch (index formats, analysis, query internals), so a
consumer must run against the very version it was built with. `>=` would let a newer, binary-incompatible Lucene
satisfy the gate and blow up at wire/run time.
Bumping: change `lucene.version` in `pom.xml`, then set **both** the pom `<version>` and `plugin.yml` `version:`
to the new Lucene version (identical), and rebuild. Every `==` consumer must be **recompiled and re-cut** — the
deliberate cost of one shared Lucene copy.
## 4. Consuming it (the `provided` rule)
A consumer plugin (see [`../../search-lucene`](../../search-lucene) for the worked example):
1. `plugin.yml`: `requires: [ "lucene-provider == 10.4.0" ]` — a **hard load gate**. If the provider is missing,
disabled, or a different version, the consumer is **not loaded** (skipped with a reason; "Blocked" in the
management UI), so it never wires against a class the classloader can't supply.
2. `pom.xml`: the Lucene artifacts at **`provided`** scope (compile-only). **Never** bundle Lucene into the
consumer's own `lib/` — that would be a second copy on the shared classloader.
3. Runtime: plain Lucene (`IndexWriter`, `IndexSearcher`, the query classes, the analyzers, the
`UnifiedHighlighter`). All five bundled jars are on the shared classloader.
## 5. Build & install
```bash
export JAVA_HOME=<path to a JDK 25>
mvn -DskipTests package
# → target/lucene-provider/ the install-ready FOLDER (plugin.yml + lib/)
# → target/runway-plugin-lucene-provider-10.4.0.zip the UI-uploadable ARCHIVE
```
The first build downloads its Maven dependencies, the Lucene jars included. It needs nothing of Runway in `~/.m2`.
- **Filesystem:** `cp -r target/lucene-provider <runway-external>/plugins/` then **restart**.
- **Management UI:** `/__app/plugins` → install → upload the `.zip`, then restart.
## 6. Verify
There is nothing to unit-test in a code-less bundle. Correctness = "the descriptor has no `mainClass` and the
five Lucene jars are present in `lib/`", which the `package` output shows. Functionally it is verified **through a
consumer**: install `lucene-provider` + `search` + `search-lucene`, boot the host in ACTIVE mode, and confirm the
startup log shows all three plugins `registered, 0 blocked` (i.e. `search-lucene`'s
`requires: lucene-provider == 10.4.0` was satisfied) and that `/search` returns Lucene-ranked results.
## 7. Pitfalls
- **A code-less plugin has NO `mainClass` and NO thin jar** — do not add one. The pom packaging is `pom` and
produces only the assembled bundle.
- **One Lucene version deployment-wide.** Never let a second plugin bundle Lucene privately; add it as a
`requires:` consumer of this provider instead.
- **Keep the plugin version == the Lucene version** and consumers pinned with `==`. A drift defeats the whole
"version tracks the principal library" contract, and a `>=` consumer would risk a binary-incompatible Lucene.
- **The `jdk.incubator.vector` log line is expected.** Lucene logs `Java vector incubator module is not readable.
For optimal vector performance, pass '--add-modules jdk.incubator.vector' to enable Vector API.` once per start.
Runway leaves the flag off: its search uses no vectors, and the module is an incubating JDK API that
makes the JVM warn at every start. See the lucene-provider [README](../README.md#log-messages-you-can-ignore) and
search-lucene's [design doc §8](../../search-lucene/docs/SEARCH-LUCENE-PLUGIN.md#8-log-messages-you-can-ignore).
+31
View File
@@ -0,0 +1,31 @@
# =============================================================================
# Runway Lucene Libraries Provider — descriptor (CODE-LESS library-provider plugin)
#
# This plugin ships NO code and NO mainClass. It carries the Apache Lucene stack
# (core + analysis-common + highlighter + memory + queries) under lib/*.jar so it
# loads once onto the shared plugin classloader — the SINGLE, deployment-wide
# copy of Lucene. Consumer plugins (e.g. `search-lucene`) compile Lucene as
# `provided` and declare an EXACT dependency:
# requires: [ "lucene-provider == 10.4.0" ]
# `==` (exact) because they are compiled against THESE binaries — a Lucene major
# can move/rename internal classes, so a consumer must run against the very
# version it was built with.
#
# Why a standalone provider: Lucene ships as a first-class shared provider so
# any plugin needing full-text search binds to ONE agreed Lucene version, never
# its own private (and possibly clashing) copy on the shared classloader.
#
# Version tracks the PRINCIPAL library taken literally: the plugin version IS the
# Lucene version (10.4.0). Bump this `version` and the pom's ${lucene.version}
# together on a Lucene upgrade, and re-cut every consumer pinned to `== <ver>`.
#
# The install folder name MUST equal this `id`: external/plugins/lucene-provider/.
# =============================================================================
id: lucene-provider
name: Lucene Libraries Provider (Apache Lucene)
version: 10.4.0
enabled: true
# No mainClass → code-less: nothing is registered into the Spring context.
# No requires → always loads (it only provides libraries).
# NOT essential → a normal optional provider; if absent, dependents are skipped.
+176
View File
@@ -0,0 +1,176 @@
<?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>
<!--
A CODE-LESS library-provider plugin: there is NO Java source and NO mainClass. `mvn package` produces NO
thin jar of its own; it only assembles the installable bundle = plugin.yml + lib/*.jar (the Apache Lucene
stack). Inherit spring-boot-starter-parent purely for its dependency-plugin/antrun defaults; the Lucene
versions are pinned explicitly below (Lucene is NOT on the Spring Boot BOM), so the jars we bundle are the
exact 10.4.0 artifacts every consumer compiles against.
The plugin VERSION *is* the Lucene version (10.4.0) — the "version tracks the principal library"
convention taken to its literal conclusion: a lucene-provider 10.4.0 IS Apache Lucene 10.4.0. Consumers
declare `requires: [ "lucene-provider == 10.4.0" ]` (EXACT: they are compiled against these binaries) and
compile Lucene as `provided`. Bump this pom's <version> AND the ${lucene.version} together on a Lucene
upgrade, and re-cut every consumer that pins `== <new version>`.
-->
<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-lucene-provider</artifactId>
<version>10.4.0</version>
<packaging>pom</packaging>
<name>Runway Lucene Libraries Provider (Apache Lucene)</name>
<licenses>
<license>
<name>GNU Affero General Public License v3.0, with the Runway additional permission for plugins</name>
<url>https://www.gnu.org/licenses/agpl-3.0.txt</url>
<distribution>repo</distribution>
<comments>See LICENSE and LICENSE-EXCEPTION.</comments>
</license>
</licenses>
<description>
A code-less Runway library-provider plugin bundling the Apache Lucene stack (core + analysis-common +
highlighter + memory + queries) under lib/, so it loads once onto the shared plugin classloader as the
single deployment-wide copy of Lucene. Consumers declare `requires: [ "lucene-provider == 10.4.0" ]`
and compile Lucene as `provided`. No mainClass, no code. The plugin version IS the Lucene version.
</description>
<properties>
<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-08-24T00:00:00Z</project.build.outputTimestamp>
<maven.compiler.release>25</maven.compiler.release>
<!-- The PRINCIPAL library this provider tracks; the plugin version above mirrors it exactly. -->
<lucene.version>10.4.0</lucene.version>
</properties>
<!-- Declared only so `dependency:copy` resolves them from the local repo (all are already installed). None
is compiled against here — there is no code. They ship in the bundle's lib/, NOT on the app classpath.
lucene-highlighter pulls in lucene-memory + lucene-queries transitively; we bundle all three explicitly
so the install folder is self-documenting and self-contained (no transitive surprises at run time). -->
<dependencies>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>${lucene.version}</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analysis-common</artifactId>
<version>${lucene.version}</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-highlighter</artifactId>
<version>${lucene.version}</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-memory</artifactId>
<version>${lucene.version}</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queries</artifactId>
<version>${lucene.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- 1. Copy EXACTLY the five Lucene jars (version pinned above) into the staged bundle's lib/.
stripVersion=false keeps the versioned filenames (self-documenting the Lucene stack). -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>bundle-lucene-libs</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>${lucene.version}</version>
</artifactItem>
<artifactItem>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analysis-common</artifactId>
<version>${lucene.version}</version>
</artifactItem>
<artifactItem>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-highlighter</artifactId>
<version>${lucene.version}</version>
</artifactItem>
<artifactItem>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-memory</artifactId>
<version>${lucene.version}</version>
</artifactItem>
<artifactItem>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queries</artifactId>
<version>${lucene.version}</version>
</artifactItem>
</artifactItems>
<outputDirectory>${project.build.directory}/lucene-provider/lib</outputDirectory>
<stripVersion>false</stripVersion>
<overWriteReleases>true</overWriteReleases>
</configuration>
</execution>
</executions>
</plugin>
<!-- 2. Assemble both installable forms: target/lucene-provider/ (folder = plugin.yml + lib/) and the
UI-uploadable target/runway-plugin-lucene-provider-<version>.zip (a single wrapping dir). -->
<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}/lucene-provider"/>
<!-- lib/ was populated by dependency:copy above; add only the descriptor. -->
<copy file="${project.basedir}/plugin.yml" todir="${stage}"/>
<copy file="${project.basedir}/LICENSE" todir="${stage}"/>
<copy file="${project.basedir}/LICENSE-EXCEPTION" todir="${stage}"/>
<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="lucene-provider"/>
</touch>
<zip destfile="${project.build.directory}/runway-plugin-lucene-provider-${project.version}.zip">
<zipfileset dir="${project.build.directory}" includes="lucene-provider/**"/>
</zip>
<echo message="Staged install folder (plugin.yml + lib/): ${stage}"/>
<echo message="UI-uploadable archive: ${project.build.directory}/runway-plugin-lucene-provider-${project.version}.zip"/>
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
+10
View File
@@ -0,0 +1,10 @@
# Changelog
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
## [3.3.0] — 2026-10-21
First public release of `search-lucene`: an Apache Lucene engine for the `search` plugin — one index per site and
language, language analyzers (stemming), tiered ranking over BM25, fuzzy matching and highlighting. Requires SPI `1.0.0` (Runway `1.0.0` or later),
`search >= 2.2.0` and `lucene-provider == 10.4.0`. 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.
+92
View File
@@ -0,0 +1,92 @@
# Runway Search — Lucene engine
A Lucene-backed `SiteSearchEngine` for the [`search`](../search) plugin: a full-text index over the search
plugin's `SearchCorpus` — every published page and content-source item the site has not excluded
from search — each item's
**title, description and body** with **per-locale stemming analysis**, a **tiered constant-score** relevance
model (exact phrase → near phrase → all terms → any term), **fuzzy** (typo-tolerant) matching, and query-focused
`<mark>` highlighting. Install it alongside `search` and it **transparently upgrades** the search box + `/search`
results page — no change to that query surface.
- **Plugin id:** `search-lucene` (v`3.3.0`) — install folder `external/plugins/search-lucene/`
- **Requires:** a Runway kernel with SPI `1.0.0` or later (`requiresSpi: ">=1.0.0"`, a floor every `1.x` kernel meets), `search >= 2.2.0` **and**
`lucene-provider == 10.4.0`. With search 2.1.x, keep 3.1.0; with search 2.0.0, keep 3.0.0.
- **Links:** only the Runway SPI (`mx.quest.runway.spi`) and the search SPI (`mx.quest.search.spi`)
- **Java package:** `mx.quest.searchlucene` · **Lucene:** supplied by the [`lucene-provider`](../lucene-provider)
plugin (compiled `provided`, **not** bundled here)
## Why a separate plugin
`search` splits search into a **query surface** (box + `/search`) and a swappable **engine** (`SiteSearchEngine`).
The built-in engine matches with plain substrings; this one indexes with Lucene analysis and
ranks by relevance, registering at a higher `priority()` so it wins wherever installed. It indexes the same
`SearchCorpus` the built-in engine does — so the `search` plugin's per-site **`exclude`** list applies without this
plugin reading it — drops a site's index the moment the kernel announces a change (a `SiteEventListener`), and
implements the SPI's manual **reindex** hook so the operator's rebuild-index button rebuilds this index too. Lucene itself
lives in the shared [`lucene-provider`](../lucene-provider) plugin (one copy deployment-wide). See
[`docs/SEARCH-LUCENE-PLUGIN.md`](docs/SEARCH-LUCENE-PLUGIN.md) and [`CHANGELOG.md`](CHANGELOG.md).
## Tuning (per-site `siteSettings:`)
`fuzzy`, `fuzzyBoost`, `titleBoost`, `descriptionBoost`, and the four tier scores (`tierPhraseTitle`,
`tierPhraseBody`, `tierNearPhrase`, `tierAllTerms`). App-level `settings:` choose index `storage` (heap/disk) and
the disk `indexRoot`. Defaults reproduce the historical ranking, so an unconfigured site behaves as before.
## Build
```bash
export JAVA_HOME=/path/to/jdk-25
(cd ../search && mvn -DskipTests install) # the jar this compiles against, into ~/.m2
mvn verify # 72 unit tests + the package
# → target/runway-plugin-search-lucene.jar (thin jar — NO bundled Lucene)
# target/search-lucene/ (folder — cp -r into <external>/plugins/ + restart)
# target/runway-plugin-search-lucene-3.3.0.zip (upload at /__app/plugins → install)
JAVA_HOME=/path/to/jdk-25 HOST_JAR=/path/to/runway-app-<ver>-exec.jar VERIFY_TMPDIR=/some/scratch scripts/verify-against-host.sh
```
The build compiles against the search plugin, `provided` from `~/.m2`: install it first with
`mvn -DskipTests install` in `../search` (the verify script does). 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. This plugin itself is never installed. At runtime the deployment must also carry the `search` plugin (2.2.0 or later) **and**
the `lucene-provider` plugin (the Lucene binaries): drop all three folders into `external/plugins/`.
## Log messages you can ignore
### `Java vector incubator module is not readable`
Once per start of the host, the first time Lucene is used (usually the first search, on a request thread), the log
shows:
```
WARN … o.a.l.i.v.VectorizationProvider : Java vector incubator module is not readable. For optimal vector performance, pass '--add-modules jdk.incubator.vector' to enable Vector API.
```
Lucene prints it (the library the `lucene-provider` plugin supplies). Nothing is wrong. **Leave it off**, for three
reasons.
- The flag makes Lucene's vector maths faster. Lucene needs that mainly for k-nearest-neighbour *vector* search.
Runway's search is keyword search (terms, phrases, typo-tolerant matches) and uses no vectors.
- A site's index is small (its published pages and items), so there is no time to win.
- `jdk.incubator.vector` is an *incubator* module, a JDK API that is not final. With it, the JVM prints
`WARNING: Using incubator modules: jdk.incubator.vector` at every start, and a later JDK may change or drop the
module.
If you want it anyway, add `--add-modules jdk.incubator.vector` to `JAVA_OPTS` in a systemd **drop-in** under
`/etc/systemd/system/runway.service.d/`. Never edit the main unit, `runway.service`: the installer rewrites it at
every upgrade. `Environment=` sets the whole variable, so the line must also carry your heap flags:
```ini
# /etc/systemd/system/runway.service.d/20-heap.conf
[Service]
Environment="JAVA_OPTS=-Xms256m -Xmx1g --add-modules jdk.incubator.vector"
```
Then run `sudo systemctl daemon-reload && sudo systemctl restart runway`. The installer's `--heap` rewrites
`20-heap.conf` whole and drops the flag, so add it again after each `--heap`. Runway's administration manual
(§15, *Memory tuning*) explains the drop-ins.
## 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.
@@ -0,0 +1,224 @@
# Runway Search — Lucene engine — design & reference
> The companion engine for the `../search` plugin, and the workspace's reference for **two** hard-to-get-right
> plugin patterns at once: implementing another plugin's **published SPI** (`requires:`), and **consuming a
> shared library-provider plugin** (`../lucene-provider`) instead of bundling the library privately. Grounded in
> the Runway kernel as built. Since 3.0.0 it links **only the Runway SPI and the search plugin's SPI**.
## 1. What it does
Implements `search`'s `SiteSearchEngine` SPI with Apache Lucene. Where the built-in engine substring-matches,
this one builds a full-text index over each searchable item's **title**, **description**, and **body text**
(extracted from the item's indexable material via `HtmlText`), analyzes queries with a **per-locale stemming
analyzer**, and ranks with a **tiered constant-score** model layered on Lucene's BM25. It registers at
`priority()` 100, so the shared search box and the results page transparently use it wherever it is installed —
and fall back to the built-in engine if this plugin is removed.
What it indexes is the search plugin's **`SearchCorpus`** (search 2.0.0): every published page and content-source
item of the kernel's listing **minus the site's search exclusions**. The built-in engine builds from the same
corpus, so which items are searchable never depends on which engine serves the query, and the `exclude` rule lives
in exactly one place — this plugin never reads the search plugin's settings.
## 2. The two `requires:` gates and the SPI floor
`plugin.yml` declares `requires: [ "search >= 2.2.0", "lucene-provider == 10.4.0" ]` and `requiresSpi: ">=1.0.0"`:
- **`search >= 2.2.0`** publishes the `SiteSearchEngine` interface this plugin implements and the `SearchCorpus` it
indexes (both in `mx.quest.search.spi`). This plugin compiles against the search plugin as a `provided`
dependency from `~/.m2` (installed from `../search`; never bundled). Both plugin jars load into ONE shared classloader, so the SPI types have a single `Class` identity and
Spring collects this engine into `search`'s `List<SiteSearchEngine>`. `>=` (not exact) because the search SPI is
API-stable — it grows by `default` methods and kept constructors only; **2.2.0** is the floor (since 3.2.0)
because this plugin keeps one index per language, which a visitor reaches only when the search box on a
localized page submits to the results page in that language — search 2.2.0 does that, while 2.1.x always
submitted to the default-language results page. (3.1.x needed 2.1.0, the first with the `SearchHit`
constructor that carries the matched words; 2.0.0 was the first to publish `SearchCorpus`.) Only the `spi` package is a contract: a build-time test fails if this plugin links any
other search class.
- **`lucene-provider == 10.4.0`** is the standalone code-less provider (`../lucene-provider`) that places the
single deployment-wide copy of Lucene on the shared classloader. **`==` (exact)** because this plugin is
**compiled against the 10.4.0 binaries** — a different Lucene could be binary-incompatible.
- **`requiresSpi: ">=1.0.0"`** — the frozen 1.x contract, which carries the services it uses: `PluginSettings`
(0.4.0), `Sites` (0.5.0), `SiteEventListener` and `CatalogEntry` (0.6.0).
If a gate is unsatisfied (missing/disabled/wrong version, or an older kernel), the host **does not load** this
plugin (skipped with a reason, shown "Blocked" in the console) — so the SPI types AND every Lucene class are
guaranteed present when this plugin's beans wire.
## 2a. What it uses, and nothing else
| Need | Published service |
|------|-------------------|
| what to index, its indexable text, the manual refresh | `SearchCorpus.corpus` / `indexableText` / `refresh` (search) |
| a site's default locale (the analyzer) | `Sites.find` (kernel SPI) |
| the per-site ranking knobs | `PluginSettings.site` (kernel SPI; descriptor defaults applied under the stored values) |
| drop an index when content changes | `SiteEventListener.onCatalogChanged` (kernel SPI; one `CONSUMER` listener) |
| app-level storage settings | its own `@ConfigurationProperties` bean under `runway.plugin.search-lucene` |
Beans: `searchLuceneStorageProps`, `searchLuceneEngine`, `searchLuceneSiteEvents`, `searchLuceneAdminModel` — every
name starts with the plugin id in lowerCamelCase (the kernel's rule for the bean namespace plugins share).
`SearchLuceneConfigTest` scans the compiled classes' constant pools: nothing of `mx.quest.runway` outside `.spi`,
nothing of `mx.quest.search` outside `.spi`, no Caffeine.
## 3. Graduated from private bundling to the provider
search-lucene **used to** bundle Lucene privately in its own `lib/` (it was the only consumer). Lucene has
**graduated** to the standalone `lucene-provider` (whose version IS the Lucene version):
- `pom.xml` now marks `lucene-core` + `lucene-analysis-common` + `lucene-highlighter` (and their transitives
`lucene-memory` + `lucene-queries`) as **`provided`** — compile-only, supplied by the provider at runtime.
- **Nothing** is copied into this plugin's own `lib/`. The staged install folder is the thin jar + templates +
i18n only; a `clean package` verifies no Lucene jar appears in `target/search-lucene/`.
- The search jar is compile-only too (never bundled — a second `Class` identity would break by-type SPI
collection).
One Lucene version deployment-wide; no silent classpath clash. On a Lucene upgrade, bump `../lucene-provider` and
this plugin's `${lucene.version}` + `requires:` pin together, then re-cut.
## 4. Ranking model
`buildQuery` composes a **tiered, additive constant-score** query — the tiers are `SHOULD` clauses, so a hit
scores the **sum** of the tiers it satisfies, giving a deterministic ordering:
| Tier | What it matches | Score |
|------|-----------------|-------|
| any-terms | each term across title (× `titleBoost`), description (× `descriptionBoost`), body; **+ fuzzy** clauses when `fuzzy` is on | BM25 (× boosts) — the base layer that separates hits *within* a tier |
| near phrase (body) | the query as a body `PhraseQuery` with slop 1 (lightly reordered / 1 gap) | constant `tierNearPhrase` |
| exact phrase (body) | the query as an exact (slop 0) body phrase | constant `tierPhraseBody` |
| exact phrase (title) | the query as an exact title phrase | constant `tierPhraseTitle` |
| all-terms-anywhere | every term appears in some field (`MUST` across fields) | constant `tierAllTerms` |
Defaults reproduce the historical ranking constants (`tierPhraseTitle 4000 > tierPhraseBody 2000 > tierNearPhrase
800 > tierAllTerms 300`; `titleBoost 8`, `descriptionBoost 4`; `fuzzy` on, `fuzzyBoost 0.4`). The phrase tiers
are skipped for a single-term query (a lone term IS its own phrase — no double-count).
- **Fuzzy** (`FuzzyQuery`): typo tolerance with a length-aware edit budget (`maxEdits`: 0 for ≤2 chars, 1 for
≤5, 2 beyond), fixed 1-char prefix, transpositions on. Fuzzy operates on the **analyzed (stemmed)** term.
- **Per-locale analyzers** (`LocaleAnalyzers`): a Lucene language `Analyzer` (with that language's stopwords +
stemmer) chosen by the **site's default locale** where one exists (en, es, fr, de, it, pt, ru, …), else
`StandardAnalyzer`. The **same** analyzer is used at index and query time — stemming is analysis-time, so the
two must never drift (or a stemmed query term would never match a stemmed indexed term).
- **Highlighting** (`UnifiedHighlighter` + `DefaultPassageFormatter`): a query-focused body passage with hits
wrapped in `<mark>…</mark>`. Private control-char markers are used internally; the passage is **HTML-escaped
first, THEN** the markers become real `<mark>` tags — so page content can't inject markup while the highlight
tags survive. Falls back to the description / a leading body slice when there is no highlightable passage.
This is the `SearchHit` snippet contract (escape everything, wrap only hits in `<mark>`), and the search surface
renders the snippet as raw HTML on that basis.
- **Matched words** (since 3.1.0, `MatchedForms`): each returned hit also carries `SearchHit.terms`, the words the
query matched **as the page writes them**, which search 2.1.0 hands to the page the result opens for
highlighting. The stored title, description and body go through the same analyzer; a token whose term is a query
term (or, with `fuzzy` on, within the fuzzy edit distance, same rule as the clauses) is kept as the text its
offsets cover. So `maestría` (term `maestr`) reports `maestrías` from the page. At most 20 words; the first
64 KiB of each text are read, so a long page costs a fixed amount per hit. Stop words match nothing and are never
reported.
## 5. Index lifecycle & storage
- **Source:** `SearchCorpus.corpus(siteId)` — every published item minus the site's exclusions — and
`SearchCorpus.indexableText(siteId, entry, locale)` for its body material (stripped to text) — the page
as rendered in that language, so strings from the site's bundles are in it.
- **One index per language (since 3.2.0).** Each item is indexed once per language it exists in: title,
description, body in that language, and the hit's URL `CatalogEntry.pathFor(locale)` — its real address there.
A site has one index per language it speaks, analyzed with **that language's analyzer**: the language's own
documents plus, for an item that does not exist in it, the item's **primary-locale** document (the site default
when the item has it, else its own first language), so a page published in one language only is still found
from every other. A query searches its own language's index (`SearchQuery.locale()` — the results page's
language, or the API's `?lang=`) with that analyzer; a language the site does not speak searches the site
default's. A fallback document is analyzed with the index's analyzer, not its own language's, so it matches on
exact and lightly stemmed forms rather than every inflection. Before 3.2.0 a site had one index of
primary-locale documents with the default language's analyzer, so every language searched default-language
text. The console's count is of items, not per-language documents.
- **Store (app-level `settings:`, `LuceneStorageProps`, restart-only — a PLATFORM concern, not per-site, because
a tenant-editable path is an isolation/abuse risk):**
- `heap` (default) — an in-memory `ByteBuffersDirectory` per language; rebuilt on first use after boot.
- `disk` — a memory-mapped `MMapDirectory` per language under `indexRoot/<siteId>/<language>` (since 3.2.0;
the site id and the language are validated and the resolved path is asserted to stay under the normalized
index root — traversal-safe). The index files a 3.1.x build left directly under `indexRoot/<siteId>` are
deleted on the first rebuild — only files Lucene names (`segments*`, `write.lock`, codec files `_*.*`), once
per site per process, so a misdirected `indexRoot` loses nothing else.
- **Freshness:** each index is **cached per site** and dropped by the plugin's `SiteEventListener`
(`LuceneSiteEvents`, phase `CONSUMER`) on **every** catalog change of the site — a page write, a content source's
change, a site lifecycle event, any plugin's settings save (the search plugin's `exclude` list and a source's
own settings both reshape the corpus). The kernel delivers it after its own caches are evicted and after every
content source has dropped its state, so the next query rebuilds from the new content. A build that a change
overtook (it may have read the old corpus) is kept as already stale: it answers the query that built it, and the
next query rebuilds. A 30 s TTL remains as the backstop for changes no event announces, and the SPI's
`reindex(siteId)` hook (the operator's rebuild-index button) refreshes the kernel's listing through
`SearchCorpus.refresh`, then drops and rebuilds eagerly, returning the fresh document count. The build is
rebuild-from-scratch (`deleteAll` then re-add), so a disk index is never left stale.
- **Safety:** `search(...)` **never throws** — a Lucene/store/corpus failure logs and returns no results, so the
query surface degrades to "no results", never a 500. Every surface is scoped to the queried `siteId`.
- **No personal data.** The index is derived from published content and lives in heap or under `indexRoot`, not in
the site folder; the plugin declares no `siteData.personal`.
## 6. Console & settings
- **App-level** `settings:` — `storage` (enum heap/disk) + `indexRoot` (string). Superadmin-only; applied on
restart.
- **Per-tenant** `siteSettings:` — the 8 ranking knobs (`fuzzy`, `fuzzyBoost`, `titleBoost`, `descriptionBoost`,
`tierPhraseTitle`, `tierPhraseBody`, `tierNearPhrase`, `tierAllTerms`), read per query (a save applies to the
next query) through `PluginSettings`. The editor is gated by the `settings` control point. `decimal` ignores `range`
(authoring guide §4.1), so `RankingConfig` defaults + clamps every value defensively.
- A dashboard card + admin fragment (bean `searchLuceneAdminModel`) show the active engine key, the site's indexed
item count, the storage mode, and the effective title boost.
## 7. Verify
- **Offline unit tests** (`mvn verify`, 72 tests, on the `runway-spi-testkit` fakes and search's own
`SiteSearchCorpus`): SPI contract (never-throws, empty index, unsafe/unknown site, limit, tie order), the search
plugin's exclusions reaching the index through its corpus, the primary-locale title/body/URL, one index per
language (`LucenePerLanguageTest`: each language's own text, analyzer and address, the primary-locale fallback,
an unknown language, the item count, the per-language disk folders, only Lucene-named 3.1.x files deleted, a
search from inside the site's own build answering nothing), `reindex`
(listing refresh + immediate rebuild inside the TTL), the listener dropping the index for every cause (page,
content, settings of another plugin, lifecycle, a replayed change) and only for its site, the mid-build change,
tiering (exact phrase > scattered; title phrase > body phrase; the documented tier sum), fuzzy on/off applied on
the next query, per-locale stemming (English `running`↔`run`; Spanish `producto`↔`productos`; unknown locale →
StandardAnalyzer), heap and disk answering identically, `<mark>` highlighting (incl. page-markup escaping), each
tuning knob, defensive config parsing, and the contract test (wiring from published services only, bean names,
template bean references, descriptor floors and version, code fallbacks = descriptor defaults, i18n, the
constant-pool scan).
- **Live** (`scripts/verify-against-host.sh`; honours `HOST_JAR`, `VERIFY_TMPDIR`, `VERIFY_LOG_DIR`; packages
everything offline and never `mvn install`s): boots the packaged host twice on the same fixture site — first
search 2.0.0 + search-lucene 3.0.0 (built from git at `BASELINE_REF`, a commit carrying those two versions; when
`BASELINE_REF` is unset, the default, or `SKIP_BASELINE=1`, the script prints a note and runs only the checks on the
current pair), then the current search + this release with the index on disk — and asserts that twelve queries
answer **byte-identically** (order, URLs, titles, snippets, scores) once the `link` and `terms` fields 3.0.0 never had are set aside; those it checks on
their own: each hit carries its marked link and at least every word its snippet marks. (Until 3.1.0 the baseline
was 2.2.1, which a Runway 1.0 kernel blocks for linking kernel internals; 3.0.0 had matched it byte for byte.) On
the current pair it asserts `3 registered, 0 blocked` with zero host-linkage and bean-name/surface warnings, the
console card and admin fragment, a save of search's `exclude` list and of this plugin's knobs reaching the next
query without a reindex, and the rebuild-index POST reporting this engine's count.
## 8. Log messages you can ignore
### `Java vector incubator module is not readable`
Once per start of the host, the first time Lucene is used (usually the first search, on a request thread), the log
shows:
```
WARN … o.a.l.i.v.VectorizationProvider : Java vector incubator module is not readable. For optimal vector performance, pass '--add-modules jdk.incubator.vector' to enable Vector API.
```
Lucene prints it (the library the `lucene-provider` plugin supplies). Nothing is wrong. **Leave it off**, for three
reasons.
- The flag makes Lucene's vector maths faster. Lucene needs that mainly for k-nearest-neighbour *vector* search.
Runway's search is keyword search (terms, phrases, typo-tolerant matches) and uses no vectors.
- A site's index is small (its published pages and items), so there is no time to win.
- `jdk.incubator.vector` is an *incubator* module, a JDK API that is not final. With it, the JVM prints
`WARNING: Using incubator modules: jdk.incubator.vector` at every start, and a later JDK may change or drop the
module.
If you want it anyway, add `--add-modules jdk.incubator.vector` to `JAVA_OPTS` in a systemd **drop-in** under
`/etc/systemd/system/runway.service.d/`. Never edit the main unit, `runway.service`: the installer rewrites it at
every upgrade. `Environment=` sets the whole variable, so the line must also carry your heap flags:
```ini
# /etc/systemd/system/runway.service.d/20-heap.conf
[Service]
Environment="JAVA_OPTS=-Xms256m -Xmx1g --add-modules jdk.incubator.vector"
```
Then run `sudo systemctl daemon-reload && sudo systemctl restart runway`. The installer's `--heap` rewrites
`20-heap.conf` whole and drops the flag, so add it again after each `--heap`. Runway's administration manual
(§15, *Memory tuning*) explains the drop-ins.
@@ -0,0 +1,30 @@
# Runway Search — Lucene engine — English strings.
# Grantable permission (permissions matrix label)
searchlucene.perm.settings=Configure Lucene search
# App-level settings form labels (superadmin — platform storage)
searchlucene.set.storage=Index storage
searchlucene.set.indexRoot=Disk index root folder
# Per-tenant settings form labels (site ranking tuning)
searchlucene.set.fuzzy=Typo-tolerant (fuzzy) matching
searchlucene.set.fuzzyBoost=Fuzzy match weight
searchlucene.set.titleBoost=Title match boost
searchlucene.set.descriptionBoost=Description match boost
searchlucene.set.tierPhraseTitle=Exact phrase in title — score
searchlucene.set.tierPhraseBody=Exact phrase in body — score
searchlucene.set.tierNearPhrase=Near phrase in body — score
searchlucene.set.tierAllTerms=All terms present — score
# Dashboard card
searchlucene.card.title=Lucene search index
searchlucene.card.pages=indexed items
# Admin status fragment
searchlucene.admin.title=Lucene index status
searchlucene.admin.engine=Engine
searchlucene.admin.pages=Indexed items
searchlucene.admin.storage=Storage
searchlucene.admin.boost=Title boost
searchlucene.admin.note=This engine supersedes the built-in search whenever it is installed. It ranks results in tiers (exact phrase, near phrase, all terms, any term), tolerates typos, and stems per the site language. The index refreshes automatically as content changes; no manual rebuild is needed.
@@ -0,0 +1,30 @@
# Runway Search — motor Lucene — cadenas en español.
# Permiso otorgable (etiqueta de la matriz de permisos)
searchlucene.perm.settings=Configurar búsqueda Lucene
# Etiquetas del formulario de configuración a nivel de aplicación (superadmin — almacenamiento)
searchlucene.set.storage=Almacenamiento del índice
searchlucene.set.indexRoot=Carpeta raíz del índice en disco
# Etiquetas del formulario de configuración por sitio (ajuste de relevancia)
searchlucene.set.fuzzy=Coincidencia tolerante a errores (difusa)
searchlucene.set.fuzzyBoost=Peso de coincidencia difusa
searchlucene.set.titleBoost=Refuerzo de coincidencia en título
searchlucene.set.descriptionBoost=Refuerzo de coincidencia en descripción
searchlucene.set.tierPhraseTitle=Frase exacta en título — puntuación
searchlucene.set.tierPhraseBody=Frase exacta en cuerpo — puntuación
searchlucene.set.tierNearPhrase=Frase cercana en cuerpo — puntuación
searchlucene.set.tierAllTerms=Todos los términos presentes — puntuación
# Tarjeta del panel
searchlucene.card.title=Índice de búsqueda Lucene
searchlucene.card.pages=elementos indexados
# Fragmento de estado (admin)
searchlucene.admin.title=Estado del índice Lucene
searchlucene.admin.engine=Motor
searchlucene.admin.pages=Elementos indexados
searchlucene.admin.storage=Almacenamiento
searchlucene.admin.boost=Refuerzo de título
searchlucene.admin.note=Este motor sustituye a la búsqueda integrada siempre que está instalado. Ordena los resultados por niveles (frase exacta, frase cercana, todos los términos, cualquier término), tolera erratas y lematiza según el idioma del sitio. El índice se actualiza automáticamente cuando cambian las páginas; no hace falta reconstruirlo a mano.
+78
View File
@@ -0,0 +1,78 @@
# =============================================================================
# Runway Search — Lucene engine
# A full-text SiteSearchEngine (title + description + body) with per-locale
# analysis (stemming), a TIERED constant-score ranking (exact phrase → near
# phrase → all-terms → any-terms), FUZZY matching, and query-focused <mark>
# highlighting — a real upgrade over the built-in substring engine.
#
# Indexes the search plugin's SearchCorpus (the site's published pages and
# content items minus the site's search exclusions — the same corpus the
# built-in engine indexes), drops a site's index on every change the kernel
# announces (a SiteEventListener), and implements the engine SPI's manual
# reindex hook. Since 3.0.0 it links only the Runway SPI and the search SPI.
#
# Lucene lives in the standalone `lucene-provider` plugin: this plugin does not
# bundle Lucene in its own lib/. It declares two hard dependencies:
# - requires: search >= 2.2.0 — publishes SiteSearchEngine, SearchCorpus and SearchHit.terms
# - requires: lucene-provider == 10.4.0 — the exact Lucene binaries it is compiled against
#
# The install folder name MUST equal this `id`: external/plugins/search-lucene/.
# =============================================================================
id: search-lucene
name: Search — Lucene engine
version: 3.3.0
# The @Configuration registered before refresh. Package mx.quest.searchlucene lives OUTSIDE mx.quest.runway.
mainClass: mx.quest.searchlucene.SearchLuceneConfig
# HARD dependencies (both must be satisfied or this plugin is skipped with a reason, shown "Blocked" in the UI):
# - search >= 2.1.0: publishes the SiteSearchEngine SPI this plugin implements and the SearchCorpus it indexes.
# `>=` (not exact) because the search SPI is API-stable (it grows by default methods and kept constructors only);
# 2.2.0 is the floor (3.2.0): this plugin keeps one index per language, which a visitor reaches only when the
# search box on a localized page submits to the results page in that language — search 2.2.0 does that (2.1.x
# always submitted to the default-language results page, so every query arrived in the default language).
# Before 3.2.0 the floor was 2.1.0, the first search with the SearchHit constructor carrying the matched words.
# - lucene-provider == 10.4.0: EXACT pin — this plugin is compiled against the 10.4.0 Lucene binaries the
# provider ships; a different Lucene could be binary-incompatible, so `==` (not `>=`).
requires: [ "search >= 2.2.0", "lucene-provider == 10.4.0" ]
# The lowest Runway SPI whose services this plugin uses (PluginSettings, Sites, SiteEventListener and the
# CatalogEntry the corpus hands out). A kernel below SPI 1.0.0 BLOCKS this plugin at startup with a reason.
requiresSpi: ">=1.0.0"
# --- Grantable control-point permission (gates the per-tenant tuning editor) -----------------------------
permissions:
- { id: settings, realm: tenant, label: searchlucene.perm.settings, defaultRoles: [] }
# --- App-level settings (superadmin): PLATFORM concerns only — WHERE the index bytes live. -----------------
# A tenant-editable filesystem path would be an isolation/abuse risk, so storage is app-level, not per-site.
# Applied on RESTART (bound by the plugin's own @ConfigurationProperties bean from
# external/plugin-settings/search-lucene.yml).
# storage : heap → in-memory ByteBuffersDirectory (default; no disk, rebuilt on boot)
# disk → MMapDirectory under indexRoot/<siteId> (survives restart, memory-mapped)
# indexRoot : the root folder for disk indexes (per-site subfolders created under it, traversal-guarded)
settings:
- { key: storage, type: enum, values: [heap, disk], default: heap, label: searchlucene.set.storage }
- { key: indexRoot, type: string, default: "./external/plugins/search-lucene/index", label: searchlucene.set.indexRoot }
# --- Per-tenant settings (tenant-owned ranking tuning; over sites/<id>/plugins/search-lucene.yml) ----------
# Applied IMMEDIATELY (read per query through the SPI's PluginSettings). `decimal` IGNORES range
# (authoring guide §4.1), so the engine clamps every knob to a sane range itself. Defaults reproduce the
# historical constants, so an unconfigured site ranks exactly as before this schema existed.
siteSettings:
# Fuzzy (typo-tolerant) matching — on/off + how much a fuzzy hit is worth relative to an exact term hit.
- { key: fuzzy, type: boolean, default: true, label: searchlucene.set.fuzzy }
- { key: fuzzyBoost, type: decimal, default: 0.4, label: searchlucene.set.fuzzyBoost }
# Per-field term boosts (applied to the any-terms tier's term matches).
- { key: titleBoost, type: decimal, default: 8.0, label: searchlucene.set.titleBoost }
- { key: descriptionBoost, type: decimal, default: 4.0, label: searchlucene.set.descriptionBoost }
# Tier scores — the constant score a document earns for matching each tier (bigger = stronger relevance
# signal). exact-phrase-in-title ≫ exact-phrase-in-body ≫ near-phrase-in-body ≫ all-terms-anywhere.
- { key: tierPhraseTitle, type: decimal, default: 4000, label: searchlucene.set.tierPhraseTitle }
- { key: tierPhraseBody, type: decimal, default: 2000, label: searchlucene.set.tierPhraseBody }
- { key: tierNearPhrase, type: decimal, default: 800, label: searchlucene.set.tierNearPhrase }
- { key: tierAllTerms, type: decimal, default: 300, label: searchlucene.set.tierAllTerms }
# --- Tenant dashboard card (fragment resolves to __plugin__/search-lucene/dashboard) ----------------------
dashboardCards:
- { realm: tenant, order: 41, fragment: dashboard, permission: "search-lucene|settings" }
+195
View File
@@ -0,0 +1,195 @@
<?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
is byte-identical at runtime. A plugin is NOT a Boot application — NO repackage; `mvn package` produces a THIN
jar of only this plugin's classes.
SPI only (3.0.0): the plugin links nothing of the kernel but `runway-spi` (no runway-app, in any scope), and
nothing of the search plugin but its published SPI package `mx.quest.search.spi` (SiteSearchEngine,
SearchCorpus, SearchQuery, SearchHit). Lucene comes from the `lucene-provider` plugin (`provided` here,
`requires: lucene-provider == 10.4.0` in plugin.yml), so this pom bundles NOTHING into a lib/ folder.
-->
<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-lucene</artifactId>
<version>3.3.0</version>
<packaging>jar</packaging>
<name>Runway Search — Lucene engine</name>
<licenses>
<license>
<name>GNU Affero General Public License v3.0, with the Runway additional permission for plugins</name>
<url>https://www.gnu.org/licenses/agpl-3.0.txt</url>
<distribution>repo</distribution>
<comments>See LICENSE and LICENSE-EXCEPTION.</comments>
</license>
</licenses>
<description>
A Lucene-backed SiteSearchEngine for the Runway `search` plugin: a full-text index over each page's
title, description and body with per-locale analysis (stemming) and a tiered constant-score ranking —
exact phrase, near phrase, all-terms, any-terms — plus fuzzy matching and query-focused snippet
highlighting. It indexes the search plugin's SearchCorpus, declares `requires: search >= 2.2.0` and
`requires: lucene-provider == 10.4.0`, registers at a higher priority than the built-in engine, and
transparently upgrades the search box and results page. Links only the Runway SPI and the search SPI;
Lucene is supplied by the lucene-provider plugin (provided).
</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>
<!-- The search plugin this engine compiles against, `provided` from ~/.m2 (install it first:
`mvn -o -DskipTests install` in ../search — the verify script does). plugin.yml declares
`search >= 2.2.0` (3.2.0: the box submits to the results page in its page's language, so a
language's index is reached); 2.1.0 was the first whose SearchHit carries the matched words (the
constructor this engine calls), and an older search does not compile this plugin. Provided, never bundled: a second copy of the search SPI classes would break by-type lookup. -->
<search.version>2.3.0</search.version>
<!-- The EXACT Lucene version this plugin is compiled against; lucene-provider must ship the same one
(plugin.yml pins `lucene-provider == 10.4.0`). Keep these two in lock-step. -->
<lucene.version>10.4.0</lucene.version>
</properties>
<dependencies>
<!-- The dependency-free extension API (SPI interfaces, services and immutable model records). -->
<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>
<!-- The `search` plugin publishes the SiteSearchEngine SPI this plugin implements and the SearchCorpus it
indexes. Compile-only: at runtime the shared plugin classloader supplies search's classes (both
plugin jars load into ONE classloader, so the SPI has one Class identity), and `requires: search`
in plugin.yml makes it a HARD load gate. `provided` from ~/.m2 (install ../search first), and never
bundled: the assembly below copies this plugin's own jar only. -->
<dependency>
<groupId>mx.quest</groupId>
<artifactId>runway-plugin-search</artifactId>
<version>${search.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<scope>provided</scope>
</dependency>
<!-- Lucene — supplied at RUNTIME by the lucene-provider plugin on the shared classloader. PROVIDED here:
compile-only, never bundled into this plugin's own lib/ (that would be a second copy on the shared
classloader). requires: lucene-provider == 10.4.0 in plugin.yml guarantees the exact binaries. -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>${lucene.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analysis-common</artifactId>
<version>${lucene.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-highlighter</artifactId>
<version>${lucene.version}</version>
<scope>provided</scope>
</dependency>
<!-- Tests DO run the real Lucene: at test time it must be on the classpath, so the same jars come in as
`test` scope too (provided is not visible to the test classpath on its own). These are the exact
10.4.0 artifacts lucene-provider ships, so the tests exercise the runtime binaries faithfully. -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-memory</artifactId>
<version>${lucene.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queries</artifactId>
<version>${lucene.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>runway-plugin-search-lucene</finalName>
<plugins>
<!-- Assemble both installable forms: target/search-lucene/ (folder) and the UI zip. NOTE: NO lib/ —
Lucene is NOT bundled here; it comes from the lucene-provider plugin at runtime. -->
<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-lucene"/>
<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-lucene.jar" todir="${stage}"/>
<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-lucene"/>
</touch>
<zip destfile="${project.build.directory}/runway-plugin-search-lucene-${project.version}.zip">
<zipfileset dir="${project.build.directory}" includes="search-lucene/**"/>
</zip>
<echo message="Staged install folder (thin jar, NO bundled Lucene — from lucene-provider): ${stage}"/>
<echo message="UI-uploadable archive: ${project.build.directory}/runway-plugin-search-lucene-${project.version}.zip"/>
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
+316
View File
@@ -0,0 +1,316 @@
#!/usr/bin/env bash
# Prove this release's contract end to end on the PACKAGED Runway host, together with the two plugins it
# requires — the current search (publishes SiteSearchEngine, SearchCorpus and SearchHit.terms) and the code-less
# lucene-provider (the Lucene binaries) — and, when BASELINE_REF is set, prove that it ranks exactly as the baseline:
#
# 1. BASELINE (only when BASELINE_REF is set): search 2.0.0 + search-lucene 3.0.0 (built from git, BASELINE_REF) +
# lucene-provider on the same host jar, a fixture site (pages written for the tiers, stemming, fuzzy and the
# exclusion list, a stored ranking knob), and a fixed set of queries answered by the JSON API.
# 2. CURRENT: the current search + this release + lucene-provider, the same fixture and queries, with the index on
# DISK this time (the app-level settings bind). Every answer — order, URLs, titles, snippets, scores — must be
# byte-identical to the baseline's (the link and terms fields 3.0.0 never had are set aside for the comparison;
# they are checked on their own: each hit carries the words it matched, as the page writes them).
# 3. On the current deployment: the three plugins load with ZERO host-linkage and bean-name/surface warnings, the
# console card and admin fragment render (bean @searchLuceneAdminModel), a settings save of the search plugin's
# exclude list and of this plugin's own knobs reach the next query without a reindex, and the operator's reindex
# POST rebuilds this index and reports its size.
#
# Only the search plugin is installed to ~/.m2 (it is this plugin's compile-time dependency, as in 2.x); everything
# else is PACKAGED offline. Formerly: this plugin compiled against the
# search jar its sibling folder just built. 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 deployments go (default: this plugin's target/)
# VERIFY_LOG_DIR=/dir keep the host logs, the query answers and the diff there (evidence)
# BASELINE_REF=<git ref> the commit carrying search 2.0.0 + search-lucene 3.0.0 (default:
# empty, which skips the before/after comparison with a note);
# SKIP_BASELINE=1 skips it too
set -uo pipefail
HERE="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
VER="$(sed -n 's/^version: *//p' "$HERE/plugin.yml")" # the release under test
REPO="$(cd "$HERE/.." && pwd)"
SEARCH="$REPO/search"
LUCENE_PROVIDER="$REPO/lucene-provider"
# 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
BASELINE_REF="${BASELINE_REF:-}"
if [ -z "$BASELINE_REF" ] && [ "${SKIP_BASELINE:-0}" != 1 ]; then
echo "[verify] BASELINE_REF is not set: skipping the comparison with search 2.0.0 + search-lucene 3.0.0" \
"(set BASELINE_REF to a commit carrying those two versions to run it)"
SKIP_BASELINE=1
fi
M2="${HOME}/.m2/repository/mx/quest"
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=Lucene-Admin-2026; SITE_USER=owner; SITE_PW=Lucene-Site-2026
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"
m2_before="$(ls -d "$M2"/runway-plugin-search-lucene/"$VER" 2>/dev/null)"
echo "[verify] packaging search (the plugin this one requires and compiles against) ..."
( cd "$SEARCH" && "$MVN" -o -q -DskipTests install ) || { echo "search build/install failed"; exit 1; }
echo "[verify] packaging lucene-provider ..."
( cd "$LUCENE_PROVIDER" && "$MVN" -o -q -DskipTests package ) || { echo "lucene-provider build failed"; exit 1; }
echo "[verify] packaging this plugin ..."
( cd "$HERE" && "$MVN" -o -q -DskipTests package ) || { echo "search-lucene 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"
mkdir -p "${VERIFY_TMPDIR:-$HERE/target}"
SCRATCH="$(mktemp -d "${VERIFY_TMPDIR:-$HERE/target}/lucene-verify.XXXXXX")"
PID=""
stop_host() { [ -z "$PID" ] || { kill "$PID" 2>/dev/null; wait "$PID" 2>/dev/null; PID=""; }; }
cleanup() {
if [ -n "${VERIFY_LOG_DIR:-}" ]; then
mkdir -p "$VERIFY_LOG_DIR"
for run in before after; do
[ -d "$SCRATCH/$run" ] || continue
mkdir -p "$VERIFY_LOG_DIR/$run"
cp "$SCRATCH/$run"/*.log "$VERIFY_LOG_DIR/$run/" 2>/dev/null
[ -d "$SCRATCH/$run/answers" ] && cp -r "$SCRATCH/$run/answers" "$VERIFY_LOG_DIR/$run/"
done
cp "$SCRATCH"/*.txt "$VERIFY_LOG_DIR/" 2>/dev/null
fi
# Wait for the host to exit before deleting: a JVM still shutting down rewrites files under external/.
[ "$KEEP" = "yes" ] || { stop_host; rm -rf "$SCRATCH"; }
}
trap cleanup EXIT
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; }
code() { curl -s -o /dev/null -w '%{http_code}' "$@"; }
# --- The fixture: pages written for the tiers, stemming, fuzzy, highlighting and the exclusion list ------------------
page() { # sites-dir slug title description body-html
local t="$1/default/templates"
printf 'path: /%s\ntemplate: _master\ntitle:\n en: "%s"\ndescription:\n en: "%s"\n' "$2" "$3" "$4" > "$t/$2.meta.yml"
printf '<!DOCTYPE html>\n<html lang="en">\n<head><title>%s</title></head>\n<body>\n<header id="site-header"></header>\n<main id="content">\n%s\n</main>\n<footer id="site-footer"></footer>\n</body>\n</html>\n' \
"$3" "$5" > "$t/$2.html"
cp "$t/about.th.xml" "$t/$2.th.xml"
}
fixture() { # sites-dir
page "$1" guide "Runway Deployment Guide" "How to deploy Runway in production." \
"<p>This guide covers the deployment of runway on a single server. Read the runway deployment guide first.</p>"
page "$1" manual "Manual" "" "<p>The cloud deployment guide explains everything about the cloud.</p>"
page "$1" notes "Notes" "Miscellaneous" \
"<p>cloud infrastructure. a long unrelated paragraph about many topics. deployment pipelines. yet another sentence entirely. a helpful guide to nothing.</p>"
page "$1" athletics "Athletics" "Sports club" "<p>They run every morning and they ran yesterday.</p>"
page "$1" handbook "Lucene Handbook" "Search internals" "<p>All about lucene, analyzers and &lt;mark&gt; tags.</p>"
page "$1" pricing "Pricing" "Plans for runway hosting" "<p>Runway hosting plans start small. Deployment support included.</p>"
page "$1" privacy "Privacy" "Runway privacy policy" "<p>runway runway privacy deployment guide</p>"
# A bilingual page whose copy comes ONLY from the site's bundles (decoupled th:text; the template's element is
# empty) -- the kernel indexes it as rendered per language, and this plugin keeps one index per
# language. Its words appear in none of QUERIES, so the 3.0.0 comparison is unaffected.
sed -i '/^locales:/a - "es"' "$1/default/site.yml"
local t="$1/default/templates"
printf 'path: /faculty\nlocalizedPaths:\n es: /facultad\nlocales: [en, es]\ntemplate: _master\ntitle:\n en: Faculty\n es: Profesores\n' > "$t/faculty.meta.yml"
printf '<!DOCTYPE html>\n<html lang="en">\n<head><title>Faculty</title></head>\n<body>\n<header id="site-header"></header>\n<main id="content"><p id="faculty-copy"></p></main>\n<footer id="site-footer"></footer>\n</body>\n</html>\n' > "$t/faculty.html"
sed 's#</thlogic># <attr sel="\#faculty-copy" th:text="\#{verify.faculty}"/>\n</thlogic>#' "$t/about.th.xml" > "$t/faculty.th.xml"
mkdir -p "$1/default/i18n"
printf '\nverify.faculty=Our students learn from researchers.\n' >> "$1/default/i18n/messages.properties"
printf '\nverify.faculty=Nuestros alumnos aprenden con una facultad de excelencia.\n' >> "$1/default/i18n/messages_es.properties"
mkdir -p "$1/default/plugins"
printf 'exclude:\n - privacy\n' > "$1/default/plugins/search.yml"
printf 'titleBoost: 9.5\n' > "$1/default/plugins/search-lucene.yml"
}
QUERIES=("runway" "deployment" "cloud%20deployment%20guide" "runway%20deployment%20guide" "running" "lucane"
"privacy" "hosting%20plans" "mark" "about" "home" "xyzzy%20nothing")
ask_all() { # out-dir
mkdir -p "$1"
local i=0
for q in "${QUERIES[@]}"; do
curl -s "$BASE/search/api?q=$q" > "$1/$(printf '%02d' "$i")-${q//%20/_}.json"
i=$((i + 1))
done
}
# --- One throwaway deployment: wizard, fixture, ACTIVE boot ----------------------------------------------------------
boot() { # log-file (uses DEPLOY_DIR and EXT)
( cd "$DEPLOY_DIR" && exec "$JAVA" -jar "$JAR" --server.port="$PORT" --runway.storage.external="$EXT" ) >"$1" 2>&1 &
PID=$!
}
deploy() { # run-name search-folder lucene-folder [app-level search-lucene.yml]
DEPLOY_DIR="$SCRATCH/$1"; EXT="$DEPLOY_DIR/external"; SITES="$EXT/sites"; LOG="$DEPLOY_DIR/active.log"
mkdir -p "$EXT/plugins" "$EXT/plugin-settings"
cp -r "$2" "$EXT/plugins/search"
cp -r "$LUCENE_PROVIDER/target/lucene-provider" "$EXT/plugins/lucene-provider"
cp -r "$3" "$EXT/plugins/search-lucene"
echo "[verify] $1: booting host (wizard) on :$PORT ..."
boot "$DEPLOY_DIR/wizard.log"
wait_for "$DEPLOY_DIR/wizard.log" "Started RunwayApplication" 90 \
|| { echo "wizard did not start"; tail -20 "$DEPLOY_DIR/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
stop_host
[ -f "$SITES/default/templates/about.th.xml" ] || { echo "the wizard did not seed $SITES/default"; exit 1; }
fixture "$SITES"
# A generous query ceiling: the comparison asks the same questions on both deployments.
printf 'runway:\n plugin:\n search:\n "rate-limit.per-ip-per-minute": 100000\n "rate-limit.per-ip-per-hour": 100000\n' \
> "$EXT/plugin-settings/search.yml"
[ -z "${4:-}" ] || printf '%s\n' "$4" > "$EXT/plugin-settings/search-lucene.yml"
echo "[verify] $1: booting host (ACTIVE) ..."
boot "$LOG"
wait_for "$LOG" "Started RunwayApplication" 90 || { echo "ACTIVE did not start"; tail -20 "$LOG"; exit 1; }
}
# --- 1. The baseline: search 2.0.0 + search-lucene 3.0.0 -------------------------------------------------------------
if [ "${SKIP_BASELINE:-0}" != 1 ]; then
echo "[verify] building the baseline (search + search-lucene at $BASELINE_REF) offline ..."
SRC="$SCRATCH/baseline-src"
mkdir -p "$SRC"
git -C "$REPO" archive "$BASELINE_REF" search search-lucene | tar -x -C "$SRC" \
|| { echo "cannot read $BASELINE_REF from git"; exit 1; }
grep -q '^version: 3.0.0' "$SRC/search-lucene/plugin.yml" && grep -q '^version: 2.0.0' "$SRC/search/plugin.yml" \
|| { echo "$BASELINE_REF does not carry search 2.0.0 + search-lucene 3.0.0"; exit 1; }
( cd "$SRC/search" && "$MVN" -o -q -DskipTests package ) >"$SCRATCH/baseline-build.txt" 2>&1 \
&& ( cd "$SRC/search-lucene" && "$MVN" -o -q -DskipTests package ) >>"$SCRATCH/baseline-build.txt" 2>&1 \
|| { echo "baseline build failed (see baseline-build.txt)"; tail -20 "$SCRATCH/baseline-build.txt"; exit 1; }
deploy before "$SRC/search/target/search" "$SRC/search-lucene/target/search-lucene"
ck "baseline: 3 plugins registered, 0 blocked" "grep -qE 'plugins: 3 registered, 0 blocked' '$LOG'"
ck "baseline: the fixture pages serve" "[ \"\$(code '$BASE/guide')\" = 200 ] && [ \"\$(code '$BASE/handbook')\" = 200 ]"
ask_all "$SCRATCH/before/answers"
grep -E ' WARN ' "$LOG" | grep -E "plugin 'search-lucene'|uses host internals" > "$SCRATCH/baseline-warnings.txt"
echo " (search-lucene 3.0.0 drew $(grep -c "search-lucene" "$SCRATCH/baseline-warnings.txt") warning line(s) naming it)"
stop_host
fi
# --- 2. The release under test: the current search + this release, index on disk -----------------------------------
INDEX_ROOT="$SCRATCH/after/lucene-index"
deploy after "$SEARCH/target/search" "$HERE/target/search-lucene" \
"$(printf 'runway:\n plugin:\n search-lucene:\n storage: disk\n indexRoot: "%s"' "$INDEX_ROOT")"
echo "== plugin load (this release's contract) =="
ck "3 plugins registered, 0 blocked" "grep -qE 'plugins: 3 registered, 0 blocked' '$LOG'"
ck "search-lucene not blocked / quarantined" "! grep -qE \"plugin 'search-lucene' 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-lucene|search)' linkage scan\" '$LOG'"
ck "ZERO bean-name/surface findings" "! grep -qE \"plugin '(search-lucene|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 \"search-lucene|mx\\.quest\\.searchlucene\""
ck "no collision / degraded / missing class" "! grep -qiE 'collision|duplicate key|degraded|NoClassDefFound|ClassNotFound' '$LOG'"
ck "Lucene is NOT bundled in search-lucene" "[ ! -d '$EXT/plugins/search-lucene/lib' ]"
ck "the fixture pages serve" "[ \"\$(code '$BASE/guide')\" = 200 ] && [ \"\$(code '$BASE/handbook')\" = 200 ]"
ck "no plugin-owned /search page (404)" "[ \"\$(code '$BASE/search?q=runway')\" = 404 ]"
echo "== ranking: the same answers as 3.0.0 =="
ask_all "$SCRATCH/after/answers"
ck "the Lucene engine serves (a 1-edit typo finds the handbook)" "grep -q '\"url\":\"/handbook\"' '$SCRATCH/after/answers/05-lucane.json'"
ck "the search plugin's exclusion applies through SearchCorpus (no /privacy for 'runway')" \
"grep -q '\"url\":\"/guide\"' '$SCRATCH/after/answers/00-runway.json' && ! grep -q '/privacy' '$SCRATCH/after/answers/00-runway.json'"
ck "each hit carries the words it matched and a link marked with them" \
"grep -qE '\"link\":\"/[^\"]*#rw-hl=[^\"]+\",\"terms\":\\[\"[^\"]+' '$SCRATCH/after/answers/04-running.json'"
ck "…as the page writes them, at least every word its snippet marks (running: run, and ran within one edit)" \
"python3 -I -c 'import json,re,sys; r=json.load(open(sys.argv[1]))[\"results\"]; ok=all(h[\"terms\"] and set(m.lower() for m in re.findall(\"<mark>(.*?)</mark>\", h[\"snippet\"])) <= set(h[\"terms\"]) for h in r); sys.exit(0 if r and ok else 1)' '$SCRATCH/after/answers/04-running.json'"
if [ "${SKIP_BASELINE:-0}" != 1 ]; then
# 3.0.0 predates link/terms (search 2.1.0): compare everything else, byte for byte.
mkdir -p "$SCRATCH/after/compared"
for f in "$SCRATCH"/after/answers/*.json; do
python3 -I -c 'import re,sys; s=open(sys.argv[1],encoding="utf-8").read(); sys.stdout.write(re.sub(r",\"link\":\"(?:[^\"\\\\]|\\\\.)*\",\"terms\":\[(?:\"(?:[^\"\\\\]|\\\\.)*\",?)*\]", "", s))' \
"$f" > "$SCRATCH/after/compared/$(basename "$f")"
done
diff -r "$SCRATCH/before/answers" "$SCRATCH/after/compared" > "$SCRATCH/ranking-diff.txt"
ck "every answer (order, URLs, titles, snippets, scores) is byte-identical to 3.0.0's (${#QUERIES[@]} queries)" \
"[ ! -s '$SCRATCH/ranking-diff.txt' ] && [ \$(ls '$SCRATCH/after/answers' | wc -l) = ${#QUERIES[@]} ]"
ck "…and the answers are not trivially empty" "[ \$(cat '$SCRATCH'/after/answers/*.json | grep -o '\"url\"' | wc -l) -ge 15 ]"
fi
echo "== one index per language, bundle strings included =="
ck "the page's Spanish copy is rendered from the bundle (fixture)" "curl -s '$BASE/es/facultad' | grep -q 'facultad de excelencia'"
curl -s "$BASE/search/api?q=excelencia&lang=es" > "$SCRATCH/after/es.json"
ck "a Spanish bundle string is found in Spanish, at the Spanish address, with the Spanish title" \
"grep -q '\"url\":\"/es/facultad\"' '$SCRATCH/after/es.json' && grep -q '\"title\":\"Profesores\"' '$SCRATCH/after/es.json'"
ck "the Spanish analyzer stems ('facultades' finds 'facultad')" \
"curl -s '$BASE/search/api?q=facultades&lang=es' | grep -q '\"url\":\"/es/facultad\"'"
ck "the English analyzer stems ('researcher' finds 'researchers')" \
"curl -s '$BASE/search/api?q=researcher&lang=en' | grep -q '\"url\":\"/faculty\"'"
ck "English does not search the Spanish text" "! curl -s '$BASE/search/api?q=excelencia&lang=en' | grep -q '/faculty'"
ck "a page in English only is still found from Spanish" \
"curl -s '$BASE/search/api?q=lucene&lang=es' | grep -q '\"url\":\"/handbook\"'"
echo "== storage: the app-level settings bind (disk) =="
ck "the site's index lives on disk under indexRoot/default, one folder per language" \
"[ -d '$INDEX_ROOT/default/en' ] && [ -d '$INDEX_ROOT/default/es' ] && ls '$INDEX_ROOT/default/es' | grep -q ."
echo "== the console (signed in as the site owner) =="
token() { grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//'; }
sc() { curl -s -H 'Accept-Language: en' -c "$SCRATCH/cookies.jar" -b "$SCRATCH/cookies.jar" "$@"; }
sc -o /dev/null -X POST "$BASE/login" --data-urlencode "username=$SITE_USER" --data-urlencode "password=$SITE_PW" \
--data-urlencode "_csrf=$(sc "$BASE/login" | token)"
LS="$BASE/__admin/plugins/search-lucene/settings"
sc "$LS" > "$SCRATCH/lucene-settings-0.html"
DOCS="$(sed -n 's:.*id="la-pages"[^>]*>\([0-9]*\)<.*:\1:p' "$SCRATCH/lucene-settings-0.html" | head -1)"
ck "the admin fragment renders (bean @searchLuceneAdminModel): engine search/lucene" \
"grep -q 'id=\"la-engine\"[^>]*>search/lucene<' '$SCRATCH/lucene-settings-0.html'"
ck "…the indexed-item count (${DOCS:-none})" "[ -n '$DOCS' ] && [ '$DOCS' -ge 8 ]"
ck "…the storage mode (disk)" "grep -q 'id=\"la-storage\"[^>]*>disk<' '$SCRATCH/lucene-settings-0.html'"
ck "…and the stored title boost (9.5)" "grep -q 'id=\"la-boost\"[^>]*>9.5<' '$SCRATCH/lucene-settings-0.html'"
sc -L "$BASE/__admin" > "$SCRATCH/dashboard.html"
ck "the dashboard card renders the count" "grep -q 'id=\"lc-pages\"[^>]*>$DOCS<' '$SCRATCH/dashboard.html'"
echo "== settings saves reach the next query, without a reindex =="
SS="$BASE/__admin/plugins/search/settings"
sc -o /dev/null -X POST "$SS" --data-urlencode "enabled=true" --data-urlencode "exclude=guide" \
--data-urlencode "_csrf=$(sc "$SS" | token)"
curl -s "$BASE/search/api?q=runway%20deployment%20guide" > "$SCRATCH/after-exclude.json"
ck "search's exclude list saved (guide in, privacy out of the list)" \
"grep -q 'guide' '$SITES/default/plugins/search.yml' && ! grep -q 'privacy' '$SITES/default/plugins/search.yml'"
ck "…the newly excluded page leaves this index at once" "! grep -q '\"url\":\"/guide\"' '$SCRATCH/after-exclude.json'"
ck "…and the no-longer-excluded page joins it" "grep -q '\"url\":\"/privacy\"' '$SCRATCH/after-exclude.json'"
sc -o /dev/null -X POST "$LS" --data-urlencode "fuzzy=false" --data-urlencode "titleBoost=9.5" \
--data-urlencode "_csrf=$(token < "$SCRATCH/lucene-settings-0.html")"
ck "this plugin's knobs saved (fuzzy off)" "grep -q 'fuzzy: false' '$SITES/default/plugins/search-lucene.yml'"
ck "…the typo no longer matches on the next query" "curl -s '$BASE/search/api?q=lucane' | grep -q '\"count\":0'"
ck "…while the exact term still does" "curl -s '$BASE/search/api?q=lucene' | grep -q '\"url\":\"/handbook\"'"
echo "== the operator's reindex rebuilds this index =="
sc "$SS" > "$SCRATCH/search-settings.html"
sc -X POST "$BASE/search/reindex" --data-urlencode "_csrf=$(token < "$SCRATCH/search-settings.html")" > "$SCRATCH/reindex.txt"
ck "POST /search/reindex reports this engine's fresh count (${DOCS:-none})" "grep -qx 'Search index rebuilt\\. ($DOCS)' '$SCRATCH/reindex.txt'"
ck "a GET does not reindex (404)" "[ \"\$(sc -o /dev/null -w '%{http_code}' '$BASE/search/reindex')\" = 404 ]"
echo "== the build wrote nothing to the local Maven repository =="
m2_after="$(ls -d "$M2"/runway-plugin-search-lucene/"$VER" 2>/dev/null)"
ck "search-lucene itself is never installed to ~/.m2 (only its compile dependency, search, is)" "[ -z '$m2_after' ] || [ '$m2_after' = '$m2_before' ]"
ck "still no WARN/ERROR names the plugin after the run" "! grep -E ' (WARN|ERROR) ' '$LOG' | grep -qiE \"search-lucene|mx\\.quest\\.searchlucene\""
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,33 @@
package mx.quest.searchlucene;
import java.util.regex.Pattern;
/**
* Reduces a page's raw HTML source to indexable plain text: drops {@code <script>}/{@code <style>} blocks and
* comments, strips the remaining tags, decodes a handful of common entities, and collapses whitespace. This is
* a best-effort text extraction for full-text indexing — not a strict HTML parser — so a malformed page still
* yields reasonable searchable text.
*/
final class HtmlText {
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 WS = Pattern.compile("\\s+");
private HtmlText() {
}
static String toText(String html) {
if (html == null || html.isBlank()) {
return "";
}
String s = SCRIPT_STYLE.matcher(html).replaceAll(" ");
s = COMMENT.matcher(s).replaceAll(" ");
s = TAG.matcher(s).replaceAll(" ");
s = s.replace("&nbsp;", " ").replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">")
.replace("&quot;", "\"").replace("&#39;", "'").replace("&apos;", "'");
return WS.matcher(s).replaceAll(" ").strip();
}
}
@@ -0,0 +1,123 @@
package mx.quest.searchlucene;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Supplier;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.ar.ArabicAnalyzer;
import org.apache.lucene.analysis.bg.BulgarianAnalyzer;
import org.apache.lucene.analysis.ca.CatalanAnalyzer;
import org.apache.lucene.analysis.cz.CzechAnalyzer;
import org.apache.lucene.analysis.da.DanishAnalyzer;
import org.apache.lucene.analysis.de.GermanAnalyzer;
import org.apache.lucene.analysis.el.GreekAnalyzer;
import org.apache.lucene.analysis.en.EnglishAnalyzer;
import org.apache.lucene.analysis.es.SpanishAnalyzer;
import org.apache.lucene.analysis.eu.BasqueAnalyzer;
import org.apache.lucene.analysis.fi.FinnishAnalyzer;
import org.apache.lucene.analysis.fr.FrenchAnalyzer;
import org.apache.lucene.analysis.gl.GalicianAnalyzer;
import org.apache.lucene.analysis.hi.HindiAnalyzer;
import org.apache.lucene.analysis.hu.HungarianAnalyzer;
import org.apache.lucene.analysis.hy.ArmenianAnalyzer;
import org.apache.lucene.analysis.id.IndonesianAnalyzer;
import org.apache.lucene.analysis.it.ItalianAnalyzer;
import org.apache.lucene.analysis.lt.LithuanianAnalyzer;
import org.apache.lucene.analysis.lv.LatvianAnalyzer;
import org.apache.lucene.analysis.nl.DutchAnalyzer;
import org.apache.lucene.analysis.no.NorwegianAnalyzer;
import org.apache.lucene.analysis.pt.PortugueseAnalyzer;
import org.apache.lucene.analysis.ro.RomanianAnalyzer;
import org.apache.lucene.analysis.ru.RussianAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.sv.SwedishAnalyzer;
import org.apache.lucene.analysis.th.ThaiAnalyzer;
import org.apache.lucene.analysis.tr.TurkishAnalyzer;
/**
* Chooses a Lucene {@link Analyzer} per content/query language, so a site's pages are tokenized <b>and
* stemmed</b> for the language they are written in — a query for {@code "running"} matches a page that says
* {@code "run"}, a Spanish query for {@code "corriendo"} matches {@code "correr"}, and so on. Where Lucene ships
* a language-specific analyzer (which bundles that language's stopword list and stemmer), that analyzer is used;
* for any language Lucene has no analyzer for — or an unknown/blank language — it falls back to
* {@link StandardAnalyzer} (tokenize + lowercase, no stemming), which is always correct, just less clever.
*
* <p><b>Why the same analyzer must be used at index and query time:</b> stemming is an analysis-time transform.
* If the index stemmed {@code "running" → "run"} but the query analyzer did not, the query term {@code "running"}
* would never match the indexed term {@code "run"}. This class is the single source of truth for "the analyzer
* for language X", called from both the indexer and the searcher, so the two can never drift.
*
* <p>Analyzers are <b>immutable and thread-safe</b> once built, and building one is not free (it reads a
* stopword resource), so instances are cached per language key. The lookup key is the lowercased ISO language
* code (e.g. {@code "en"}, {@code "es"}); a full {@link Locale} is reduced to its language.
*/
final class LocaleAnalyzers {
/** Language code → a factory for that language's analyzer. Absent code ⇒ StandardAnalyzer fallback. */
private static final Map<String, Supplier<Analyzer>> BY_LANGUAGE = Map.ofEntries(
Map.entry("ar", ArabicAnalyzer::new),
Map.entry("bg", BulgarianAnalyzer::new),
Map.entry("ca", CatalanAnalyzer::new),
Map.entry("cs", CzechAnalyzer::new),
Map.entry("da", DanishAnalyzer::new),
Map.entry("de", GermanAnalyzer::new),
Map.entry("el", GreekAnalyzer::new),
Map.entry("en", EnglishAnalyzer::new),
Map.entry("es", SpanishAnalyzer::new),
Map.entry("eu", BasqueAnalyzer::new),
Map.entry("fi", FinnishAnalyzer::new),
Map.entry("fr", FrenchAnalyzer::new),
Map.entry("gl", GalicianAnalyzer::new),
Map.entry("hi", HindiAnalyzer::new),
Map.entry("hu", HungarianAnalyzer::new),
Map.entry("hy", ArmenianAnalyzer::new),
Map.entry("id", IndonesianAnalyzer::new),
Map.entry("it", ItalianAnalyzer::new),
Map.entry("lt", LithuanianAnalyzer::new),
Map.entry("lv", LatvianAnalyzer::new),
Map.entry("nl", DutchAnalyzer::new),
Map.entry("no", NorwegianAnalyzer::new),
Map.entry("pt", PortugueseAnalyzer::new),
Map.entry("ro", RomanianAnalyzer::new),
Map.entry("ru", RussianAnalyzer::new),
Map.entry("sv", SwedishAnalyzer::new),
Map.entry("th", ThaiAnalyzer::new),
Map.entry("tr", TurkishAnalyzer::new));
/** Built analyzers, cached by language key. Analyzers are thread-safe, so caching is a pure win. */
private final ConcurrentMap<String, Analyzer> cache = new ConcurrentHashMap<>();
/**
* The analyzer for {@code locale}'s language — a stemming language analyzer where Lucene ships one, else
* {@link StandardAnalyzer}. Never {@code null}. The returned analyzer is shared and must not be closed by the
* caller (the engine owns lifecycle via {@link #close()}).
*
* @param locale the content/query locale; a {@code null} locale is treated as the standard fallback
*/
Analyzer forLocale(Locale locale) {
String lang = (locale == null) ? "" : locale.getLanguage().toLowerCase(Locale.ROOT);
return forLanguage(lang);
}
/** As {@link #forLocale(Locale)} but keyed directly by an ISO language code (blank/unknown ⇒ standard). */
Analyzer forLanguage(String language) {
String lang = (language == null) ? "" : language.toLowerCase(Locale.ROOT);
return cache.computeIfAbsent(lang, k -> {
Supplier<Analyzer> factory = BY_LANGUAGE.get(k);
return (factory != null) ? factory.get() : new StandardAnalyzer();
});
}
/** Whether a genuine language analyzer (with stemming) exists for {@code language} — for the console/tests. */
static boolean hasLanguageAnalyzer(String language) {
return language != null && BY_LANGUAGE.containsKey(language.toLowerCase(Locale.ROOT));
}
/** Release every cached analyzer (called when the engine is disposed). Idempotent. */
void close() {
cache.values().forEach(Analyzer::close);
cache.clear();
}
}
@@ -0,0 +1,35 @@
package mx.quest.searchlucene;
/**
* Read-only status model for the plugin's console surfaces (dashboard card + admin fragment), read by template
* bean name, e.g. {@code ${@searchLuceneAdminModel.indexedPages(tenantSiteId)}}. It delegates to the live
* {@link LuceneSearchEngine} so the numbers reflect the actual per-site index and effective ranking config.
*/
public class LuceneAdminModel {
private final LuceneSearchEngine engine;
public LuceneAdminModel(LuceneSearchEngine engine) {
this.engine = engine;
}
/** How many pages are in this site's Lucene index right now. */
public int indexedPages(String siteId) {
return engine.indexedDocuments(siteId);
}
/** The engine key (constant) — shown so an operator can confirm which engine is active. */
public String engineKey() {
return LuceneSearchEngine.KEY;
}
/** The effective title boost applied to this site's queries. */
public String titleBoost(String siteId) {
return String.valueOf(engine.effectiveTitleBoost(siteId));
}
/** The active index storage mode ({@code heap} or {@code disk}) — an app-level (platform) setting. */
public String storageMode() {
return engine.storageMode();
}
}
@@ -0,0 +1,690 @@
package mx.quest.searchlucene;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Pattern;
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;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.StoredFields;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.uhighlight.DefaultPassageFormatter;
import org.apache.lucene.search.uhighlight.UnifiedHighlighter;
import org.apache.lucene.store.ByteBuffersDirectory;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.MMapDirectory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A Lucene-backed {@link SiteSearchEngine} — the {@code search-lucene} plugin's contribution to the {@code search}
* plugin's engine SPI. It builds a per-site full-text index over the search plugin's {@link SearchCorpus} — every
* published page and content-source item (the entries plugins publish, …) the site has not excluded from search — indexing each
* item's <b>title</b>,
* <b>description</b> and <b>body text</b> (extracted from the item's indexable material with {@link HtmlText})
* and answers a
* query with a <b>tiered, constant-score</b> relevance model layered on top of Lucene's BM25 term matching:
*
* <ol>
* <li><b>any-terms</b> — each analyzed query term as a {@code SHOULD} {@link TermQuery} across title (boosted),
* description (boosted) and body, plus optional typo-tolerant {@link FuzzyQuery} clauses. This is the
* BM25-scored base layer that separates documents <em>within</em> a tier.</li>
* <li><b>near phrase (body)</b> — the query terms as a {@link PhraseQuery} with a small slop, a
* {@code ConstantScoreQuery} worth {@code tierNearPhrase}: proximity beats scattered terms.</li>
* <li><b>exact phrase (body)</b> — the query as an exact ({@code slop=0}) body phrase, worth
* {@code tierPhraseBody}.</li>
* <li><b>exact phrase (title)</b> — the query as an exact title phrase, worth {@code tierPhraseTitle}: a page
* whose <em>title</em> is the query is the strongest possible match.</li>
* <li><b>all-terms-anywhere</b> — a {@code ConstantScoreQuery} worth {@code tierAllTerms} that fires only when
* every query term appears somewhere in the document, lifting complete matches above partial ones.</li>
* </ol>
*
* <p>The tiers are additive {@code SHOULD} clauses, so a hit's score is the sum of the tiers it satisfies — an
* exact-title-phrase hit outranks a near-phrase hit, which outranks a scattered-terms hit, deterministically.
* Analysis (tokenization + <b>stemming</b>) is <b>per-locale</b> via {@link LocaleAnalyzers}, so a query matches
* a stemmed surface form (an English query {@code running} matches {@code run}); the <em>same</em> analyzer is
* used at index and query time so the two never drift. Result snippets are <b>query-focused and highlighted</b>:
* {@link UnifiedHighlighter} wraps the matched terms in {@code <mark>…</mark>} within the best-matching body
* passage, falling back to a plain leading snippet if highlighting yields nothing. Each hit also carries the words
* the query matched as the page writes them ({@link MatchedForms}), which the page the result opens highlights.
*
* <p>The index covers the {@link SearchCorpus} the search plugin publishes — every published item, pages and
* content-source items alike, minus the site's search exclusions. It is the same corpus the built-in engine
* indexes, so what is searchable never depends on which engine serves the query, and the exclusion rule lives in
* one place (the search plugin).
*
* <p><b>One index per language (since 3.2.0).</b> Each item is indexed once per language it exists in — its title,
* description and body in that language (the body is the page as the kernel renders it there, bundle strings
* included), linked at {@link CatalogEntry#pathFor} that language. A site has one index per language it speaks,
* analyzed with that language's analyzer: the language's own documents plus, for an item that does not exist in
* it, 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 page published in one language only is still found from every other. A query searches
* the index of its own language ({@link SearchQuery#locale()}), with that index's analyzer; a language the site
* does not speak searches the site default's. A fallback document is analyzed with the index's analyzer, not its
* own language's — so it matches on exact and lightly stemmed forms, not on every inflection. Before 3.2.0 a site
* had one index of primary-locale documents analyzed with the default language's analyzer, so every language
* searched default-language text.
*
* <p>The index lives in heap ({@link ByteBuffersDirectory}) or on disk ({@link MMapDirectory}) per the app-level
* {@link LuceneStorageProps}. It is cached per site, dropped by {@link #invalidate} — which the plugin's
* {@code SiteEventListener} calls for every change that may reshape the corpus (a page write, a content source's
* change, a site lifecycle event, any plugin's settings save) — rebuilt eagerly by the operator's {@link #reindex}
* action, and additionally refreshed by a short TTL (the backstop for changes no event announces). The engine registers at {@link #priority()}
* 100 (it supersedes the built-in engine) and is always {@link #available(String) available} — it builds on
* demand. Per the SPI contract, {@link #search(SearchQuery)} <b>never throws</b>: any failure (I/O, a corrupt
* index) is logged and returns no results.
*/
public class LuceneSearchEngine implements SiteSearchEngine, AutoCloseable {
static final String KEY = "search/lucene";
private static final Logger log = LoggerFactory.getLogger(LuceneSearchEngine.class);
/** Indexed + query field names. */
private static final String F_TITLE = "title";
private static final String F_DESCRIPTION = "description";
private static final String F_BODY = "body";
/** Stored (display-only) field names. */
private static final String S_URL = "s_url";
private static final String S_TITLE = "s_title";
private static final String S_DESCRIPTION = "s_description";
private static final String S_BODY = "s_body";
private static final long FRESHNESS_MILLIS = 30_000L;
private static final int SNIPPET_MAX = 200;
private static final int MAX_QUERY_TERMS = 32;
/** Slop for the "near phrase" tier — terms may be up to this far apart / lightly reordered. */
private static final int NEAR_SLOP = 1;
/** Private markers the {@link UnifiedHighlighter} wraps hits in; rewritten to {@code <mark>}/{@code </mark>}
* only after the surrounding passage has been HTML-escaped, so a page's own {@code <} can't forge a tag. */
private static final char MARK_OPEN_CH = '\u0001';
private static final char MARK_CLOSE_CH = '\u0002';
private static final String MARK_OPEN = String.valueOf(MARK_OPEN_CH);
private static final String MARK_CLOSE = String.valueOf(MARK_CLOSE_CH);
/** Guards the per-site subfolder used for a disk index (path-traversal / injection safe). */
private static final Pattern SAFE_SITE_ID = Pattern.compile("[a-z0-9][a-z0-9._-]{0,63}");
/** A language subdirectory name: an ISO 639 code as {@link Locale#getLanguage()} returns it. */
private static final Pattern SAFE_LANGUAGE = Pattern.compile("[a-z]{2,8}");
private final SearchCorpus corpus;
private final Sites sites;
private final PluginSettings settings;
private final LuceneStorageProps storage;
private final LocaleAnalyzers analyzers = new LocaleAnalyzers();
private final Map<String, CachedIndex> cache = new ConcurrentHashMap<>();
private final Map<String, Object> locks = new ConcurrentHashMap<>();
/**
* Bumped by every {@link #invalidate}. A build that started before an invalidation may have read the old corpus,
* so it is kept only as already-stale: it answers the query that built it, and the next query rebuilds.
*/
private final AtomicLong generation = new AtomicLong();
/** Site index folders already checked for a 3.1.x index (see {@link #deleteOldLayout}). */
private final java.util.Set<Path> oldLayoutChecked = ConcurrentHashMap.newKeySet();
/**
* The sites whose index this thread is building. A build renders pages, and a page's widget that searched
* the same site would re-enter the build (the per-site lock is reentrant) and recurse; such a search answers
* nothing instead.
*/
private static final ThreadLocal<java.util.Set<String>> BUILDING = ThreadLocal.withInitial(java.util.HashSet::new);
/**
* @param corpus what to index: the search plugin's corpus (the content listing minus the site's exclusions)
* @param sites the kernel's site lookup (a site's default locale chooses the analyzer)
* @param settings this plugin's per-site settings (the ranking knobs), read per query
* @param storage the app-level storage settings (heap or disk)
*/
public LuceneSearchEngine(SearchCorpus corpus, Sites sites, PluginSettings settings, LuceneStorageProps storage) {
this.corpus = Objects.requireNonNull(corpus, "corpus");
this.sites = Objects.requireNonNull(sites, "sites");
this.settings = Objects.requireNonNull(settings, "settings");
this.storage = Objects.requireNonNull(storage, "storage");
}
/** One language's index: its directory, the analyzer used to build it (reused at query time) and its size. */
private record LanguageIndex(Directory dir, Analyzer analyzer, int documents) {
}
/**
* A built per-site index: one {@link LanguageIndex} per language the site speaks, the site default's language
* (the index a query in another language searches), the number of items indexed, and when it was built.
*/
private record CachedIndex(Map<String, LanguageIndex> languages, String defaultLanguage, int items,
long builtAtMillis) {
/** The same index, marked as already past its freshness window. */
CachedIndex stale() {
return new CachedIndex(languages, defaultLanguage, items, 0L);
}
/** The index a query in {@code locale} searches; the site default's when the site lacks that language. */
LanguageIndex forQuery(Locale locale) {
LanguageIndex index = languages.get(locale.getLanguage());
return index != null ? index : languages.get(defaultLanguage);
}
void close() {
languages.values().forEach(l -> closeQuietly(l.dir()));
}
}
@Override
public String key() {
return KEY;
}
@Override
public int priority() {
return 100; // supersede the built-in engine wherever this plugin is installed
}
@Override
public List<SearchHit> search(SearchQuery query) {
if (BUILDING.get().contains(query.siteId())) {
return List.of(); // a search from inside this site's own index build (see BUILDING)
}
LanguageIndex index;
try {
index = index(query.siteId()).forQuery(query.locale());
} catch (RuntimeException e) {
log.warn("lucene index unavailable for site '{}': {}", query.siteId(), e.toString());
return List.of();
}
if (index == null || index.documents() == 0) {
return List.of();
}
List<String> terms = analyze(index.analyzer(), query.text());
if (terms.isEmpty()) {
return List.of();
}
RankingConfig ranking = ranking(query.siteId());
Query q = buildQuery(terms, ranking);
try (DirectoryReader reader = DirectoryReader.open(index.dir())) {
IndexSearcher searcher = new IndexSearcher(reader);
TopDocs top = searcher.search(q, Math.max(1, query.limit()));
String[] highlights = highlight(searcher, index.analyzer(), q, top);
StoredFields stored = searcher.storedFields();
MatchedForms matched = MatchedForms.forQuery(index.analyzer(), terms, ranking.fuzzy());
List<SearchHit> hits = new ArrayList<>(top.scoreDocs.length);
for (int i = 0; i < top.scoreDocs.length; i++) {
ScoreDoc sd = top.scoreDocs[i];
Document d = stored.document(sd.doc);
String snippet = snippet(highlights[i], d);
List<String> forms = matched.in(
List.of(nonNull(d.get(S_TITLE)), nonNull(d.get(S_DESCRIPTION)), nonNull(d.get(S_BODY))));
hits.add(new SearchHit(d.get(S_URL), d.get(S_TITLE), snippet, sd.score, forms));
}
return List.copyOf(hits);
} catch (IOException | RuntimeException e) {
log.warn("lucene search failed for site '{}': {}", query.siteId(), e.toString());
return List.of(); // an SPI never throws for a query; fall back to no results
}
}
/**
* The SPI's manual-reindex hook: drops the cached index and rebuilds it <b>now</b> from current content,
* returning the fresh document count — so the operator's reindex action rebuilds this engine too, not only
* the built-in one. A failed rebuild logs and reports {@code 0}, per the SPI's never-throw posture.
*/
@Override
public int reindex(String siteId) {
corpus.refresh(siteId); // out-of-band edits fire no event; refresh the shared listing before rebuilding
invalidate(siteId);
return indexedDocuments(siteId);
}
// ------------------------------------------------------------------------------------------------- console
/**
* The number of items (pages and content) currently in this site's index — items, not per-language documents
* (builds/refreshes it if needed) — for the console.
*/
public int indexedDocuments(String siteId) {
try {
return index(siteId).items();
} catch (RuntimeException e) {
return 0;
}
}
/** The effective per-tenant title boost (for the console). */
public float effectiveTitleBoost(String siteId) {
return ranking(siteId).titleBoost();
}
/** The active storage mode ({@code heap}/{@code disk}) — for the console. */
public String storageMode() {
return storage.isDisk() ? "disk" : "heap";
}
// ----------------------------------------------------------------------------------------------- lifecycle
/**
* 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();
evict(siteId);
}
private void evict(String siteId) {
CachedIndex removed = cache.remove(siteId);
if (removed != null) {
removed.close();
}
}
/** Release every cached directory and analyzer (Spring calls this on context shutdown). */
@Override
public void close() {
cache.values().forEach(CachedIndex::close);
cache.clear();
analyzers.close();
}
// --------------------------------------------------------------------------------------------- index build
private CachedIndex index(String siteId) {
long now = System.currentTimeMillis();
CachedIndex cached = cache.get(siteId);
if (cached != null && now - cached.builtAtMillis() < FRESHNESS_MILLIS) {
return cached;
}
synchronized (locks.computeIfAbsent(siteId, k -> new Object())) {
cached = cache.get(siteId);
if (cached != null && System.currentTimeMillis() - cached.builtAtMillis() < FRESHNESS_MILLIS) {
return cached;
}
long started = generation.get();
CachedIndex fresh;
BUILDING.get().add(siteId);
try {
fresh = build(siteId);
} finally {
BUILDING.get().remove(siteId);
}
if (generation.get() != started) {
fresh = fresh.stale(); // a change arrived mid-build: this one may hold the old corpus
}
CachedIndex prev = cache.put(siteId, fresh);
if (prev != null) {
prev.close();
}
return fresh;
}
}
/** One item's indexed fields in one language. */
private record IndexedText(String url, String title, String description, String body) {
}
/** An item's primary-locale fields and the languages it has its own documents in, while views are assembled. */
private record Item(IndexedText primary, java.util.Set<String> languages) {
}
/**
* Builds every language index of a site (see the class comment). Each item's text is read once per language it
* exists in and reused by every index that holds it. An unknown site gets one empty index for English.
*/
private CachedIndex build(String siteId) {
SiteView site = sites.find(siteId).orElse(null);
Locale siteDefault = site == null ? Locale.ENGLISH : site.defaultLocale();
Map<String, List<IndexedText>> own = new java.util.LinkedHashMap<>();
List<Item> items = new ArrayList<>();
try {
for (CatalogEntry entry : corpus.corpus(siteId)) { // empty for an unknown site
Locale primary = entry.ref().primaryLocale(siteDefault);
java.util.Set<String> languages = new java.util.LinkedHashSet<>();
IndexedText primaryText = null;
List<Locale> locales = entry.ref().locales().isEmpty() ? List.of(siteDefault) : entry.ref().locales();
for (Locale locale : locales) {
if (!languages.add(locale.getLanguage())) {
continue;
}
IndexedText text = text(siteId, entry, locale);
own.computeIfAbsent(locale.getLanguage(), k -> new ArrayList<>()).add(text);
if (locale.getLanguage().equals(primary.getLanguage())) {
primaryText = text;
}
}
items.add(new Item(primaryText != null ? primaryText : text(siteId, entry, primary),
java.util.Set.copyOf(languages)));
}
} catch (RuntimeException e) {
log.warn("lucene corpus read failed for site '{}': {}", siteId, e.toString());
}
java.util.Set<String> viewLanguages = new java.util.LinkedHashSet<>();
viewLanguages.add(siteDefault.getLanguage());
if (site != null) {
site.locales().forEach(l -> viewLanguages.add(l.getLanguage()));
}
viewLanguages.addAll(own.keySet());
Map<String, LanguageIndex> indexes = new java.util.HashMap<>();
for (String language : viewLanguages) {
List<IndexedText> view = new ArrayList<>(own.getOrDefault(language, List.of()));
for (Item item : items) {
if (!item.languages().contains(language)) {
view.add(item.primary());
}
}
indexes.put(language, write(siteId, language, view));
}
return new CachedIndex(Map.copyOf(indexes), siteDefault.getLanguage(), items.size(),
System.currentTimeMillis());
}
/** The item's fields in {@code locale}: title, description and body in that language, at its address there. */
private IndexedText text(String siteId, CatalogEntry entry, Locale locale) {
String title = localized(entry.ref().title(), locale, entry.ref().id());
String description = localized(entry.ref().description(), locale, "");
String body = HtmlText.toText(corpus.indexableText(siteId, entry, locale));
return new IndexedText(entry.pathFor(locale), title, description, body);
}
/** Writes one language's index with that language's analyzer; a failed write leaves what was added so far. */
private LanguageIndex write(String siteId, String language, List<IndexedText> texts) {
Analyzer analyzer = analyzers.forLanguage(language);
Directory dir;
try {
dir = newDirectory(siteId, language);
} catch (IOException e) {
log.warn("lucene directory init failed for site '{}' ({}), falling back to heap: {}", siteId, language,
e.toString());
dir = new ByteBuffersDirectory();
}
int docs = 0;
try (IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(analyzer))) {
writer.deleteAll(); // rebuild-from-scratch semantics for a disk directory that already had content
for (IndexedText text : texts) {
Document doc = new Document();
doc.add(new TextField(F_TITLE, text.title(), Field.Store.NO));
doc.add(new TextField(F_DESCRIPTION, text.description(), Field.Store.NO));
// Body is BOTH analyzed (for matching) and stored (so the highlighter can re-analyze the source).
doc.add(new TextField(F_BODY, text.body(), Field.Store.YES));
doc.add(new StoredField(S_URL, text.url()));
doc.add(new StoredField(S_TITLE, text.title()));
doc.add(new StoredField(S_DESCRIPTION, text.description()));
doc.add(new StoredField(S_BODY, text.body()));
writer.addDocument(doc);
docs++;
}
} catch (IOException | RuntimeException e) {
log.warn("lucene index build failed for site '{}' ({}): {}", siteId, language, e.toString());
}
return new LanguageIndex(dir, analyzer, docs);
}
/**
* A directory for one language of {@code siteId}: an in-memory {@link ByteBuffersDirectory} in heap mode, or a
* memory-mapped {@link MMapDirectory} under {@code indexRoot/<siteId>/<language>} in disk mode. The site id is
* validated against {@link #SAFE_SITE_ID}, the language against {@link #SAFE_LANGUAGE}, and the resolved path is
* asserted to stay under the (normalized, absolute) index root, so a crafted id can never escape the index tree
* — even though site ids are already path-safe upstream, storage paths get their own guard (defense in depth for
* an operator-set root). Index files a 3.1.x build left directly under {@code indexRoot/<siteId>} (one index per
* site) are deleted, so the old index does not linger beside the new ones.
*/
static boolean isLuceneFile(String name) {
return name.startsWith(org.apache.lucene.index.IndexFileNames.SEGMENTS) || name.equals("write.lock")
|| org.apache.lucene.index.IndexFileNames.CODEC_FILE_PATTERN.matcher(name).matches();
}
private Directory newDirectory(String siteId, String language) throws IOException {
if (!storage.isDisk()) {
return new ByteBuffersDirectory();
}
if (!SAFE_SITE_ID.matcher(siteId).matches()) {
throw new IOException("unsafe site id for a disk index: '" + siteId + "'");
}
if (!SAFE_LANGUAGE.matcher(language).matches()) {
throw new IOException("unsafe language for a disk index: '" + language + "'");
}
Path root = Path.of(storage.getIndexRoot()).toAbsolutePath().normalize();
Path siteDir = root.resolve(siteId).normalize();
Path languageDir = siteDir.resolve(language).normalize();
if (!languageDir.startsWith(root) || !languageDir.getParent().equals(siteDir)) {
throw new IOException("index path escapes the index root: " + languageDir);
}
Files.createDirectories(languageDir);
deleteOldLayout(siteDir);
return new MMapDirectory(languageDir);
}
/**
* Deletes a 3.1.x single index left directly under a site's index directory — only files Lucene names
* ({@code segments*}, {@code write.lock}, codec files such as {@code _0.cfs}), so an {@code indexRoot} pointed by
* mistake at a folder holding other files loses none of them — once per site per process.
*/
private void deleteOldLayout(Path siteDir) {
if (!oldLayoutChecked.add(siteDir)) {
return;
}
try (java.util.stream.Stream<Path> files = Files.list(siteDir)) {
files.filter(Files::isRegularFile).filter(f -> isLuceneFile(f.getFileName().toString())).forEach(file -> {
try {
Files.deleteIfExists(file);
} catch (IOException ignored) {
// a file that cannot be deleted is harmless: no index reads it any more
}
});
} catch (IOException ignored) {
// same: leftovers are never read
}
}
// --------------------------------------------------------------------------------------------- query build
/**
* Composes the tiered constant-score query from the analyzed terms and the site's ranking config. See the
* class doc for the tier semantics; the tiers are additive {@code SHOULD} clauses so a document's score is
* the sum of the tiers it matches.
*/
Query buildQuery(List<String> terms, RankingConfig cfg) {
BooleanQuery.Builder root = new BooleanQuery.Builder();
// Tier 1: any-terms (BM25-scored base) — each term across the three fields, with per-field boosts, plus
// optional fuzzy variants. This layer separates documents WITHIN the higher constant-score tiers.
BooleanQuery.Builder anyTerms = new BooleanQuery.Builder();
for (String term : terms) {
anyTerms.add(new BoostQuery(new TermQuery(new Term(F_TITLE, term)), cfg.titleBoost()),
BooleanClause.Occur.SHOULD);
anyTerms.add(new BoostQuery(new TermQuery(new Term(F_DESCRIPTION, term)), cfg.descriptionBoost()),
BooleanClause.Occur.SHOULD);
anyTerms.add(new TermQuery(new Term(F_BODY, term)), BooleanClause.Occur.SHOULD);
if (cfg.fuzzy()) {
int edits = maxEdits(term);
if (edits > 0) {
anyTerms.add(new BoostQuery(fuzzy(F_BODY, term, edits), cfg.fuzzyBoost()),
BooleanClause.Occur.SHOULD);
anyTerms.add(new BoostQuery(fuzzy(F_TITLE, term, edits), cfg.fuzzyBoost()),
BooleanClause.Occur.SHOULD);
}
}
}
root.add(anyTerms.build(), BooleanClause.Occur.SHOULD);
// Tiers 2–4: phrase tiers (only meaningful for a multi-term query; a single term IS its own phrase, so
// the phrase tiers would just double-count — skip them for one term).
if (terms.size() > 1) {
root.add(constant(phrase(F_TITLE, terms, 0), cfg.tierPhraseTitle()), BooleanClause.Occur.SHOULD);
root.add(constant(phrase(F_BODY, terms, 0), cfg.tierPhraseBody()), BooleanClause.Occur.SHOULD);
root.add(constant(phrase(F_BODY, terms, NEAR_SLOP), cfg.tierNearPhrase()), BooleanClause.Occur.SHOULD);
}
// Tier 5: all-terms-anywhere — every term must appear in some field; a constant lift for complete matches.
root.add(constant(allTermsAnywhere(terms), cfg.tierAllTerms()), BooleanClause.Occur.SHOULD);
return root.build();
}
/** Wraps {@code q} so it contributes a flat, position-independent {@code score} (the tier's constant). */
private static Query constant(Query q, float score) {
return new BoostQuery(new ConstantScoreQuery(q), score);
}
/** A {@link PhraseQuery} over {@code field} for the ordered {@code terms}, allowing {@code slop} reordering. */
private static Query phrase(String field, List<String> terms, int slop) {
PhraseQuery.Builder b = new PhraseQuery.Builder().setSlop(slop);
for (String term : terms) {
b.add(new Term(field, term));
}
return b.build();
}
/** A {@code MUST}-across-fields query: every term must match in title, description or body (in any position). */
private static Query allTermsAnywhere(List<String> terms) {
BooleanQuery.Builder all = new BooleanQuery.Builder();
for (String term : terms) {
BooleanQuery.Builder anyField = new BooleanQuery.Builder();
anyField.add(new TermQuery(new Term(F_TITLE, term)), BooleanClause.Occur.SHOULD);
anyField.add(new TermQuery(new Term(F_DESCRIPTION, term)), BooleanClause.Occur.SHOULD);
anyField.add(new TermQuery(new Term(F_BODY, term)), BooleanClause.Occur.SHOULD);
all.add(anyField.build(), BooleanClause.Occur.MUST);
}
return all.build();
}
/** A typo-tolerant {@link FuzzyQuery}: {@code edits} max, 1-char prefix fixed, 50 expansions, transpositions. */
private static FuzzyQuery fuzzy(String field, String term, int edits) {
return new FuzzyQuery(new Term(field, term), edits, 1, 50, true);
}
/** The Levenshtein edit budget for a term: none for very short terms, 1 for short, 2 for longer — so a fuzzy
* match never turns a 3-letter word into an unrelated one. */
static int maxEdits(String term) {
int len = term.length();
if (len <= 2) {
return 0;
}
return (len <= 5) ? 1 : 2;
}
// --------------------------------------------------------------------------------------------- highlighting
/**
* Query-focused highlighting over the stored body field: {@link UnifiedHighlighter} finds the best passage
* for each top doc and wraps the matched terms in the private markers (rewritten to {@code <mark>} later).
* Returns one snippet per top doc (aligned by index), each possibly {@code null} when the doc has no
* highlightable body. Any highlighter failure degrades to an all-{@code null} array — the caller then falls
* back to a plain leading snippet, so highlighting never breaks a search.
*/
private static String[] highlight(IndexSearcher searcher, Analyzer analyzer, Query query, TopDocs top) {
if (top.scoreDocs.length == 0) {
return new String[0];
}
try {
UnifiedHighlighter highlighter = UnifiedHighlighter.builder(searcher, analyzer)
.withFormatter(new DefaultPassageFormatter(MARK_OPEN, MARK_CLOSE, " … ", false))
.build();
return highlighter.highlight(F_BODY, query, top, 1);
} catch (IOException | RuntimeException e) {
log.debug("lucene highlighting failed, falling back to plain snippets: {}", e.toString());
return new String[top.scoreDocs.length];
}
}
/**
* The snippet for a hit: prefer the highlighter's query-focused, {@code <mark>}-wrapped passage; if there is
* none, fall back to the page description, else a leading slice of the body — always plain (no markers). The
* highlighted passage is produced by first HTML-escaping the raw passage, THEN turning the private markers
* into real {@code <mark>} tags, so page content can never inject markup while the highlight tags survive.
*/
private static String snippet(String highlighted, Document doc) {
if (highlighted != null && (highlighted.indexOf(MARK_OPEN_CH) >= 0)) {
return markup(highlighted);
}
String description = doc.get(S_DESCRIPTION);
String base = (description != null && !description.isBlank()) ? description : doc.get(S_BODY);
if (base == null || base.isBlank()) {
return "";
}
base = base.strip();
return base.length() <= SNIPPET_MAX ? base : base.substring(0, SNIPPET_MAX).stripTrailing() + "…";
}
/** Escapes the passage's HTML metacharacters, then rewrites the private markers to {@code <mark>} tags. */
private static String markup(String passage) {
String escaped = passage.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
.replace("\"", "&quot;").replace("'", "&#39;");
return escaped.replace(MARK_OPEN, "<mark>").replace(MARK_CLOSE, "</mark>").strip();
}
// -------------------------------------------------------------------------------------------------- shared
/** Analyzes free text into its terms with {@code analyzer} (same transform used at index time), capped. */
private static List<String> analyze(Analyzer analyzer, String text) {
List<String> out = new ArrayList<>();
try (TokenStream ts = analyzer.tokenStream(F_BODY, text)) {
CharTermAttribute term = ts.addAttribute(CharTermAttribute.class);
ts.reset();
while (ts.incrementToken() && out.size() < MAX_QUERY_TERMS) {
out.add(term.toString());
}
ts.end();
} catch (IOException e) {
return List.of();
}
return out;
}
/** This plugin's ranking knobs for the site, from its per-site settings (declared defaults applied). */
private RankingConfig ranking(String siteId) {
return RankingConfig.from(settings.site(siteId).values());
}
/** 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;
}
private static String nonNull(String value) {
return value == null ? "" : value;
}
private static void closeQuietly(Directory dir) {
try {
dir.close();
} catch (IOException | UncheckedIOException e) {
log.debug("failed to close a lucene directory: {}", e.toString());
}
}
}
@@ -0,0 +1,37 @@
package mx.quest.searchlucene;
import java.util.Objects;
import mx.quest.runway.spi.model.CatalogChange;
import mx.quest.runway.spi.service.SiteEventListener;
/**
* The plugin's one {@link SiteEventListener}, a {@link Phase#CONSUMER CONSUMER}: it reads the content listing (through
* the search plugin's {@code SearchCorpus}) and contributes none. The kernel delivers it after every kernel cache the
* change affects has been evicted and every content source has dropped its own state, so the rebuild it triggers reads
* the new state.
*
* <p>{@link #onCatalogChanged} drops the site's index for <b>every</b> cause — a page write, a content source's change,
* a site lifecycle event, and <b>any</b> plugin's settings save: a source reshapes its items from its settings (its
* URL prefix, say), and the search plugin's {@code exclude} list reshapes the corpus. No {@code pluginId} scoping is
* needed. This plugin's own settings (the ranking knobs) are read per query, so they need nothing here. The callback
* only evicts; the rebuild happens lazily on the next query. It runs on every node, for local and replayed changes
* alike: it only drops local state.
*/
final class LuceneSiteEvents implements SiteEventListener {
private final LuceneSearchEngine engine;
LuceneSiteEvents(LuceneSearchEngine engine) {
this.engine = Objects.requireNonNull(engine, "engine");
}
@Override
public Phase phase() {
return Phase.CONSUMER;
}
@Override
public void onCatalogChanged(CatalogChange change) {
engine.invalidate(change.siteId());
}
}
@@ -0,0 +1,72 @@
package mx.quest.searchlucene;
import java.util.Locale;
/**
* The plugin's <b>app-level</b> settings — where the index bytes live — bound from
* {@code external/plugin-settings/search-lucene.yml} (keys under {@code runway.plugin.search-lucene.*}), the
* plugin.yml {@code settings:} schema. Storage is a <b>platform</b> concern, not a tenant one: a filesystem path
* a tenant could edit would be an isolation/abuse risk, so it is app-level and applied on <b>restart</b> (a
* plugin reads its app-level settings through its own {@code @ConfigurationProperties}, never host machinery). The
* binding is declared on the {@code @Bean} method ({@code searchLuceneStorageProps} in {@link SearchLuceneConfig}), so
* the bean carries the plugin-id prefix every plugin bean name needs.
*
* <p>Field defaults mirror the schema defaults, so the plugin behaves sensibly (heap storage) when the file is
* absent — degrade-don't-crash.
*
* @see Storage the two storage modes and their trade-offs
*/
public class LuceneStorageProps {
/**
* Where a per-site Lucene index is held.
*
* <ul>
* <li>{@link #HEAP} — an in-memory {@code ByteBuffersDirectory}: no disk footprint, but the index is
* rebuilt from the page store after every restart. The default; ideal for small/medium sites.</li>
* <li>{@link #DISK} — a memory-mapped {@code MMapDirectory} under {@link #getIndexRoot()}{@code /<siteId>}:
* survives restarts and lets the OS page large indexes in/out of memory. Choose for large corpora.</li>
* </ul>
*/
public enum Storage { HEAP, DISK }
private Storage storage = Storage.HEAP;
private String indexRoot = "./external/plugins/search-lucene/index";
/** The configured storage mode; never {@code null} (defaults to {@link Storage#HEAP}). */
public Storage getStorage() {
return storage;
}
/**
* Binds the {@code storage} setting. Tolerant of case and blanks: an unrecognized or blank value falls back
* to {@link Storage#HEAP} rather than failing the context (degrade-don't-crash for a hand-edited file).
*/
public void setStorage(String storage) {
if (storage == null || storage.isBlank()) {
this.storage = Storage.HEAP;
return;
}
try {
this.storage = Storage.valueOf(storage.trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException ex) {
this.storage = Storage.HEAP;
}
}
/** The root folder for disk indexes (per-site subfolders are created under it); never blank. */
public String getIndexRoot() {
return indexRoot;
}
/** Binds the {@code indexRoot} setting; a blank value restores the default so the path is never empty. */
public void setIndexRoot(String indexRoot) {
this.indexRoot = (indexRoot == null || indexRoot.isBlank())
? "./external/plugins/search-lucene/index" : indexRoot.trim();
}
/** Whether disk (MMap) storage is selected. */
public boolean isDisk() {
return storage == Storage.DISK;
}
}
Loaded 100 of 1372 files, more files were not shown because too many files have changed in this diff. Show more