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

+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>