From ce217fc952302023db1c8e36f022bb1e728dc0b1 Mon Sep 17 00:00:00 2001 From: Runway Date: Wed, 21 Oct 2026 13:49:47 -0600 Subject: [PATCH] Runway 1.0.1 --- CHANGELOG.md | 69 ++ README.md | 1 + docs/ADMINISTRATION.md | 6 +- docs/KNOWN-LIMITATIONS.md | 4 - docs/OPERATIONS.md | 1 + docs/SITE-MANAGER-GUIDE.md | 4 +- plugins/README.md | 10 + plugins/blog/CHANGELOG.md | 10 + plugins/blog/LICENSE | 661 ++++++++++++++++ plugins/blog/LICENSE-EXCEPTION | 44 ++ plugins/blog/README.md | 117 +++ plugins/blog/docs/BLOG-PLUGIN.md | 202 +++++ plugins/blog/i18n/messages.properties | 71 ++ plugins/blog/i18n/messages_es.properties | 66 ++ plugins/blog/plugin.yml | 43 ++ plugins/blog/pom.xml | 184 +++++ plugins/blog/scripts/verify-against-host.sh | 331 ++++++++ .../mx/quest/blog/BlogAdminController.java | 332 ++++++++ .../main/java/mx/quest/blog/BlogConfig.java | 50 ++ .../java/mx/quest/blog/BlogContentSource.java | 309 ++++++++ .../main/java/mx/quest/blog/BlogEntry.java | 97 +++ .../main/java/mx/quest/blog/BlogSettings.java | 75 ++ .../main/java/mx/quest/blog/BlogStore.java | 261 +++++++ .../quest/blog/BlogAdminControllerTest.java | 369 +++++++++ .../blog/BlogAdminTemplatesRenderTest.java | 160 ++++ .../java/mx/quest/blog/BlogConfigTest.java | 195 +++++ .../mx/quest/blog/BlogContentSourceTest.java | 372 +++++++++ .../blog/BlogEntryTemplateContractTest.java | 200 +++++ .../java/mx/quest/blog/BlogStoreTest.java | 266 +++++++ .../java/mx/quest/blog/TemplateHarness.java | 86 +++ .../blog-1.3.1/entries/draft-post/body-en.md | 1 + .../blog-1.3.1/entries/draft-post/entry.yml | 8 + .../blog-1.3.1/entries/hello-world/body-en.md | 3 + .../blog-1.3.1/entries/hello-world/body-es.md | 3 + .../blog-1.3.1/entries/hello-world/entry.yml | 15 + .../blog-1.3.1/entries/launch/body-en.md | 1 + .../blog-1.3.1/entries/launch/entry.yml | 12 + .../blog-1.3.1/entries/no-author/body-en.md | 1 + .../blog-1.3.1/entries/no-author/entry.yml | 10 + plugins/blog/templates/admin-edit.html | 96 +++ plugins/blog/templates/admin-edit.th.xml | 57 ++ plugins/blog/templates/admin-list.html | 63 ++ plugins/blog/templates/admin-list.th.xml | 43 ++ plugins/blog/templates/entry-classic.html | 31 + plugins/blog/templates/entry-classic.th.xml | 31 + plugins/blog/templates/entry-minimal.html | 22 + plugins/blog/templates/entry-minimal.th.xml | 11 + plugins/carousel-manager/CHANGELOG.md | 9 + plugins/carousel-manager/LICENSE | 661 ++++++++++++++++ plugins/carousel-manager/LICENSE-EXCEPTION | 44 ++ plugins/carousel-manager/README.md | 39 + .../carousel-manager/docs/CAROUSEL-PLUGIN.md | 83 ++ .../carousel-manager/i18n/messages.properties | 19 + .../i18n/messages_es.properties | 19 + plugins/carousel-manager/plugin.yml | 35 + plugins/carousel-manager/pom.xml | 146 ++++ .../scripts/verify-against-host.sh | 134 ++++ .../mx/quest/carousel/CarouselAdminModel.java | 21 + .../mx/quest/carousel/CarouselConfig.java | 34 + .../mx/quest/carousel/CarouselWidget.java | 104 +++ .../src/main/java/mx/quest/carousel/Html.java | 20 + .../main/java/mx/quest/carousel/Slide.java | 28 + .../carousel/CarouselAdminModelTest.java | 22 + .../mx/quest/carousel/CarouselConfigTest.java | 125 +++ .../mx/quest/carousel/CarouselWidgetTest.java | 206 +++++ .../static/carousel-help.html | 42 ++ plugins/carousel-manager/static/carousel.css | 71 ++ plugins/carousel-manager/static/carousel.js | 49 ++ plugins/carousel-manager/templates/admin.html | 19 + .../carousel-manager/templates/admin.th.xml | 9 + .../carousel-manager/templates/dashboard.html | 15 + .../templates/dashboard.th.xml | 7 + plugins/contact/CHANGELOG.md | 10 + plugins/contact/LICENSE | 661 ++++++++++++++++ plugins/contact/LICENSE-EXCEPTION | 44 ++ plugins/contact/README.md | 63 ++ plugins/contact/docs/CONTACT-PLUGIN.md | 256 +++++++ plugins/contact/i18n/messages.properties | 69 ++ plugins/contact/i18n/messages_es.properties | 66 ++ plugins/contact/plugin.yml | 70 ++ plugins/contact/pom.xml | 144 ++++ .../contact/scripts/verify-against-host.sh | 383 ++++++++++ .../mx/quest/contact/ContactAdminModel.java | 69 ++ .../java/mx/quest/contact/ContactConfig.java | 66 ++ .../mx/quest/contact/ContactEndpoint.java | 310 ++++++++ .../java/mx/quest/contact/ContactForm.java | 63 ++ .../java/mx/quest/contact/ContactMailer.java | 195 +++++ .../java/mx/quest/contact/ContactStore.java | 124 +++ .../mx/quest/contact/ContactSubmission.java | 31 + .../java/mx/quest/contact/ContactWidget.java | 79 ++ .../src/main/java/mx/quest/contact/Html.java | 20 + .../quest/contact/JakartaMailTransport.java | 24 + .../java/mx/quest/contact/MailSendResult.java | 47 ++ .../java/mx/quest/contact/MailTransport.java | 25 + .../java/mx/quest/contact/SmtpSettings.java | 80 ++ .../contact/ContactAdminTemplateTest.java | 98 +++ .../mx/quest/contact/ContactConfigTest.java | 226 ++++++ .../mx/quest/contact/ContactEndpointTest.java | 418 ++++++++++ .../mx/quest/contact/ContactMailerTest.java | 201 +++++ .../mx/quest/contact/ContactStoreTest.java | 115 +++ .../mx/quest/contact/ContactWidgetTest.java | 150 ++++ plugins/contact/static/contact-help.html | 62 ++ plugins/contact/static/contact.css | 80 ++ plugins/contact/templates/admin.html | 75 ++ plugins/contact/templates/admin.th.xml | 57 ++ plugins/contact/templates/dashboard.html | 15 + plugins/contact/templates/dashboard.th.xml | 7 + plugins/demo/scripts/verify-against-host.sh | 2 +- plugins/discoverability/CHANGELOG.md | 10 + plugins/discoverability/LICENSE | 661 ++++++++++++++++ plugins/discoverability/LICENSE-EXCEPTION | 44 ++ plugins/discoverability/README.md | 170 +++++ .../docs/DISCOVERABILITY-PLUGIN.md | 375 +++++++++ .../docs/PLUGIN-AUTHORING-GUIDE.md | 9 + .../discoverability/i18n/messages.properties | 142 ++++ .../i18n/messages_es.properties | 141 ++++ plugins/discoverability/plugin.yml | 176 +++++ plugins/discoverability/pom.xml | 198 +++++ .../scripts/compare-with-previous.sh | 206 +++++ .../discoverability/scripts/install-into.sh | 21 + .../scripts/verify-against-host.sh | 317 ++++++++ .../java/mx/quest/discover/ArticleSchema.java | 110 +++ .../mx/quest/discover/CollectionSchema.java | 75 ++ .../mx/quest/discover/CrawlConditional.java | 210 ++++++ .../mx/quest/discover/DiscoverAdminModel.java | 151 ++++ .../quest/discover/DiscoverabilityConfig.java | 145 ++++ .../discover/DiscoverabilityProperties.java | 172 +++++ .../mx/quest/discover/FaqAdvisoryCheck.java | 103 +++ .../java/mx/quest/discover/FaqPageSchema.java | 72 ++ .../quest/discover/IndexNowKeyEndpoint.java | 70 ++ .../mx/quest/discover/IndexNowSubmitter.java | 395 ++++++++++ .../src/main/java/mx/quest/discover/Ld.java | 108 +++ .../mx/quest/discover/LlmsTxtEndpoint.java | 124 +++ .../quest/discover/LocalBusinessSchema.java | 75 ++ .../mx/quest/discover/PageSchemaConfig.java | 164 ++++ .../java/mx/quest/discover/PageTypeCheck.java | 127 ++++ .../java/mx/quest/discover/PageTypes.java | 182 +++++ .../main/java/mx/quest/discover/PageUrls.java | 33 + .../java/mx/quest/discover/PersonSchema.java | 56 ++ .../java/mx/quest/discover/ProductSchema.java | 53 ++ .../mx/quest/discover/RobotsTxtEndpoint.java | 393 ++++++++++ .../java/mx/quest/discover/SchemaContext.java | 27 + .../java/mx/quest/discover/SchemaType.java | 75 ++ .../main/java/mx/quest/discover/Schemas.java | 84 +++ .../java/mx/quest/discover/ServiceSchema.java | 79 ++ .../mx/quest/discover/SimplePageType.java | 43 ++ .../java/mx/quest/discover/SiteConfig.java | 50 ++ .../mx/quest/discover/SitemapEndpoint.java | 331 ++++++++ .../mx/quest/discover/StructuredDataHead.java | 405 ++++++++++ .../quest/discover/CrawlConditionalTest.java | 208 +++++ .../discover/DescriptorDefaultsTest.java | 111 +++ .../discover/DiscoverabilityConfigTest.java | 191 +++++ .../test/java/mx/quest/discover/Entries.java | 55 ++ .../quest/discover/FaqAdvisoryCheckTest.java | 97 +++ .../quest/discover/HostCatalogParityTest.java | 218 ++++++ .../mx/quest/discover/HostDescriptorTest.java | 70 ++ .../quest/discover/IndexNowSubmitterTest.java | 470 ++++++++++++ .../test/java/mx/quest/discover/LdTest.java | 65 ++ .../quest/discover/LlmsTxtEndpointTest.java | 250 ++++++ .../mx/quest/discover/PageTypeCheckTest.java | 111 +++ .../java/mx/quest/discover/PageTypesTest.java | 176 +++++ .../quest/discover/RobotsTxtEndpointTest.java | 341 +++++++++ .../mx/quest/discover/SchemaProblemsTest.java | 72 ++ .../discover/SettingsDescriptorTest.java | 172 +++++ .../quest/discover/SitemapEndpointTest.java | 416 ++++++++++ .../discover/StructuredDataHeadTest.java | 712 ++++++++++++++++++ .../java/mx/quest/discover/TestSettings.java | 58 ++ .../static/discoverability-help.html | 351 +++++++++ plugins/discoverability/templates/admin.html | 36 + .../discoverability/templates/admin.th.xml | 23 + .../discoverability/templates/dashboard.html | 18 + .../templates/dashboard.th.xml | 10 + .../scripts/verify-against-host.sh | 2 +- plugins/search/CHANGELOG.md | 14 + plugins/search/README.md | 2 +- plugins/search/i18n/messages_fr.properties | 9 + plugins/search/plugin.yml | 2 +- plugins/search/pom.xml | 4 +- plugins/search/scripts/verify-against-host.sh | 28 +- .../java/mx/quest/search/SearchConfig.java | 2 +- .../mx/quest/search/SearchConfigTest.java | 4 +- plugins/search/static/highlight-loader.js | 2 +- plugins/search/static/highlight.js | 2 +- pom.xml | 4 +- runway-app/pom.xml | 2 +- .../console/TenantBackupsController.java | 2 +- .../runway/content/PagesContentSource.java | 2 +- .../runway/editorial/EditorialService.java | 5 +- .../endpoint/PreAuthBodyLimitFilter.java | 2 +- .../endpoint/RouteFormCaptureFilter.java | 2 +- .../quest/runway/head/ScriptNonceStamper.java | 3 +- .../runway/head/ScriptPreloadStripper.java | 38 +- .../quest/runway/health/SiteHealthFilter.java | 2 +- .../runway/i18n/SiteAwareMessageSource.java | 14 +- .../java/mx/quest/runway/log/AuditEntry.java | 2 +- .../mx/quest/runway/log/AuditJournal.java | 4 +- .../quest/runway/page/LoadedSiteInputs.java | 2 +- .../quest/runway/page/PageReseedService.java | 4 +- .../mx/quest/runway/page/PageValidator.java | 2 +- .../quest/runway/page/PageWriteService.java | 4 +- .../runway/plugin/EssentialAllowlist.java | 16 +- .../runway/plugin/HostLinkageScanner.java | 4 +- .../runway/plugin/PluginAdminService.java | 2 +- .../quest/runway/plugin/PluginCompliance.java | 3 +- .../quest/runway/plugin/PluginDescriptor.java | 4 +- .../quest/runway/plugin/PluginResolution.java | 6 +- .../plugin/PluginStaticResourceConfig.java | 6 +- .../runway/plugin/PluginSurfaceCheck.java | 2 +- .../plugin/SitePluginConfigService.java | 2 +- .../runway/reload/SiteReloadService.java | 6 +- .../runway/security/AccountStateFilter.java | 2 +- .../security/LoginProtectionFilter.java | 2 +- .../runway/security/SecurityHeaders.java | 2 +- .../java/mx/quest/runway/web/CspFilter.java | 4 +- .../runway/web/RunwayHttpCacheProperties.java | 5 +- .../quest/runway/web/TenantConsolePaths.java | 6 +- .../mx/quest/runway/web/UnmeteredPaths.java | 11 +- .../backup/BackupFormatVersionTest.java | 2 +- .../console/KernelSettingsAdoptTest.java | 2 +- .../console/KernelSettingsScreenTest.java | 2 +- .../runway/console/MessageApostropheTest.java | 2 +- .../console/OperatorSpanishRegisterTest.java | 4 +- .../endpoint/PreAuthBodyLimitE2ETest.java | 7 +- .../runway/endpoint/RouteFormCapE2ETest.java | 6 +- .../runway/head/HeadInjectionFilterTest.java | 2 +- .../head/ScriptPreloadStripperTest.java | 2 +- .../runway/health/SiteHealthEndToEndTest.java | 4 +- .../runway/i18n/LanguageTagBundlesTest.java | 2 +- .../runway/page/LoadedSiteInputsTest.java | 4 +- .../runway/page/PageValidatorServiceTest.java | 2 +- .../plugin/EssentialRepairAdviceTest.java | 6 +- .../plugin/PluginAssetCacheControlTest.java | 2 +- .../PluginSettingsEtagIntegrationTest.java | 7 +- .../plugin/PluginStaticResourceTest.java | 4 +- .../runway/reload/SiteReloadEndToEndTest.java | 2 +- .../SecurityFilterMetricNamesTest.java | 2 +- .../security/UsernameUniquenessTest.java | 2 +- .../quest/runway/storage/FileStampTest.java | 2 +- .../ConsoleCacheControlIntegrationTest.java | 2 +- .../mx/quest/runway/web/CspFilterTest.java | 2 +- .../runway/web/CspHeaderBindingTest.java | 5 +- .../mx/quest/runway/web/CspNonceE2ETest.java | 2 +- .../runway/head/preload-corpus-chrome155.txt | 2 +- runway-dist/pom.xml | 2 +- runway-plugin-protection/plugin.yml | 14 +- runway-plugin-protection/pom.xml | 2 +- .../protection/DescriptorSpiFloorTest.java | 10 +- .../ProtectionDescriptorK4Test.java | 2 +- .../protection/RateLimitEdgeGuardTest.java | 2 +- runway-spi-testkit/pom.xml | 2 +- runway-spi/pom.xml | 2 +- .../java/mx/quest/runway/spi/RunwaySpi.java | 9 +- scripts/install.sh | 12 +- scripts/make-selfextract.sh | 6 +- scripts/plugin-seed.sh | 16 +- scripts/release-notes.sh | 10 +- scripts/test-install-config.sh | 15 +- scripts/test-plugin-seed.sh | 12 +- scripts/test-release-notes.sh | 4 +- 259 files changed, 22226 insertions(+), 206 deletions(-) create mode 100644 plugins/blog/CHANGELOG.md create mode 100644 plugins/blog/LICENSE create mode 100644 plugins/blog/LICENSE-EXCEPTION create mode 100644 plugins/blog/README.md create mode 100644 plugins/blog/docs/BLOG-PLUGIN.md create mode 100644 plugins/blog/i18n/messages.properties create mode 100644 plugins/blog/i18n/messages_es.properties create mode 100644 plugins/blog/plugin.yml create mode 100644 plugins/blog/pom.xml create mode 100755 plugins/blog/scripts/verify-against-host.sh create mode 100644 plugins/blog/src/main/java/mx/quest/blog/BlogAdminController.java create mode 100644 plugins/blog/src/main/java/mx/quest/blog/BlogConfig.java create mode 100644 plugins/blog/src/main/java/mx/quest/blog/BlogContentSource.java create mode 100644 plugins/blog/src/main/java/mx/quest/blog/BlogEntry.java create mode 100644 plugins/blog/src/main/java/mx/quest/blog/BlogSettings.java create mode 100644 plugins/blog/src/main/java/mx/quest/blog/BlogStore.java create mode 100644 plugins/blog/src/test/java/mx/quest/blog/BlogAdminControllerTest.java create mode 100644 plugins/blog/src/test/java/mx/quest/blog/BlogAdminTemplatesRenderTest.java create mode 100644 plugins/blog/src/test/java/mx/quest/blog/BlogConfigTest.java create mode 100644 plugins/blog/src/test/java/mx/quest/blog/BlogContentSourceTest.java create mode 100644 plugins/blog/src/test/java/mx/quest/blog/BlogEntryTemplateContractTest.java create mode 100644 plugins/blog/src/test/java/mx/quest/blog/BlogStoreTest.java create mode 100644 plugins/blog/src/test/java/mx/quest/blog/TemplateHarness.java create mode 100644 plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/draft-post/body-en.md create mode 100644 plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/draft-post/entry.yml create mode 100644 plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/hello-world/body-en.md create mode 100644 plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/hello-world/body-es.md create mode 100644 plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/hello-world/entry.yml create mode 100644 plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/launch/body-en.md create mode 100644 plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/launch/entry.yml create mode 100644 plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/no-author/body-en.md create mode 100644 plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/no-author/entry.yml create mode 100644 plugins/blog/templates/admin-edit.html create mode 100644 plugins/blog/templates/admin-edit.th.xml create mode 100644 plugins/blog/templates/admin-list.html create mode 100644 plugins/blog/templates/admin-list.th.xml create mode 100644 plugins/blog/templates/entry-classic.html create mode 100644 plugins/blog/templates/entry-classic.th.xml create mode 100644 plugins/blog/templates/entry-minimal.html create mode 100644 plugins/blog/templates/entry-minimal.th.xml create mode 100644 plugins/carousel-manager/CHANGELOG.md create mode 100644 plugins/carousel-manager/LICENSE create mode 100644 plugins/carousel-manager/LICENSE-EXCEPTION create mode 100644 plugins/carousel-manager/README.md create mode 100644 plugins/carousel-manager/docs/CAROUSEL-PLUGIN.md create mode 100644 plugins/carousel-manager/i18n/messages.properties create mode 100644 plugins/carousel-manager/i18n/messages_es.properties create mode 100644 plugins/carousel-manager/plugin.yml create mode 100644 plugins/carousel-manager/pom.xml create mode 100755 plugins/carousel-manager/scripts/verify-against-host.sh create mode 100644 plugins/carousel-manager/src/main/java/mx/quest/carousel/CarouselAdminModel.java create mode 100644 plugins/carousel-manager/src/main/java/mx/quest/carousel/CarouselConfig.java create mode 100644 plugins/carousel-manager/src/main/java/mx/quest/carousel/CarouselWidget.java create mode 100644 plugins/carousel-manager/src/main/java/mx/quest/carousel/Html.java create mode 100644 plugins/carousel-manager/src/main/java/mx/quest/carousel/Slide.java create mode 100644 plugins/carousel-manager/src/test/java/mx/quest/carousel/CarouselAdminModelTest.java create mode 100644 plugins/carousel-manager/src/test/java/mx/quest/carousel/CarouselConfigTest.java create mode 100644 plugins/carousel-manager/src/test/java/mx/quest/carousel/CarouselWidgetTest.java create mode 100644 plugins/carousel-manager/static/carousel-help.html create mode 100644 plugins/carousel-manager/static/carousel.css create mode 100644 plugins/carousel-manager/static/carousel.js create mode 100644 plugins/carousel-manager/templates/admin.html create mode 100644 plugins/carousel-manager/templates/admin.th.xml create mode 100644 plugins/carousel-manager/templates/dashboard.html create mode 100644 plugins/carousel-manager/templates/dashboard.th.xml create mode 100644 plugins/contact/CHANGELOG.md create mode 100644 plugins/contact/LICENSE create mode 100644 plugins/contact/LICENSE-EXCEPTION create mode 100644 plugins/contact/README.md create mode 100644 plugins/contact/docs/CONTACT-PLUGIN.md create mode 100644 plugins/contact/i18n/messages.properties create mode 100644 plugins/contact/i18n/messages_es.properties create mode 100644 plugins/contact/plugin.yml create mode 100644 plugins/contact/pom.xml create mode 100755 plugins/contact/scripts/verify-against-host.sh create mode 100644 plugins/contact/src/main/java/mx/quest/contact/ContactAdminModel.java create mode 100644 plugins/contact/src/main/java/mx/quest/contact/ContactConfig.java create mode 100644 plugins/contact/src/main/java/mx/quest/contact/ContactEndpoint.java create mode 100644 plugins/contact/src/main/java/mx/quest/contact/ContactForm.java create mode 100644 plugins/contact/src/main/java/mx/quest/contact/ContactMailer.java create mode 100644 plugins/contact/src/main/java/mx/quest/contact/ContactStore.java create mode 100644 plugins/contact/src/main/java/mx/quest/contact/ContactSubmission.java create mode 100644 plugins/contact/src/main/java/mx/quest/contact/ContactWidget.java create mode 100644 plugins/contact/src/main/java/mx/quest/contact/Html.java create mode 100644 plugins/contact/src/main/java/mx/quest/contact/JakartaMailTransport.java create mode 100644 plugins/contact/src/main/java/mx/quest/contact/MailSendResult.java create mode 100644 plugins/contact/src/main/java/mx/quest/contact/MailTransport.java create mode 100644 plugins/contact/src/main/java/mx/quest/contact/SmtpSettings.java create mode 100644 plugins/contact/src/test/java/mx/quest/contact/ContactAdminTemplateTest.java create mode 100644 plugins/contact/src/test/java/mx/quest/contact/ContactConfigTest.java create mode 100644 plugins/contact/src/test/java/mx/quest/contact/ContactEndpointTest.java create mode 100644 plugins/contact/src/test/java/mx/quest/contact/ContactMailerTest.java create mode 100644 plugins/contact/src/test/java/mx/quest/contact/ContactStoreTest.java create mode 100644 plugins/contact/src/test/java/mx/quest/contact/ContactWidgetTest.java create mode 100644 plugins/contact/static/contact-help.html create mode 100644 plugins/contact/static/contact.css create mode 100644 plugins/contact/templates/admin.html create mode 100644 plugins/contact/templates/admin.th.xml create mode 100644 plugins/contact/templates/dashboard.html create mode 100644 plugins/contact/templates/dashboard.th.xml create mode 100644 plugins/discoverability/CHANGELOG.md create mode 100644 plugins/discoverability/LICENSE create mode 100644 plugins/discoverability/LICENSE-EXCEPTION create mode 100644 plugins/discoverability/README.md create mode 100644 plugins/discoverability/docs/DISCOVERABILITY-PLUGIN.md create mode 100644 plugins/discoverability/docs/PLUGIN-AUTHORING-GUIDE.md create mode 100644 plugins/discoverability/i18n/messages.properties create mode 100644 plugins/discoverability/i18n/messages_es.properties create mode 100644 plugins/discoverability/plugin.yml create mode 100644 plugins/discoverability/pom.xml create mode 100644 plugins/discoverability/scripts/compare-with-previous.sh create mode 100755 plugins/discoverability/scripts/install-into.sh create mode 100755 plugins/discoverability/scripts/verify-against-host.sh create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/ArticleSchema.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/CollectionSchema.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/CrawlConditional.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/DiscoverAdminModel.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/DiscoverabilityConfig.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/DiscoverabilityProperties.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/FaqAdvisoryCheck.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/FaqPageSchema.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/IndexNowKeyEndpoint.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/IndexNowSubmitter.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/Ld.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/LlmsTxtEndpoint.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/LocalBusinessSchema.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/PageSchemaConfig.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/PageTypeCheck.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/PageTypes.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/PageUrls.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/PersonSchema.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/ProductSchema.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/RobotsTxtEndpoint.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/SchemaContext.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/SchemaType.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/Schemas.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/ServiceSchema.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/SimplePageType.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/SiteConfig.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/SitemapEndpoint.java create mode 100644 plugins/discoverability/src/main/java/mx/quest/discover/StructuredDataHead.java create mode 100644 plugins/discoverability/src/test/java/mx/quest/discover/CrawlConditionalTest.java create mode 100644 plugins/discoverability/src/test/java/mx/quest/discover/DescriptorDefaultsTest.java create mode 100644 plugins/discoverability/src/test/java/mx/quest/discover/DiscoverabilityConfigTest.java create mode 100644 plugins/discoverability/src/test/java/mx/quest/discover/Entries.java create mode 100644 plugins/discoverability/src/test/java/mx/quest/discover/FaqAdvisoryCheckTest.java create mode 100644 plugins/discoverability/src/test/java/mx/quest/discover/HostCatalogParityTest.java create mode 100644 plugins/discoverability/src/test/java/mx/quest/discover/HostDescriptorTest.java create mode 100644 plugins/discoverability/src/test/java/mx/quest/discover/IndexNowSubmitterTest.java create mode 100644 plugins/discoverability/src/test/java/mx/quest/discover/LdTest.java create mode 100644 plugins/discoverability/src/test/java/mx/quest/discover/LlmsTxtEndpointTest.java create mode 100644 plugins/discoverability/src/test/java/mx/quest/discover/PageTypeCheckTest.java create mode 100644 plugins/discoverability/src/test/java/mx/quest/discover/PageTypesTest.java create mode 100644 plugins/discoverability/src/test/java/mx/quest/discover/RobotsTxtEndpointTest.java create mode 100644 plugins/discoverability/src/test/java/mx/quest/discover/SchemaProblemsTest.java create mode 100644 plugins/discoverability/src/test/java/mx/quest/discover/SettingsDescriptorTest.java create mode 100644 plugins/discoverability/src/test/java/mx/quest/discover/SitemapEndpointTest.java create mode 100644 plugins/discoverability/src/test/java/mx/quest/discover/StructuredDataHeadTest.java create mode 100644 plugins/discoverability/src/test/java/mx/quest/discover/TestSettings.java create mode 100644 plugins/discoverability/static/discoverability-help.html create mode 100644 plugins/discoverability/templates/admin.html create mode 100644 plugins/discoverability/templates/admin.th.xml create mode 100644 plugins/discoverability/templates/dashboard.html create mode 100644 plugins/discoverability/templates/dashboard.th.xml create mode 100644 plugins/search/i18n/messages_fr.properties diff --git a/CHANGELOG.md b/CHANGELOG.md index 45b7833..65d0376 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,75 @@ All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/). +## [1.0.1] — 2026-10-21 + +_A patch release: every first-party plugin is now published with Runway — blog, carousel-manager, contact and +discoverability join demo, search, search-lucene and lucene-provider — the installed release carries its license +files, the install instructions work as written, and the 1.0.0 upgrade notes are corrected. The plugin contract is unchanged (SPI `1.0.0`); every plugin release that +`1.0.0` paired with loads unchanged. Built on the `1.0.1-SNAPSHOT` line after `1.0.0`._ + +### Upgrading — read this first + +**From `1.0.0`: a kernel upgrade, no flag, no setting; plugin upgrades optional.** Coming from an older release: read each +newer release's *Upgrading* first, oldest first. Paths are the installer defaults (`/opt/runway`, `/opt/runway-data`). + +**1. Back up.** Take each site's backup (**Backups**) and copy `/opt/runway-data/external/` somewhere **outside** +`external/plugins/`. Nothing in `platform.yml` changes in this release. + +**2. Upgrade the kernel:** + +```bash +chmod +x runway-1.0.1.bin +sudo ./runway-1.0.1.bin -y +``` + +The essential plugin moves with the kernel to `1.0.1` (its descriptor changes in comments and version only, and its +jar is rebuilt), so the installer refreshes it; expect these lines, once: + +``` +refreshing bundled plugin 'protection' from this release (it moves with the kernel; files you edited are backed up) +plugin 'protection': plugin.yml replaced (the previous one kept as plugin.yml.bak, for a rollback) +plugin 'protection': runway-plugin-protection.jar replaced (the previous one kept as runway-plugin-protection.jar.bak, for a rollback) +keeping the bundled plugins in the release: /opt/runway-1.0.1/seed/ (the repair copy — Administration §12) +``` + +**3. Check.** **About Runway** shows `1.0.1`; on **Plugins** every row is *Loaded*, none *Blocked*, and protection +shows `1.0.1`; the start log says `plugins: N registered, 0 blocked`. `/opt/runway-1.0.1/` now holds `LICENSE`, +`LICENSE-EXCEPTION` and `THIRD-PARTY-NOTICES`. + +**4. Plugins (optional).** This release carries blog 2.1.0, carousel-manager 2.1.0, contact 2.1.0 and +discoverability 2.3.0, each built for Runway 1.0.0 with its license files, and search 2.3.1 (French strings for +visitors); their earlier releases keep working on 1.0.1. To upgrade one, read its CHANGELOG section, replace its folder with the new zip and restart. + +**5. Rollback**, if needed: `sudo bash runway-1.0.0.bin -y` puts 1.0.0 back, its protection files included. + +### Fixed +- **The installed release carries its license files.** The installer now copies `LICENSE`, `LICENSE-EXCEPTION` + and `THIRD-PARTY-NOTICES` into the release directory (`/opt/runway-/`). In `1.0.0` they were in the + distribution zip and inside the jars (`META-INF/`), but not at the top of an installed release. +- **The install and upgrade instructions set the execute bit.** A downloaded `.bin` is not executable, so the + documented `sudo ./runway-.bin` failed; README, Administration §3 and §15 and + Operations now run `chmod +x` first (`sudo bash runway-.bin` works too). + +### Added +- **blog, carousel-manager, contact and discoverability are published**, under the GNU AGPL v3.0 with the additional + permission for plugins, and attached to this release beside demo, search, search-lucene and lucene-provider. + `KNOWN-LIMITATIONS.md` no longer lists the missing sitemap/robots/llms.txt/structured-data plugin, and the docs list + all eight plugins. +- **search 2.3.1 speaks French to visitors**: the search box, the results heading and count, "no results" and the + rate-limit notice. + +### Changed +- Code comments across the kernel, the SPI's version log (`RunwaySpi`) and the protection descriptor no longer refer + to releases before `1.0.0`. + +### Notes +- **An upgrade to 1.0.0 printed more protection-refresh lines than its notes listed:** besides the jar, the installer + replaced protection's `plugin.yml` (keeping `plugin.yml.bak`) and updated `templates/admin-app.th.xml` and + `templates/app-dos.th.xml`, which changed in comments only. Upgrading to 1.0.1 prints the four lines listed above. +- The documentation links the releases page directly (), and + Administration §11 says where each plugin's zip comes from. + ## [1.0.0] — 2026-10-21 The first public release of Runway: a multi-site web platform built as a small multi-tenant kernel, with every diff --git a/README.md b/README.md index 36e6f92..26b4988 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ bundle appended — no `makeself`, only stock `bash`/`tar`/`gzip`). Run it as ro **idempotent**, so re-running the same or a newer `.bin` upgrades in place: ```sh +chmod +x runway-.bin # a download has no execute bit sudo ./runway-.bin # interactive: prompts on a TTY sudo ./runway-.bin -y # unattended, all defaults sudo ./runway-.bin -y --no-firewall # ...and never touch the host firewall diff --git a/docs/ADMINISTRATION.md b/docs/ADMINISTRATION.md index 3151f0b..5a79938 100644 --- a/docs/ADMINISTRATION.md +++ b/docs/ADMINISTRATION.md @@ -182,6 +182,7 @@ curl -fL -O \ curl -fL -O \ https://g.quest.mx/quest/runway/releases/download/latest/SHA256SUMS sha256sum -c SHA256SUMS --ignore-missing # must print: runway-latest.bin: OK +chmod +x runway-latest.bin # a download has no execute bit sudo ./runway-latest.bin ``` @@ -202,6 +203,7 @@ your own high-volume clients*. **Install (interactive).** Copy the `.bin` to the target host and run it as root: ```bash +chmod +x runway-.bin # a download has no execute bit sudo ./runway-.bin ``` @@ -1604,7 +1606,8 @@ plugin installed). Delete it afterward to confirm it removes cleanly like any ot **Where the plugins come from.** Each Runway release on the releases page () also carries the public plugins built for it — -`runway-plugin--.zip` for `runway-demo`, `search`, `search-lucene` and `lucene-provider` — listed in +`runway-plugin--.zip` for `blog`, `carousel-manager`, `contact`, `discoverability`, `runway-demo`, `search`, +`search-lucene` and `lucene-provider` — listed in the same `SHA256SUMS`. Install one by uploading its zip on **Plugins** (below), then restart. > ### ⚠️ Never park an old plugin version inside `external/plugins/` @@ -2488,6 +2491,7 @@ restart. installs and upgrades, and it is idempotent: ```bash +chmod +x runway-.bin sudo ./runway-.bin -y # or interactively ``` diff --git a/docs/KNOWN-LIMITATIONS.md b/docs/KNOWN-LIMITATIONS.md index f3c29c2..a5f4b2e 100644 --- a/docs/KNOWN-LIMITATIONS.md +++ b/docs/KNOWN-LIMITATIONS.md @@ -136,10 +136,6 @@ closes it. Items marked **after 1.0** are decided: they are not part of the `1.0 and parses it itself, and takes its CSRF token in the `X-CSRF-TOKEN` header (no first-party plugin accepts uploads). - **Billboard and News plugins are not built** (**after 1.0**, as plugin releases). -- **No published plugin serves `/sitemap.xml`, `/robots.txt`, `/llms.txt` or schema.org structured data.** The - kernel provides the seams (`EndpointContributor`, `HeadContributor`) and the Site-manager guide (§10) describes - what such a plugin provides, but none of the published plugins (demo, search, search-lucene, lucene-provider) - does; without one a site serves no `/robots.txt` at all (crawlers read that as everything allowed) and no sitemap. - **The search plugin's rate limit is a courtesy limiter, not a defence.** It keys on the client address after the kernel's trusted-proxy gate; the kernel's own edge guard is the abuse floor. - **A search index rebuilds by rendering every page once per language.** A page is indexed as rendered in diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md index fc5ac67..9d08ea4 100644 --- a/docs/OPERATIONS.md +++ b/docs/OPERATIONS.md @@ -902,6 +902,7 @@ means the pin never got written (**§4.4**); a stuck plugin apply means a plugin installs and upgrades, and it is idempotent (Administration §15 has the full walk-through): ```bash +chmod +x runway-.bin # a download has no execute bit sudo ./runway-.bin -y # or interactively — not with --port / --tls-keystore ``` diff --git a/docs/SITE-MANAGER-GUIDE.md b/docs/SITE-MANAGER-GUIDE.md index c550fea..d0a0dbb 100644 --- a/docs/SITE-MANAGER-GUIDE.md +++ b/docs/SITE-MANAGER-GUIDE.md @@ -1168,8 +1168,8 @@ they never touch your templates. Analytics and richer GEO markup are added by pl ### Sitemaps, robots and AI crawlers The core stops at the page's own ``. The crawl surfaces themselves — `/sitemap.xml`, `/robots.txt` -and `/llms.txt` — and the schema.org structured data that says what a page *is* come from a plugin, -if your operator has installed one; it then appears in the **Settings** dropdown +and `/llms.txt` — and the schema.org structured data that says what a page *is* come from a plugin (the `discoverability` plugin +does all four), if your operator has installed one; it then appears in the **Settings** dropdown with its own per-site form (**§8**). Without one your site serves no `/robots.txt` at all, which crawlers read as *everything allowed*. diff --git a/plugins/README.md b/plugins/README.md index 0f733b2..fe096c1 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -15,6 +15,10 @@ plugins built for it, beside the kernel's own files and listed in the same `SHA2 plugins/ ├── docs/PLUGIN-AUTHORING-GUIDE.md # THE canonical guide: build any Runway plugin from scratch ├── demo/ # the reference "kitchen-sink" plugin — exercises EVERY seam +├── blog/ # a blog: entries as virtual pages via ContentSource, in the site's own chrome +├── carousel-manager/ # an image/slide carousel content widget, slides configured per site +├── contact/ # a contact form widget: emails each submission and stores it for the console +├── discoverability/ # SEO+ & GEO: sitemap.xml, robots.txt, llms.txt and schema.org JSON-LD ├── search/ # on-site search: box widget + /search + /search/api + a published SiteSearchEngine SPI ├── search-lucene/ # a Lucene engine for `search` (requires: search + lucene-provider; per-locale analyzers, heap or disk) └── lucene-provider/ # CODE-LESS library provider: bundles Apache Lucene under lib/ (no mainClass) @@ -41,6 +45,12 @@ with no code of its own to verify. - Implementing another plugin's SPI (`requires:`) + **consuming a library-provider** (Lucene) → [`search-lucene/`](search-lucene/). - A **code-less library-provider** plugin (bundle a shared library under `lib/`, no `mainClass`) → [`lucene-provider/`](lucene-provider/) (Apache Lucene) — consumed by a `requires:` plugin (`search-lucene`). + - Routable content of your own (virtual pages in the site's chrome, sitemap and search included) → + [`blog/`](blog/) (`ContentSource`). + - A public form that posts, mails and stores tenant data → [`contact/`](contact/). + - Server routes and `` markup for a whole site (`EndpointContributor`, `HeadContributor`) → + [`discoverability/`](discoverability/). + - A self-contained content widget with its own static assets → [`carousel-manager/`](carousel-manager/). ## Conventions diff --git a/plugins/blog/CHANGELOG.md b/plugins/blog/CHANGELOG.md new file mode 100644 index 0000000..f394834 --- /dev/null +++ b/plugins/blog/CHANGELOG.md @@ -0,0 +1,10 @@ +# Changelog + +All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/). + +## [2.1.0] — 2026-10-21 + +First public release of `blog`: blog entries as first-class virtual pages through the kernel's `ContentSource` +seam — each with its own URL (under a configurable prefix, or a custom path), rendered in the site's own chrome, in +every language the site serves, and listed in the sitemap and `llms.txt`. Requires SPI `1.0.0` (Runway `1.0.0` or later). Licensed under the GNU AGPL v3.0 with an additional permission for +plugins (`LICENSE`, `LICENSE-EXCEPTION`). diff --git a/plugins/blog/LICENSE b/plugins/blog/LICENSE new file mode 100644 index 0000000..dba13ed --- /dev/null +++ b/plugins/blog/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/plugins/blog/LICENSE-EXCEPTION b/plugins/blog/LICENSE-EXCEPTION new file mode 100644 index 0000000..b634521 --- /dev/null +++ b/plugins/blog/LICENSE-EXCEPTION @@ -0,0 +1,44 @@ +Runway — additional permission for plugins +(an additional permission under section 7 of the GNU Affero General Public License, version 3) + +Copyright (C) 2026 Quest ICT SAS de CV + +Runway is free software: you can redistribute it and/or modify it under the terms of the +GNU Affero General Public License as published by the Free Software Foundation, version 3 +(the file LICENSE), with the additional permission below. Runway is distributed in the hope +that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public +License for more details. + +1. Definitions + + "Runway" means the Runway kernel and every Runway plugin whose source carries this file. + + "Published SPI" means the public classes and interfaces of the runway-spi artifact + (the package mx.quest.runway.spi and its subpackages), together with the public classes + and interfaces of any package named "spi" that a part of Runway publishes for other + plugins to use (for example mx.quest.search.spi). + + "Plugin" means an independent module that Runway loads as a plugin, that interacts with + Runway only through the Published SPI, and that is not based on any part of Runway other + than the Published SPI. + +2. Permission + + As an additional permission, the copyright holder gives you permission to combine Runway + with Plugins, and to convey and run the resulting combination, without the terms of the + GNU Affero General Public License applying to those Plugins. You may license, convey and + run your Plugins under terms of your choice, provided that you continue to meet the terms + of the GNU Affero General Public License for Runway itself, including offering the + Corresponding Source of Runway, and of any modification you make to it, as that license + requires. + +3. Testing + + Compiling a Plugin's tests against the runway-spi-testkit artifact, and running them, does + not by itself make the Plugin subject to the GNU Affero General Public License. + +4. Modified versions + + If you modify Runway, you may extend this additional permission to your version, but you + are not obliged to do so. If you do not wish to, delete this file from your version. diff --git a/plugins/blog/README.md b/plugins/blog/README.md new file mode 100644 index 0000000..e4d0e66 --- /dev/null +++ b/plugins/blog/README.md @@ -0,0 +1,117 @@ +# blog — a blog for Runway sites + +Blog entries as **first-class virtual pages**, built on the host's `ContentSource` seam: each entry has its own URL under a configurable prefix (default `/blog`) — or a per-entry +**custom absolute path** — renders inside the **tenant's own master chrome** through this plugin's shipped +entry templates, follows the site's full language dispatch (per-language slugs, `?lang=` switcher, canonical +redirects), appears in **sitemap.xml / llms.txt** with `hreflang` + ``, and is linkable from any +tenant page as `${urls['blog:']}`. All of that is host-provided; this plugin only stores entries and +answers the source contract. + +**The plugin links only the Runway SPI** (service tier, SPI `1.0.0`) — no kernel-internal class. The full design +and reference is [`docs/BLOG-PLUGIN.md`](docs/BLOG-PLUGIN.md); the release notes are in +[`CHANGELOG.md`](CHANGELOG.md); `scripts/verify-against-host.sh` checks it end to end against a packaged kernel. + +- **Storage** — entries live in the *tenant's* folder: `sites//plugins/blog/entries//entry.yml` + (metadata) + `body-.md` (one Markdown body per language), through the kernel's `PluginSiteFiles` (confined + to the plugin's subtree). Tenant backups carry the whole blog + automatically; the metadata/body file split keeps enumeration body-free (the source contract). +- **Authoring** — the tenant console gains a **Blog** screen (`/__admin/blog`, gated by the grantable + `blog|manage` control point): list, create, edit (per-language title/description/slug/body), publish/ + unpublish, delete — each a CSRF-checked `POST`. Every mutation is announced with `ContentChanges`, so routing, + sitemap and search follow on the next request; the editor warns when a published **page owns an entry's + address** (the page wins — the platform's precedence rule), and refuses a custom path the kernel would not serve. +- **Settings** (per tenant, applied immediately): `enabled`, `prefix`, `template` + (`entry-classic` — title, date line, back link — or `entry-minimal` — title + body only). +- **Search** — entries declare the kernel's `content.indexable-text` capability and serve their + body through it (rendered Markdown→HTML, the same transform the page render uses, so the engines' HTML + stripper yields clean prose — raw Markdown syntax would leak into index terms and snippets). A search engine + that indexes the content catalog (the `search` and `search-lucene` plugins) finds entries by body text, + title and description — first-class search citizens, no blog-specific code in any engine. +- **Markdown** — rendered with [commonmark-java] (bundled in this plugin's `lib/`, private to this plugin). + Entry Markdown is operator-authored trusted content: raw HTML passes through, exactly as a page author may + write markup. + +## Bylines and publication dates + +Each entry carries its own **author** and **publication date**, and both travel across the SPI as that +entry's own values — so the discoverability plugin emits a truthful per-post `author` and `datePublished` in +`Article`/`BlogPosting` structured data, and the entry template renders a byline. + +Without them, authorship and dates could only come from the per-site `content.schema` block, which matches by +path prefix — one `/blog/*` entry covering *every* post. The only honest options would be to emit nothing, or to +assert a single author and date identically across all posts: false of nearly every page carrying it, and +exactly the kind of untrue markup structured-data policy prohibits. + +Notes: + +- Both fields are **optional**. An unattributed entry renders no byline and asserts no author — absence is a + normal state, never a placeholder. +- The byline element appears when the entry has an author **or** a date, and each part renders independently, + so an entry with one but not the other is handled correctly. +- `author` is a free-text display name, matching the kernel's page-level author. A real identity model is a + larger design; blocking bylines on it would leave content unattributable meanwhile. + +## Publication dates + +Each entry's `publishedOn` date is carried across the SPI as that entry's own `publishedAt`, so the +discoverability plugin can emit a **truthful per-post `datePublished`** in `Article`/`BlogPosting` +structured data. + +Notes: + +- `publishedOn` is free-form display text. A value that is not an ISO `yyyy-MM-dd` date yields **no** + `datePublished` rather than a guess — asserting a wrong date is worse than asserting none, because a + consumer is told to trust it. +- Dates are interpreted at **midnight UTC**, matching how the kernel's page editor parses its own date + field, so a blog entry and a page dated the same day produce the same instant. + +## Requirements + +**Needs Runway 1.0.0 or later** (SPI `1.0.0`). The descriptor declares `requiresSpi: ">=1.0.0"`, so an older +kernel blocks this plugin at startup with a reason and still boots its other plugins. Upgrade the kernel first, then +the plugin. + +## Build + +```bash +mvn package +``` + +`target/blog/` (the install-ready folder) and `target/runway-plugin-blog-.zip` (the UI-upload +archive), where `` is the `version:` in `plugin.yml`. + +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. + +## Install (either path, then restart the host) + +```bash +# 1. cp -r target/blog /plugins/ +# 2. app console → /__app/plugins → install → upload runway-plugin-blog-.zip +``` + +## Verify + +```bash +mvn verify # 67 unit tests, incl. the no-host-linkage bytecode scan +JAVA_HOME=… HOST_JAR=…/runway-app--exec.jar VERIFY_TMPDIR=… scripts/verify-against-host.sh # 56 end-to-end checks +``` + +## Try it + +1. Console → **Blog** → **New entry**: id `hello-world`, tick a language, type a title and a Markdown body, + tick **Published**, Save. +2. Visit `https:///blog/hello-world` — the entry wears the site's chrome. +3. `GET /sitemap.xml` — the entry is listed with `hreflang` alternates and ``. +4. Give a **page** the same path — the page serves, the blog editor and the Pages screen both warn. + +_Java package `mx.quest.blog` · plugin id `blog` · built against `runway-spi` 1.0.0 · declared SPI floor +`>=1.0.0`._ + +[commonmark-java]: https://github.com/commonmark/commonmark-java + +## License + +GNU Affero General Public License v3.0 with an additional permission for plugins (`LICENSE`, `LICENSE-EXCEPTION`), +copyright Quest ICT SAS de CV. The permission means that a plugin which uses only the published SPI may carry any +license. diff --git a/plugins/blog/docs/BLOG-PLUGIN.md b/plugins/blog/docs/BLOG-PLUGIN.md new file mode 100644 index 0000000..87417f7 --- /dev/null +++ b/plugins/blog/docs/BLOG-PLUGIN.md @@ -0,0 +1,202 @@ +# Runway Blog plugin — design & reference + +> The plugins' reference for **routable content that is not a kernel page**: a plugin `ContentSource` whose +> items the kernel routes, renders in the tenant's own master chrome, lists in sitemap.xml / llms.txt and hands to +> search — using **only the Runway SPI** (SPI 1.0.0). Grounded in the Runway kernel as built. + +## 1. What it does + +- **Entries as virtual pages.** Each entry is served by the kernel at `/` (default prefix `/blog`), + or at a per-entry **custom absolute path** (`/announcing-v2`) for the default language, with **per-language + slugs** (`/es/blog/hola-mundo`). The kernel does the routing (real pages always win first), the locale ladder + (`?lang=`, cookie, `Accept-Language`, canonical redirects), the `` (title, description, `hreflang` + alternates, canonical), the `ETag`/`304`, and wraps the body in the **site's own master** (`_master`). +- **Body templates** shipped by the plugin: `entry-classic` (title, a meta line with the date and the byline, the + body, a back link) and `entry-minimal` (title and body). The operator picks one per site. +- **Discoverability and search, through the kernel catalog.** Published entries are part of the site's content + catalog, so sitemap.xml (with `hreflang` and ``), llms.txt and the URL map (`${urls['blog:']}`, usable + in any page) list them, and a search engine that indexes the catalog finds an entry by the words of its body + (`content.indexable-text`: the body rendered to HTML, the same transform the page uses). The blog has no + blog-specific code in any of those plugins. +- **Bylines and dates.** Each entry carries its own `author` and `publishedOn`; both cross the SPI as that entry's + own values (`ContentRef.author`, `ContentRef.publishedAt`, midnight UTC; a non-ISO date yields no date), so + structured data can attribute and date every post truthfully. Both are optional and render independently. +- **Console** (`/__admin/blog`, tenant console, gated by `blog|manage`): list, create, edit (per-language title, + description, slug, Markdown body; date, author, custom path, published), publish/unpublish, delete. The editor + warns when a **published page owns an entry's URL** in some language (the page wins, so the entry is unreachable + there). Per-site settings (`enabled`, `prefix`, `template`) are edited on the kernel's generic settings form, + gated by `blog|settings`. +- **Markdown** is rendered with [commonmark-java], bundled in this plugin's `lib/` and private to it. Entry + Markdown is operator-authored, trusted content: raw HTML passes through, exactly as a page author may write + markup. + +## 2. Storage (the site's folder) + +``` +sites//plugins/blog/ +└── entries// + ├── entry.yml # metadata (no id: the folder name is the id) + ├── body-en.md # one Markdown body per language + └── body-es.md +sites//plugins/blog.yml # the per-site settings (the kernel's settings store) +``` + +- Read and written through **`PluginSiteFiles`**, which confines every path to `plugins/blog/` (symbolic links + included) and writes atomically (temporary file + rename), so a public reader never sees a torn `entry.yml`. +- `entry.yml` goes through the plugin's own **lenient** Jackson 3 `YAMLMapper`, so **an entry written by an earlier + release or by hand loads unchanged** (a missing `published:` defaults, an unknown key is ignored) and is **written + back byte for byte** (`BlogStoreTest` proves both with the fixture entries under `src/test/resources/fixtures`, + written by blog 1.3.1 and including an entry with no `author`). +- **`updatedAt`** is the newest modification time of the entry's files (`FileEntry.lastModified`), so a console + edit of only a body moves the `ETag` and `` with no explicit bump. It is read when the source lists the + entries, and that list is cached until a change is announced (§3) — so a file edited **on disk** does not move + them until then. +- **Metadata/body split**: listing reads only `entry.yml` files; a body is read only to render or index it — the + `ContentSource` rule that keeps `/sitemap.xml` from reading the whole corpus. +- Ids (`[a-z0-9-]`, ≤ 100) and language codes (`[a-z]{2,8}`) are validated before any path is formed. One + unreadable `entry.yml` is skipped with a WARN; it never blanks the blog. +- **Backups**: the entries live in the site's folder, so full backups carry them with no `BackupParticipant`. + They are **published content, not personal data**, so nothing is declared under `siteData.personal` and a + transfer copy carries them too. + +## 3. Freshness: who drops what, and when + +| Change | Announced by | What the kernel does | What the blog does | +|---|---|---|---| +| An entry is created, edited, (un)published or deleted | the console: `ContentChanges.changed(site, "blog", id)` after the write | evicts routing, the URL map and the catalog; relays to cluster peers; delivers a `CONTENT` `CatalogChange` | `BlogContentSource.onCatalogChanged` (SOURCE phase) drops the site's URL index and enumerated refs | +| The blog's settings are saved | the kernel's settings form | evicts the settings cache; delivers `SettingsChange` | `onSettingsChanged` drops the index (a prefix change re-keys every URL) | +| A site lifecycle event (incl. a backup **restore**) | the kernel | evicts its caches | `onSiteLifecycle` drops the index (the files were replaced wholesale) | + +The source listens in the **`SOURCE` phase**: the kernel delivers every SOURCE listener first, evicts the catalog +once more, and only then lets consumers (sitemap, search) re-read — so none of them rebuilds from the blog's stale +index. A change replayed from a cluster peer arrives with `local = false` and drops this node's index the same way. +A file edited by hand **on disk** announces nothing, and the blog's index and listing have **no** time-to-live: + +- a **new** entry folder, an `entry.yml` change (title, slug, path, published) or a deleted entry takes effect only + after the next console save of any entry, a save of the blog's settings, or a site lifecycle event — a **site + reload** (`POST /__reload/site/`, Runway Administration §12.2) is the deliberate one; +- an edited **`body-.md`** is served at once (the body is read on every full render), but **under the old + `ETag`** and with the old ``, and search keeps the old text: a browser or CDN holding the page + revalidates to `304` and keeps the old body, until one of the events above. **After editing entry files on + disk, reload the site.** (Measured against a packaged kernel: body changed on disk → `200` with the new body and the + same `ETag`, conditional request → `304`; after the reload → a new `ETag`.) + +**Result, for site managers:** an entry saved in the console serves at once, and is in sitemap.xml and search on +the next request; an unpublished entry is a 404 at once and leaves both (the verify script checks each of these). + +## 4. The body-template contract + +The templates read `${master}` and `${content.*}`. The SPI documents that render model on `ContentSource` / +`ContentRef.bodyTemplate` as a **contract**: a body template renders with +exactly + +- `master` — the site master to wrap (`th:replace="~{${master} :: …}"`); +- `content` — `id`, `sourceKey`, `title`, `description` (in the rendered locale), `bodyHtml`, `attributes` (from + `body()`), `updatedAt`; +- `locale`; and `urls` (link targets: `${urls['index']}`, `${urls['blog:']}`). + +Nothing else is promised. The shipped templates use only these; +**`BlogEntryTemplateContractTest` holds them to it**: statically (every `${…}` starts from one of the four +variables, every `content.` key is a listed one, no bean is reached, every `#{…}` key is in the plugin's bundle) and +by rendering them with Thymeleaf over a model built exactly to the contract, with no kernel class. The attributes +the blog puts in `body()` are its own: `publishedOn` and `author`, each present only when set. + +## 5. The console screen + +`BlogAdminController` carries **`@ConsoleScreen`**: the kernel's own advice fills the operator shell's model +(topbar, menus incl. this plugin's entry, language switcher, footer). Handlers return `ConsoleScreen.LAYOUT_VIEW` with +`CONTENT_TEMPLATE` set to `__plugin__/blog/admin-list|admin-edit` and `PAGE_TITLE_KEY`. + +- **Tenancy** is always the bound one: `RequestContext.site()`; empty (the application console) → `400`. +- **Every handler** is `@PreAuthorize("@authz.may('blog|manage')")` (`AccessCheck`, bean `authz`). +- **Every state change is a `POST`** (create, update, publish toggle, delete) checked by the console chain's CSRF + filter; each form carries `${_csrf}`. The three `GET`s only render. A test asserts this shape. +- **Validation before writing** — what the kernel's fail-closed re-filter would otherwise drop silently: a slug + must match the slug grammar; a custom path must be absolute, free of `|` and `:`, and + **`ContentCatalogView.servablePath`** (safe, not reserved, not an endpoint route such as `/sitemap.xml`). +- **The reverse advisory** asks `ContentCatalogView.pageAt(site, path, locale)` for each language's real URL. +- Console words come from `Messages.console` (the operator's UI language) and the plugin's bundle. The templates + read only the controller's model plus `_csrf`, and only this plugin's message keys (the pretitle uses + `blog.admin.pretitle`, not a kernel key) — `BlogAdminTemplatesRenderTest` checks both. + +## 6. Settings + +| Key | Type | Default | Notes | +|---|---|---|---| +| `enabled` | boolean | `true` | Off: nothing serves or lists; entries are kept. | +| `prefix` | string | `/blog` | Normalized (leading `/`, no trailing `/`); `/` puts entries at the top level. A prefix under which the kernel would not serve an entry (`/app`, `/__x`, `/actuator`, `|`, `..` — checked with `servablePath` on a child path) falls back to `/blog`. | +| `template` | enum | `entry-classic` | `entry-classic` or `entry-minimal`; anything else reads as classic. | + +Read through **`PluginSettings.site(siteId)`** (stored value > descriptor default > code fallback; the code +fallbacks equal the descriptor defaults, which a test asserts). + +## 7. Inventory + +| Piece | Type | Role | +|---|---|---| +| `BlogConfig` | `mainClass` `@Configuration` | wires the three beans from SPI services; bean names `blogStore`, `blogContentSource`, `blogAdminController` | +| `BlogStore` | over `PluginSiteFiles` | `entries//entry.yml` + `body-.md` | +| `BlogEntry` | record | one entry's metadata (the `entry.yml` document) | +| `BlogSettings` | record | the effective per-site settings (`PluginSettings` + `servablePath`) | +| `BlogContentSource` | `ContentSource` (`blog`) + `SiteEventListener` (SOURCE) | enumerate / resolve (O(1) index) / body / indexableText; index invalidation | +| `BlogAdminController` | `@Controller` `@ConsoleScreen` | the authoring screens | +| `templates/` | decoupled Thymeleaf | `entry-classic`, `entry-minimal`, `admin-list`, `admin-edit` | +| `i18n/` | EN / ES | public labels + console | +| `lib/commonmark-*.jar` | bundled | Markdown | + +## 8. What it links (SPI 1.0.0) + +`pom.xml` depends on `runway-spi` only (`runway-spi-testkit` and Thymeleaf for tests; Spring, Spring Security and +Jackson 3 YAML as **provided** platform libraries); **`runway-app` is not a dependency in any scope**, and +`BlogConfigTest` scans the compiled classes' constant pools for any `mx.quest.runway` reference outside +`mx.quest.runway.spi`. + +The SPI services it uses: `PluginSiteFiles` (with the plugin's own `YAMLMapper`), `PluginSettings`, +`ContentCatalogView` (`servablePath`, `pageAt`), `ContentChanges`, `SiteEventListener` (SOURCE phase), +`RequestContext` (`SiteView`), `Messages.console` and `@ConsoleScreen`. + +`requiresSpi: ">=1.0.0"`: a kernel with an older SPI blocks the plugin before wiring, with a reason. + +## 9. Verify + +`scripts/verify-against-host.sh` (honours `JAVA_HOME` (required), `MVN`, `HOST_TARGET`, `HOST_JAR`, `VERIFY_TMPDIR`, +`VERIFY_LOG_DIR`, `COMPANIONS`; never runs +`mvn install`, never needs `--keep`) boots the **packaged** host in ACTIVE mode with the wizard's default site made +bilingual (EN default, ES), the **1.3.1 fixture entries** copied into it, and — built offline from copies of the +sibling folders, skipped if they cannot be built — the `discoverability` and `search` plugins. It checks: + +- the plugin loads (registered, 0 blocked) with **zero** host-linkage and bean-name/surface findings (the kernel + logs "linkage scan: …" and blocks a plugin that links host internals; a surface problem names the bean) and no + WARN or ERROR about it, and the application console's plugins screen shows it Loaded with no health note (this check + has no positive control since every companion became SPI-only; one needs a deliberately host-linked fixture jar); +- the 1.3.1 entries serve unchanged: default URL, localized slug in Spanish, custom path, the byline and date, the + entry without an author (date, no byline), the draft a 404, an `ETag` that revalidates `304`, and a page's + `${urls['blog:hello-world']}`; +- sitemap.xml and llms.txt list the published entries and not the draft; search finds an entry by a body word; +- the console renders inside the shell, is gated for anonymous visitors, and every mutation is a CSRF-checked POST + (no token → `403`, nothing written; a `GET` on a mutation path changes nothing); +- create → serves at once, in sitemap.xml and search on the next request; edit the body → search follows; + unpublish → `404` and gone from both; a reserved custom path is refused at save; a prefix change through the + settings form re-keys the URLs at once (and a reserved prefix falls back to `/blog`); delete removes the folder; +- a full backup and a transfer copy both carry the entries. + +Unit tests (67) run on the testkit's fakes with no kernel class: the store (`BlogStoreTest`, incl. the 1.3.1 +fixture read in place and written back byte for byte, confinement through a planted symbolic link), the source and +its listener (`BlogContentSourceTest`, driven by `EventDispatch` in the kernel's order), the controller +(`BlogAdminControllerTest`: parsing, validation, announcements, advisory, tenancy, the screen's POST-only shape), +the console templates (`BlogAdminTemplatesRenderTest`), the body-template contract +(`BlogEntryTemplateContractTest`), and the plugin's contract with the host (`BlogConfigTest`: wiring, bean names, +descriptor, EN/ES parity, the constant-pool scan). + +## 10. Not covered (honest gaps) + +- **No listing page.** There is no `/blog` index of entries; link entries from a site page with + `${urls['blog:']}`. A listing would be a widget or a virtual page — a feature for a later release. +- **No per-entry `noindex` or canonical override**, no categories or tags, no RSS/Atom feed. +- **`author` is free text** (a display name), not an account. +- **Concurrent edits of one entry**: the last save wins (each file write is atomic; there is no merge). +- **A file edited on disk** is not picked up until something announces a change (any console save, a settings + save, a site reload); an edited body is served at once but under the old `ETag` until then (§3). Reload the site + after editing entry files by hand. + +[commonmark-java]: https://github.com/commonmark/commonmark-java diff --git a/plugins/blog/i18n/messages.properties b/plugins/blog/i18n/messages.properties new file mode 100644 index 0000000..291538e --- /dev/null +++ b/plugins/blog/i18n/messages.properties @@ -0,0 +1,71 @@ +# Blog plugin — appended LAST to each site's bundle (add-only: a site defining the same key wins) and to the +# operator console bundle. Public-side keys (the entry templates) + the console screens. + +# Public entry templates +blog.publishedOn=Published on +blog.by=By +blog.back=Back to the site + +# Console — permissions / settings / menu labels (referenced from plugin.yml) +blog.perm.settings=Configure the blog +blog.perm.manage=Manage blog entries +blog.settings.enabled=Blog enabled +blog.settings.prefix=URL prefix +blog.settings.template=Entry template +blog.menu=Blog + +# Console — list screen +blog.admin.pretitle=Site +blog.admin.title=Blog +blog.admin.heading=Blog +blog.admin.new=New entry +blog.admin.new.tip=Create a new blog entry (it starts unpublished). +blog.admin.disabled=The blog is disabled for this site (see the plugin's settings) — entries are kept but none serves. +blog.admin.col.entry=Entry +blog.admin.col.path=Path +blog.admin.col.langs=Languages +blog.admin.col.date=Date +blog.admin.col.status=Status +blog.admin.col.actions=Actions +blog.admin.empty=No entries yet. +blog.admin.published=Published +blog.admin.draft=Draft +blog.admin.edit=Edit +blog.admin.publish=Publish +blog.admin.unpublish=Unpublish +blog.admin.delete=Delete +blog.admin.delete.confirm=Delete this entry and all its languages? + +# Console — editor +blog.edit.heading=Edit entry +blog.edit.headingNew=New entry +blog.edit.back=Back to blog +blog.edit.shadowed=A page owns this entry's address — the page wins, so the entry is unreachable there: +blog.edit.entry=Entry +blog.edit.id=Id +blog.edit.id.tip=The entry's stable identity (lowercase letters, digits, hyphens). It names the entry's folder and its default slug; it cannot be changed later. +blog.edit.date=Publication date +blog.edit.author=Author +blog.edit.author.tip=Who is credited for this post. Shown as a byline and used for structured data. Leave blank for an unattributed entry. +blog.edit.customPath=Custom path +blog.edit.customPath.tip=Optional absolute address (e.g. /announcing-v2) replacing the prefixed one for the default language. Leave empty for the normal / address. +blog.edit.published=Published +blog.edit.defaultLang=default +blog.edit.langOn=Published in this language +blog.edit.title=Title +blog.edit.slug=Slug +blog.edit.slug.tip=The address segment under the blog prefix for this language. The default language's slug is the entry's base slug. +blog.edit.description=Description +blog.edit.body=Body (Markdown) +blog.edit.save=Save + +# Console — flash/error feedback +blog.flash.created=Entry created. +blog.flash.saved=Saved. +blog.flash.published=Entry published. +blog.flash.unpublished=Entry unpublished. +blog.flash.deleted=Entry deleted. +blog.error.duplicate=An entry with that id already exists. +blog.error.reservedId=That id is reserved — pick another. +blog.error.invalid=Some fields are invalid: +blog.error.ioError=The entry could not be written. diff --git a/plugins/blog/i18n/messages_es.properties b/plugins/blog/i18n/messages_es.properties new file mode 100644 index 0000000..52bc093 --- /dev/null +++ b/plugins/blog/i18n/messages_es.properties @@ -0,0 +1,66 @@ +# Blog plugin — español. + +blog.publishedOn=Publicado el +blog.by=Por +blog.back=Volver al sitio + +blog.perm.settings=Configurar el blog +blog.perm.manage=Gestionar entradas del blog +blog.settings.enabled=Blog activo +blog.settings.prefix=Prefijo de URL +blog.settings.template=Plantilla de entrada +blog.menu=Blog + +blog.admin.pretitle=Sitio +blog.admin.title=Blog +blog.admin.heading=Blog +blog.admin.new=Nueva entrada +blog.admin.new.tip=Crea una nueva entrada (empieza sin publicar). +blog.admin.disabled=El blog está desactivado para este sitio (ver la configuración del plugin) — las entradas se conservan pero ninguna se sirve. +blog.admin.col.entry=Entrada +blog.admin.col.path=Ruta +blog.admin.col.langs=Idiomas +blog.admin.col.date=Fecha +blog.admin.col.status=Estado +blog.admin.col.actions=Acciones +blog.admin.empty=Aún no hay entradas. +blog.admin.published=Publicada +blog.admin.draft=Borrador +blog.admin.edit=Editar +blog.admin.publish=Publicar +blog.admin.unpublish=Despublicar +blog.admin.delete=Eliminar +blog.admin.delete.confirm=¿Eliminar esta entrada y todos sus idiomas? + +blog.edit.heading=Editar entrada +blog.edit.headingNew=Nueva entrada +blog.edit.back=Volver al blog +blog.edit.shadowed=Una página posee la dirección de esta entrada — la página gana, así que la entrada es inaccesible ahí: +blog.edit.entry=Entrada +blog.edit.id=Id +blog.edit.id.tip=La identidad estable de la entrada (minúsculas, dígitos, guiones). Nombra su carpeta y su slug por defecto; no puede cambiarse después. +blog.edit.date=Fecha de publicación +blog.edit.author=Autor +blog.edit.author.tip=A quién se atribuye esta entrada. Se muestra como firma y se usa en los datos estructurados. Déjelo en blanco si no lleva autor. +blog.edit.customPath=Ruta personalizada +blog.edit.customPath.tip=Dirección absoluta opcional (p. ej. /anunciando-v2) que sustituye a la prefijada para el idioma por defecto. Vacío = la dirección normal /. +blog.edit.published=Publicada +blog.edit.defaultLang=por defecto +blog.edit.langOn=Publicada en este idioma +blog.edit.title=Título +blog.edit.slug=Slug +blog.edit.slug.tip=El segmento de la dirección bajo el prefijo del blog para este idioma. El slug del idioma por defecto es el slug base de la entrada. +blog.edit.description=Descripción +blog.edit.body=Cuerpo (Markdown) +blog.edit.save=Guardar + +# Consola — mensajes de estado/error +blog.flash.created=Entrada creada. +blog.flash.saved=Guardado. +blog.flash.published=Entrada publicada. +blog.flash.unpublished=Entrada despublicada. +blog.flash.deleted=Entrada eliminada. +blog.error.duplicate=Ya existe una entrada con ese id. +blog.error.reservedId=Ese id está reservado — elige otro. +blog.error.invalid=Algunos campos no son válidos: +blog.error.ioError=No se pudo escribir la entrada. diff --git a/plugins/blog/plugin.yml b/plugins/blog/plugin.yml new file mode 100644 index 0000000..0736bfb --- /dev/null +++ b/plugins/blog/plugin.yml @@ -0,0 +1,43 @@ +# ============================================================================= +# Runway Blog Plugin — descriptor +# Blog entries as first-class virtual pages via the kernel's ContentSource seam. +# Links ONLY the Runway SPI (service tier, SPI 1.0.0). +# The install folder name MUST equal this `id`: external/plugins/blog/. +# ============================================================================= +id: blog +name: Blog +version: 2.1.0 + +# Built against the SPI service tier (ContentChanges, SiteEventListener, ContentCatalogView, PluginSettings, +# PluginSiteFiles, RequestContext, Messages and @ConsoleScreen) as frozen in SPI 1.0.0. A kernel below it BLOCKS this +# plugin at startup with a reason. +requiresSpi: ">=1.0.0" + +# The @Configuration registered into the host context before refresh. Its package (mx.quest.blog) lives +# OUTSIDE mx.quest.runway so the host never double-scans it. Beans are wired EXPLICITLY (no @ComponentScan), and every +# bean name starts with the plugin id (blog…). +mainClass: mx.quest.blog.BlogConfig + +# --- Per-site data ----------------------------------------------------------------------------------------- +# Entries live in sites//plugins/blog/entries// (entry.yml + body-.md). They are PUBLISHED +# CONTENT the site's own operators author, not visitor or user input, so nothing is +# declared under siteData.personal: a transfer copy of the site carries the blog, like its pages. + +# --- Grantable control-point permissions ----------------------------------------------------------------- +# `settings` (reserved id) gates the per-site config editor; `manage` gates the authoring screen. +permissions: + - { id: settings, realm: tenant, label: blog.perm.settings, defaultRoles: [] } + - { id: manage, realm: tenant, label: blog.perm.manage, defaultRoles: [] } + +# --- Per-site settings (tenant-owned BEHAVIOUR; over sites//plugins/blog.yml; applied IMMEDIATELY — a save +# reaches the blog's SiteEventListener, which drops its per-site URL index before anything re-reads it) ------- +siteSettings: + - { key: enabled, type: boolean, default: true, label: blog.settings.enabled } + - { key: prefix, type: string, default: "/blog", label: blog.settings.prefix } + - { key: template, type: enum, default: entry-classic, range: "entry-classic,entry-minimal", + label: blog.settings.template } + +# --- Tenant-console menu entry (gated by the FULL namespaced permission key; visibility is UX only) -------- +menu: + - { realm: tenant, region: menu, order: 55, label: blog.menu, path: "/__admin/blog", + permission: "blog|manage", icon: "fa-solid fa-feather-pointed" } diff --git a/plugins/blog/pom.xml b/plugins/blog/pom.xml new file mode 100644 index 0000000..2ef20c0 --- /dev/null +++ b/plugins/blog/pom.xml @@ -0,0 +1,184 @@ + + + 4.0.0 + + + + org.springframework.boot + spring-boot-starter-parent + 4.0.6 + + + + mx.quest + runway-plugin-blog + 2.1.0 + jar + Runway Blog Plugin + + + GNU Affero General Public License v3.0, with the Runway additional permission for plugins + https://www.gnu.org/licenses/agpl-3.0.txt + repo + See LICENSE and LICENSE-EXCEPTION. + + + + A blog for Runway sites, built on the kernel's ContentSource seam: entries are plugin-owned files in + the tenant's folder (metadata + per-language Markdown bodies), served as first-class virtual pages — + own URLs under a configurable prefix (or per-entry custom paths), the site's master chrome, full + locale dispatch, sitemap/llms.txt listing, search indexing, and by-id links. Authored in a console + screen. Links only the Runway SPI (service tier, SPI 1.0.0). + + + + 25 + 25 + UTF-8 + + 2026-10-21T18:56:00Z + 1.0.0 + + 0.25.1 + + + + + mx.quest + runway-spi + ${runway.version} + + + + mx.quest + runway-spi-testkit + ${runway.version} + test + + + + + org.springframework.boot + spring-boot-starter + provided + + + + org.springframework + spring-webmvc + provided + + + + org.springframework.security + spring-security-core + provided + + + + tools.jackson.dataformat + jackson-dataformat-yaml + provided + + + + + org.commonmark + commonmark + ${commonmark.version} + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.thymeleaf + thymeleaf-spring6 + test + + + + + runway-plugin-blog + + + + org.apache.maven.plugins + maven-dependency-plugin + + + stage-lib + package + + copy-dependencies + + + ${project.build.directory}/staged-lib + runtime + + mx.quest + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + assemble-plugin-folder + package + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/blog/scripts/verify-against-host.sh b/plugins/blog/scripts/verify-against-host.sh new file mode 100755 index 0000000..86b1dde --- /dev/null +++ b/plugins/blog/scripts/verify-against-host.sh @@ -0,0 +1,331 @@ +#!/usr/bin/env bash +# Build this plugin, drop it into a throwaway Runway deployment, boot the PACKAGED host in ACTIVE mode, and prove +# the blog's contract end to end against a Runway 1.0.0 kernel (SPI 1.0.0): +# - it loads with ZERO host-linkage and bean-name/surface findings, and nothing blocks or quarantines it; +# - entries WRITTEN BY blog 1.3.1 (the test fixture, placed in the site's plugins/blog/entries/ before the boot — +# one of them without an author) load unchanged: they serve at their URLs (default prefix, localized slug, +# custom path) inside the tenant's own master chrome, with the byline where there is one and none where there +# is not; the draft does not serve; +# - a page linking ${urls['blog:']} gets the entry's URL from the kernel catalog; +# - with discoverability and search installed (built from this repository's sibling folders into the scratch +# folder; SKIPPED when they cannot be built): sitemap.xml and llms.txt list the published entries and not the +# draft, and search finds an entry by a word that is only in its Markdown body (indexableText); +# - the console screen (@ConsoleScreen) renders inside the operator shell, gated (anonymous → login), and every +# mutation is a CSRF-checked POST: without the token → 403 and nothing written; a GET on a mutation path +# changes nothing; +# - signed in as the site owner: create → the entry serves AT ONCE and is in sitemap and search on the next +# request (ContentChanges evicts routing, the catalog and search); edit the body → search follows; unpublish → +# 404 and gone from sitemap and search; a reserved custom path is refused at save; a prefix change through the +# settings form re-keys the URLs at once (onSettingsChanged); delete → the folder is gone; +# - a FULL backup and a TRANSFER copy both carry the entries (published content, not personal data). +# 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--exec.jar the kernel to verify against (default: the host checkout's +# runway-app/target jar MATCHING its pom version) +# COMPANIONS="discoverability search" sibling plugins to install for the sitemap/llms.txt/search checks +# (built offline from a COPY in the scratch folder; their own folders +# are never written). Set it to "" to skip those checks. +# VERIFY_TMPDIR=/dir where the throwaway deployment goes (default: $TMPDIR or /tmp) +# VERIFY_LOG_DIR=/dir keep copies of the host logs and the backup manifests there +# The script never runs `mvn install` (nothing is written to ~/.m2): it packages offline against whatever is already +# in the local repository. +set -uo pipefail + +HERE="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)" +# JAVA_HOME must name a JDK 25. MVN (default: `mvn` on the PATH) and HOST_TARGET (default: see above) can be set in the environment. +if [ -z "${JAVA_HOME:-}" ] || [ ! -x "$JAVA_HOME/bin/java" ]; then echo "set JAVA_HOME to a JDK 25"; exit 2; fi +export JAVA_HOME +JAVA="$JAVA_HOME/bin/java" +MVN="${MVN:-mvn}" +# Default host: the kernel at the root of the repository this plugin sits in (plugins//), 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 +COMPANIONS="${COMPANIONS-discoverability search}" + +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=Blog-Admin-2026; SITE_USER=owner; SITE_PW=Blog-Site-2026 +SECRET_KEY=blog-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:.*\(.*\).*:\1:p' "$HOST_TARGET/../pom.xml" | head -1)" + JAR="$HOST_TARGET/runway-app-$HOST_VERSION-exec.jar" +fi +[ -f "$JAR" ] || { echo "no host exec jar $JAR — build the host (mvn -pl runway-app package) or set HOST_JAR"; exit 1; } +echo "[verify] host jar: $JAR" + +SCRATCH="$(mktemp -d "${VERIFY_TMPDIR:-${TMPDIR:-/tmp}}/blog-verify.XXXXXX")" +cleanup() { + [ -z "${VERIFY_LOG_DIR:-}" ] || { mkdir -p "$VERIFY_LOG_DIR" \ + && cp "$SCRATCH"/*.log "$SCRATCH"/*-manifest.yml "$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/blog" "$EXT/plugins/blog" + +# --- Companion plugins, built from a COPY (their own folders stay untouched) --------------------------------------- +INSTALLED="" +for id in $COMPANIONS; do + src="$HERE/../$id" + [ -f "$src/pom.xml" ] || { echo "[verify] companion $id: no source at $src"; continue; } + mkdir -p "$SCRATCH/build" + ( cd "$src" && tar --exclude=./target -cf - . ) | ( mkdir -p "$SCRATCH/build/$id" && cd "$SCRATCH/build/$id" && tar -xf - ) + if ( cd "$SCRATCH/build/$id" && "$MVN" -o -q -DskipTests package >"$SCRATCH/build-$id.txt" 2>&1 ) \ + && [ -d "$SCRATCH/build/$id/target/$id" ]; then + cp -r "$SCRATCH/build/$id/target/$id" "$EXT/plugins/$id" + INSTALLED="$INSTALLED $id" + echo "[verify] companion $id $(sed -n 's/^version: *//p' "$EXT/plugins/$id/plugin.yml") installed" + else + echo "[verify] companion $id could not be built (see build-$id.txt) — its checks are skipped" + fi +done +has() { case " $INSTALLED " in *" $1 "*) return 0 ;; esac; return 1; } + +wait_for() { for _ in $(seq 1 "$3"); do grep -q "$2" "$1" 2>/dev/null && return 0; sleep 1; done; return 1; } +PASS=0; FAIL=0; SKIP=0 +ck() { if eval "$2" >/dev/null 2>&1; then echo " PASS $1"; PASS=$((PASS+1)); else echo " FAIL $1"; FAIL=$((FAIL+1)); fi; } +skip() { echo " SKIP $1"; SKIP=$((SKIP+1)); } +boot() { ( cd "$SCRATCH" && exec "$JAVA" -jar "$JAR" --server.port="$PORT" --runway.storage.external="$EXT" \ + --runway.security.secret-key="$SECRET_KEY" ) >"$1" 2>&1 & PID=$!; } + +echo "[verify] booting host (wizard) on :$PORT ..." +boot "$SCRATCH/wizard.log" +wait_for "$SCRATCH/wizard.log" "Started RunwayApplication" 90 || { echo "wizard did not start"; tail -20 "$SCRATCH/wizard.log"; exit 1; } +curl -s -o /dev/null -X POST "$BASE/setup" --data-urlencode "username=$APP_USER" --data-urlencode "password=$APP_PW" \ + --data-urlencode "displayName=Root" --data-urlencode "siteAdminUsername=$SITE_USER" --data-urlencode "siteAdminPassword=$SITE_PW" +for _ in $(seq 1 30); do kill -0 "$PID" 2>/dev/null || break; sleep 1; done + +# --- The default site, prepared on disk before the ACTIVE boot reads it --------------------------------------------- +SITE="$EXT/sites/default" +[ -f "$SITE/site.yml" ] || { echo "the wizard did not seed $SITE"; exit 1; } +# Two languages (English default, Spanish), so the localized slug and the locale ladder are exercised. +python3 -I - "$SITE/site.yml" <<'PY' +import re, sys +p = sys.argv[1]; s = open(p, encoding="utf-8").read() +s = re.sub(r'(?m)^locales:\n(?:- .*\n)*', 'locales:\n- "en"\n- "es"\n', s) +open(p, "w", encoding="utf-8").write(s) +PY +grep -q '^- "es"' "$SITE/site.yml" || { echo "could not add Spanish to the site:"; cat "$SITE/site.yml"; exit 1; } +# Entries exactly as blog 1.3.1 wrote them (the unit tests' fixture, produced by the 1.3.1 store). +mkdir -p "$SITE/plugins/blog" +cp -r "$HERE/src/test/resources/fixtures/blog-1.3.1/entries" "$SITE/plugins/blog/entries" +# A page whose body links an entry through the kernel's URL map: the seeded About page, edited on disk. +sed -i 's|
|
blog|' "$SITE/templates/about.html" +sed -i 's|||' \ + "$SITE/templates/about.th.xml" +# llms.txt is part of discoverability's opt-in GEO area (off by default): switch it on for this site. +has discoverability && printf '"geo.enabled": true\n' > "$SITE/plugins/discoverability.yml" + +echo "[verify] booting host (ACTIVE) ..." +boot "$SCRATCH/active.log" +wait_for "$SCRATCH/active.log" "Started RunwayApplication" 90 || { echo "ACTIVE did not start"; tail -20 "$SCRATCH/active.log"; exit 1; } +LOG="$SCRATCH/active.log" +ENTRIES="$SITE/plugins/blog/entries" +code() { curl -s -o /dev/null -w '%{http_code}' -H 'Accept-Language: en' "$@"; } +get() { curl -s -H 'Accept-Language: en' "$@"; } + +echo "== plugin load (SPI 1.0.0 contract) ==" +EXPECTED=$((1 + $(echo $INSTALLED | wc -w))) +ck "plugins registered ($EXPECTED), 0 blocked" "grep -qE 'plugins: $EXPECTED registered, 0 blocked' '$LOG'" +ck "blog not blocked / quarantined" "! grep -qE \"plugin 'blog' is blocked|plugin-quarantine/blog\" '$LOG'" +# Host linkage and the surface rules: the kernel logs "plugin 'blog' linkage scan: " before "is blocked" (the +# check above), and a surface problem names the offending bean ("bean name …", "… may not contribute"). The badge +# wording of the plugins screen ("uses host internals") is matched too. +ck "ZERO host-linkage findings for blog" "! grep -qE \"plugin 'blog' (uses host internals|linkage scan)\" '$LOG'" +ck "ZERO bean-name/surface findings for blog" "! grep -qE \"plugin 'blog'.*(bean name|may not contribute)\" '$LOG'" +ck "no WARN/ERROR from or about the blog" "! grep -E ' (WARN|ERROR) ' '$LOG' | grep -qiE \"mx\\.quest\\.blog|'blog'|blog entr\"" +ck "no key collision / degraded" "! grep -qiE 'collision|duplicate key|degraded' '$LOG'" + +# The application console's plugins screen: blog's row shows the version, LOADED, and no health note at all — no +# host-linkage badge, no contained failure, no warning. +APP_JAR_C="$SCRATCH/cookies-app.txt" +ac() { curl -s -H 'Accept-Language: en' -c "$APP_JAR_C" -b "$APP_JAR_C" "$@"; } +ac -o /dev/null -X POST "$BASE/app/login" --data-urlencode "username=$APP_USER" --data-urlencode "password=$APP_PW" \ + --data-urlencode "_csrf=$(ac "$BASE/app/login" | grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//')" +ac "$BASE/__app/plugins" > "$SCRATCH/plugins-screen.html" +row() { # plugin-id -> its on the plugins screen + python3 -I - "$SCRATCH/plugins-screen.html" "$1" <<'PY2' +import re, sys +html = open(sys.argv[1], encoding="utf-8").read() +for tr in re.findall(r"(?s)", html): + if re.search(r'class="c-id">%s<' % re.escape(sys.argv[2]), tr): + print(tr); break +PY2 +} +row blog > "$SCRATCH/plugins-row-blog.html" +BLOG_VERSION="$(sed -n 's/^version: *//p' "$HERE/plugin.yml")" +ck "plugins screen: blog $BLOG_VERSION, Loaded" \ + "grep -q 'class=\"c-version\">$BLOG_VERSION<' '$SCRATCH/plugins-row-blog.html' && grep -q 'bg-green-lt' '$SCRATCH/plugins-row-blog.html'" +ck "…with no host-linkage badge, no failure count and no health notes" \ + "[ -s '$SCRATCH/plugins-row-blog.html' ] && ! grep -qE 'c-host|c-failures|c-notes|c-warning|c-refused' '$SCRATCH/plugins-row-blog.html'" +# There used to be a positive control here: "an unmigrated companion (discoverability) does show the badge". Every +# companion is SPI-only now, so it failed for the wrong reason and was dropped. A real control +# needs a deliberately host-linked fixture jar; until then the badge check above has none. + +echo "== entries written by blog 1.3.1 serve unchanged ==" +get "$BASE/blog/hello-world" > "$SCRATCH/hello.html" +ck "/blog/hello-world -> 200" "[ \"\$(code '$BASE/blog/hello-world')\" = 200 ]" +ck "…inside the tenant's master chrome (site header + footer)" \ + "grep -q 'id=\"site-header\"' '$SCRATCH/hello.html' && grep -q 'id=\"site-footer\"' '$SCRATCH/hello.html' && ! grep -q 'from the master at render' '$SCRATCH/hello.html'" +ck "…with its title, its rendered Markdown and its byline" \ + "grep -q 'Hello world' '$SCRATCH/hello.html' && grep -q 'bold' '$SCRATCH/hello.html' && grep -q 'By Jane Doe' '$SCRATCH/hello.html' && grep -q 'Published on 2026-07-17' '$SCRATCH/hello.html'" +get "$BASE/es/blog/hola-mundo" > "$SCRATCH/hola.html" +ck "/es/blog/hola-mundo (the localized slug) -> 200 in Spanish" \ + "[ \"\$(code '$BASE/es/blog/hola-mundo')\" = 200 ] && grep -q 'Hola mundo' '$SCRATCH/hola.html' && grep -q 'Publicado el' '$SCRATCH/hola.html'" +get "$BASE/blog/no-author" > "$SCRATCH/no-author.html" +ck "the entry 1.3.1 wrote WITHOUT an author serves, with a date and no byline" \ + "[ \"\$(code '$BASE/blog/no-author')\" = 200 ] && grep -q 'Unattributed' '$SCRATCH/no-author.html' && grep -q 'Published on 2026-08-01' '$SCRATCH/no-author.html' && ! grep -q 'id=\"entry-author\"' '$SCRATCH/no-author.html'" +ck "the custom path /announcing-v2 serves the launch entry" \ + "[ \"\$(code '$BASE/announcing-v2')\" = 200 ] && get '$BASE/announcing-v2' | grep -q 'By Richard Roe'" +ck "the draft does not serve (404)" "[ \"\$(code '$BASE/blog/draft-post')\" = 404 ]" +ck "a page's \${urls['blog:hello-world']} is the entry's URL (kernel catalog)" \ + "get '$BASE/about' | grep -q 'id=\"to-blog\" href=\"/blog/hello-world\"'" +ck "an entry carries an ETag (its updatedAt) and revalidates 304" \ + "E=\$(curl -s -D - -o /dev/null '$BASE/blog/hello-world' | sed -n 's/^[Ee][Tt]ag: *//p' | tr -d '\r'); [ -n \"\$E\" ] && [ \"\$(code -H \"If-None-Match: \$E\" '$BASE/blog/hello-world')\" = 304 ]" + +sitemap() { get "$BASE/sitemap.xml"; } +search() { get "$BASE/search/api?q=$1"; } +echo "== sitemap.xml / llms.txt / search through the kernel catalog ==" +if has discoverability; then + sitemap > "$SCRATCH/sitemap-0.xml" + ck "sitemap.xml lists the published entries (default + localized URLs, custom path)" \ + "grep -q '/blog/hello-world' '$SCRATCH/sitemap-0.xml' && grep -q '/es/blog/hola-mundo' '$SCRATCH/sitemap-0.xml' && grep -q '/announcing-v2' '$SCRATCH/sitemap-0.xml' && grep -q '/blog/no-author' '$SCRATCH/sitemap-0.xml'" + ck "…and not the draft" "! grep -q 'draft-post' '$SCRATCH/sitemap-0.xml'" + ck "llms.txt lists an entry" "get '$BASE/llms.txt' | grep -q '/blog/hello-world'" +else + skip "sitemap.xml / llms.txt (discoverability not installed)" +fi +if has search; then + ck "search finds an entry by a word only in its Markdown body (indexableText)" \ + "search words | grep -q '/blog/hello-world'" + ck "…and not the draft's body" "! search 'Not+yet' | grep -q 'draft-post'" +else + skip "search (search not installed)" +fi + +echo "== the console screen: @ConsoleScreen, gated, CSRF-checked POSTs ==" +token() { grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//'; } +JAR_C="$SCRATCH/cookies.txt" +sc() { curl -s -H 'Accept-Language: en' -c "$JAR_C" -b "$JAR_C" "$@"; } +ck "anonymous GET /__admin/blog does not render the screen (sign-in first)" \ + "R=\$(curl -s -o /dev/null -w '%{http_code} %{redirect_url}' '$BASE/__admin/blog'); echo \"\$R\" | grep -qE '^(302|303) .*/login|^40[13]'" +ck "anonymous POST create without a token -> 403, nothing written" \ + "[ \"\$(code -X POST '$BASE/__admin/blog/create' -d 'id=anon-post&title_en=x&published=on')\" = 403 ] && [ ! -e '$ENTRIES/anon-post' ]" +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/blog" > "$SCRATCH/console-list.html" +ck "signed in: the list renders INSIDE the operator shell" \ + "grep -q 'id=\"topbar\"' '$SCRATCH/console-list.html' && grep -q 'id=\"op-main\"' '$SCRATCH/console-list.html' && grep -q 'id=\"bl-heading\"' '$SCRATCH/console-list.html'" +ck "…with the 1.3.1 entries, the draft badge and the plugin's pretitle" \ + "grep -q '>hello-world<' '$SCRATCH/console-list.html' && grep -q '>draft-post<' '$SCRATCH/console-list.html' && grep -q '>Draft<' '$SCRATCH/console-list.html' && grep -q 'id=\"bl-pretitle\">Site<' '$SCRATCH/console-list.html'" +ck "…and the shell's menu carries the Blog entry" "grep -q 'href=\"/__admin/blog\"' '$SCRATCH/console-list.html'" +ck "every mutating form is a POST carrying the console's CSRF token" \ + "! grep -qE 'href=\"/__admin/blog/[^\"]*/(publish|delete)\"' '$SCRATCH/console-list.html' && grep -qE 'method=\"post\" action=\"/__admin/blog/hello-world/publish\"' '$SCRATCH/console-list.html' && grep -qE 'name=\"_csrf\" value=\"[^\"]+\"' '$SCRATCH/console-list.html'" +TOKEN="$(token < "$SCRATCH/console-list.html")" +ck "signed in, POST without the token -> 403 and the entry stays published" \ + "[ \"\$(sc -o /dev/null -w '%{http_code}' -X POST '$BASE/__admin/blog/hello-world/publish')\" = 403 ] && grep -q 'published: true' '$ENTRIES/hello-world/entry.yml'" +ck "signed in, GET on the publish path changes nothing" \ + "sc -o /dev/null '$BASE/__admin/blog/hello-world/publish'; grep -q 'published: true' '$ENTRIES/hello-world/entry.yml'" +ck "the editor of an entry 1.3.1 wrote shows its fields" \ + "sc '$BASE/__admin/blog/no-author/edit' | grep -q 'value=\"Unattributed\"'" + +echo "== create / edit / unpublish / delete: every change is visible on the next request ==" +[ -n "$(has discoverability && echo y)" ] && sitemap > /dev/null # warm the catalog cache before the change +[ -n "$(has search && echo y)" ] && search warmup > /dev/null # …and the search index +R="$(sc -o /dev/null -w '%{http_code} %{redirect_url}' -X POST "$BASE/__admin/blog/create" \ + --data-urlencode "_csrf=$TOKEN" --data-urlencode 'id=fresh-post' --data-urlencode 'title_en=Fresh post' \ + --data-urlencode 'title_es=Entrada nueva' --data-urlencode 'slug_es=entrada-nueva' \ + --data-urlencode 'body_en=Zanzibar is the first word of this body.' --data-urlencode 'locales_en=on' \ + --data-urlencode 'locales_es=on' --data-urlencode 'published=on' --data-urlencode 'publishedOn=2026-10-18')" +ck "create -> redirect to the editor" "echo '$R' | grep -qE '^302 .*/__admin/blog/fresh-post/edit'" +ck "…written into the entries folder" "[ -f '$ENTRIES/fresh-post/entry.yml' ] && [ -f '$ENTRIES/fresh-post/body-en.md' ]" +ck "…and it serves AT ONCE (routing evicted)" "get '$BASE/blog/fresh-post' | grep -q 'Zanzibar'" +ck "…in Spanish at its localized slug" "[ \"\$(code '$BASE/es/blog/entrada-nueva')\" = 200 ]" +if has discoverability; then ck "…and is in sitemap.xml on the next request" "sitemap | grep -q '/blog/fresh-post'"; fi +if has search; then ck "…and search finds it on the next request" "search zanzibar | grep -q '/blog/fresh-post'"; fi +sc -o /dev/null -X POST "$BASE/__admin/blog/fresh-post" --data-urlencode "_csrf=$TOKEN" \ + --data-urlencode 'title_en=Fresh post' --data-urlencode 'body_en=Quokka replaced the old word.' \ + --data-urlencode 'locales_en=on' --data-urlencode 'published=on' --data-urlencode 'publishedOn=2026-10-18' +ck "edit the body -> the page shows the new body" "get '$BASE/blog/fresh-post' | grep -q 'Quokka'" +if has search; then + ck "…search finds the new word" "search quokka | grep -q '/blog/fresh-post'" + ck "…and no longer the old one" "! search zanzibar | grep -q '/blog/fresh-post'" +fi +ck "a reserved custom path is refused at save, nothing written" \ + "sc -X POST '$BASE/__admin/blog/create' --data-urlencode '_csrf=$TOKEN' -d 'id=bad-path&title_en=x&customPath=/app/x&published=on' | grep -q 'customPath' && [ ! -e '$ENTRIES/bad-path' ]" +sc -o /dev/null -X POST "$BASE/__admin/blog/fresh-post/publish" --data-urlencode "_csrf=$TOKEN" +ck "unpublish -> 404 at once" "[ \"\$(code '$BASE/blog/fresh-post')\" = 404 ]" +if has discoverability; then ck "…and gone from sitemap.xml" "! sitemap | grep -q 'fresh-post'"; fi +if has search; then ck "…and from search" "! search quokka | grep -q 'fresh-post'"; fi + +echo "== a prefix change through the settings form re-keys every URL at once ==" +SETTINGS="$BASE/__admin/plugins/blog/settings" +sc -o /dev/null -X POST "$SETTINGS" --data-urlencode "_csrf=$(sc "$SETTINGS" | token)" \ + --data-urlencode 'enabled=true' --data-urlencode 'prefix=/news' --data-urlencode 'template=entry-minimal' +ck "the settings were stored" "grep -q 'prefix: \"/news\"' '$SITE/plugins/blog.yml'" +ck "/news/hello-world -> 200 with the minimal template (no byline)" \ + "[ \"\$(code '$BASE/news/hello-world')\" = 200 ] && ! get '$BASE/news/hello-world' | grep -q 'By Jane Doe'" +ck "/blog/hello-world -> 404 (the old URL is gone)" "[ \"\$(code '$BASE/blog/hello-world')\" = 404 ]" +ck "the custom path is unaffected" "[ \"\$(code '$BASE/announcing-v2')\" = 200 ]" +if has discoverability; then ck "sitemap.xml follows the new prefix" "sitemap | grep -q '/news/hello-world'"; fi +sc -o /dev/null -X POST "$SETTINGS" --data-urlencode "_csrf=$(sc "$SETTINGS" | token)" \ + --data-urlencode 'enabled=true' --data-urlencode 'prefix=/app' --data-urlencode 'template=entry-classic' +ck "a reserved prefix (/app) falls back to /blog instead of hiding every entry" \ + "[ \"\$(code '$BASE/blog/hello-world')\" = 200 ]" + +echo "== backups carry the blog (published content, not personal data) ==" +sc -o "$SCRATCH/full.zip" "$BASE/__admin/backups/download" +sc -o "$SCRATCH/transfer.zip" "$BASE/__admin/backups/download-transfer" +zipq() { # zip mode -> prints what was asked + python3 -I - "$@" <<'PY' +import sys, zipfile +z = zipfile.ZipFile(sys.argv[1]); mode = sys.argv[2] +names = z.namelist() +if mode == "has": + sys.exit(0 if any(n.endswith(sys.argv[3]) for n in names) else 1) +if mode == "read": + n = next(n for n in names if n.endswith(sys.argv[3])); sys.stdout.write(z.read(n).decode("utf-8")) +PY +} +zipq "$SCRATCH/full.zip" read manifest.yml > "$SCRATCH/full-manifest.yml" 2>/dev/null +zipq "$SCRATCH/transfer.zip" read manifest.yml > "$SCRATCH/transfer-manifest.yml" 2>/dev/null +ck "the full backup carries the entries" "zipq '$SCRATCH/full.zip' has plugins/blog/entries/hello-world/entry.yml" +ck "the transfer copy carries them too" "zipq '$SCRATCH/transfer.zip' has plugins/blog/entries/no-author/body-en.md" +ck "…and its manifest omits nothing of the blog" "! grep -q 'plugins/blog' '$SCRATCH/transfer-manifest.yml'" + +echo "== delete ==" +sc -o /dev/null -X POST "$BASE/__admin/blog/fresh-post/delete" --data-urlencode "_csrf=$TOKEN" +ck "delete removes the entry's folder" "[ ! -e '$ENTRIES/fresh-post' ]" +ck "…and the other entries are intact" "[ -f '$ENTRIES/hello-world/entry.yml' ] && [ -f '$ENTRIES/no-author/entry.yml' ]" + +ck "no ERROR in the host log after all of it" "! grep -q ' ERROR ' '$LOG'" + +echo; echo "RESULT: $PASS passed, $FAIL failed, $SKIP skipped" +if [ "$KEEP" = "yes" ]; then echo "[verify] kept at $BASE (scratch $SCRATCH; kill $PID to stop)"; wait "$PID"; fi +exit "$FAIL" diff --git a/plugins/blog/src/main/java/mx/quest/blog/BlogAdminController.java b/plugins/blog/src/main/java/mx/quest/blog/BlogAdminController.java new file mode 100644 index 0000000..d94b6e3 --- /dev/null +++ b/plugins/blog/src/main/java/mx/quest/blog/BlogAdminController.java @@ -0,0 +1,332 @@ +package mx.quest.blog; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; +import mx.quest.runway.spi.model.SiteView; +import mx.quest.runway.spi.service.ConsoleScreen; +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.RequestContext; +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.util.MultiValueMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.server.ResponseStatusException; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +/** + * The blog's tenant-console authoring screens ({@code /__admin/blog}): list, create, edit, publish/unpublish + * and delete entries — a plugin-owned console surface rendered inside the operator shell through + * {@link ConsoleScreen} (the kernel fills the shell's model; the {@code contentTemplate} resolves through this + * plugin's own {@code __plugin__/blog/…} namespace). + * + *

Four platform disciplines enforced here: + *

    + *
  • tenancy is always the bound one ({@link RequestContext#site()}), never a path/param id;
  • + *
  • every mutation is announced through {@link ContentChanges#changed} — the single freshness trigger + * for the plugin's own URL index (delivered back to {@link BlogContentSource} as a SOURCE listener) and for + * every kernel consumer (routing, sitemap, llms.txt, search), relayed cluster-wide by the host;
  • + *
  • every state change is a CSRF-checked {@code POST} (the console chain checks the token; the + * templates put it in every form) — the {@code GET}s only render;
  • + *
  • the reverse advisory: the edit screen asks the kernel's + * {@link ContentCatalogView#pageAt} whether a published page owns any of the entry's URLs — the page would + * win, so the author is warned exactly where they type the slug.
  • + *
+ * + *

Gated by this plugin's own grantable control point ({@code blog|manage}, checked by the kernel's + * {@code AccessCheck}, bean {@code authz}); the per-site settings editor is gated separately by the reserved + * {@code settings} point (host-rendered from the descriptor schema). + */ +@Controller +@ConsoleScreen +public class BlogAdminController { + + private static final Logger log = LoggerFactory.getLogger(BlogAdminController.class); + + private static final String PERMISSION = "@authz.may('blog|manage')"; + + /** Ids the routing table owns — an entry named like an action verb would be uneditable/unreachable. */ + private static final Set RESERVED_IDS = Set.of("create", "new"); + private static final Pattern SAFE_SLUG = Pattern.compile("[a-z0-9][a-z0-9-]{0,98}[a-z0-9]|[a-z0-9]"); + + private final RequestContext request; + private final BlogStore store; + private final BlogContentSource source; + private final ContentCatalogView catalog; + private final ContentChanges changes; + private final Messages messages; + + public BlogAdminController(RequestContext request, BlogStore store, BlogContentSource source, + ContentCatalogView catalog, ContentChanges changes, Messages messages) { + this.request = request; + this.store = store; + this.source = source; + this.catalog = catalog; + this.changes = changes; + this.messages = messages; + } + + private String message(String key, String fallback) { + return messages.console(key, fallback); + } + + /** One list row: the entry plus its resolved public path (under the current prefix settings). */ + public record EntryRow(BlogEntry entry, String publicPath) { + } + + @GetMapping("/__admin/blog") + @PreAuthorize(PERMISSION) + public String list(Model model) { + SiteView site = boundTenancy(); + List rows = new ArrayList<>(); + for (BlogEntry entry : store.list(site.id())) { + rows.add(new EntryRow(entry, source.publicPath(site.id(), entry))); + } + model.addAttribute("rows", rows); + model.addAttribute("blogEnabled", source.settings(site.id()).enabled()); + model.addAttribute(ConsoleScreen.PAGE_TITLE_KEY, "blog.admin.title"); + model.addAttribute(ConsoleScreen.CONTENT_TEMPLATE, "__plugin__/blog/admin-list"); + return ConsoleScreen.LAYOUT_VIEW; + } + + @GetMapping("/__admin/blog/new") + @PreAuthorize(PERMISSION) + public String createForm(Model model) { + SiteView site = boundTenancy(); + editorModel(model, site, new BlogEntry("new-entry", Map.of(), Map.of(), List.of(), null, Map.of(), + null, false, null, null, null), Map.of(), true); + return ConsoleScreen.LAYOUT_VIEW; + } + + @PostMapping("/__admin/blog/create") + @PreAuthorize(PERMISSION) + public String create(@RequestParam("id") String id, @RequestParam MultiValueMap params, + Model model, RedirectAttributes redirect) { + SiteView site = boundTenancy(); + String entryId = id == null ? "" : id.trim().toLowerCase(Locale.ROOT); + String error = null; + try { + BlogStore.requireSafeId(entryId); + if (RESERVED_IDS.contains(entryId)) { + error = message("blog.error.reservedId", "That id is reserved — pick another."); + } else if (store.read(site.id(), entryId).isPresent()) { + error = message("blog.error.duplicate", "An entry with that id already exists."); + } else { + validateForm(site, params); + save(site, entryId, params); + redirect.addFlashAttribute("flash", + message("blog.flash.created", "Entry created.")); + return "redirect:/__admin/blog/" + entryId + "/edit"; + } + } catch (IllegalArgumentException invalid) { + error = message("blog.error.invalid", "Some fields are invalid: ") + invalid.getMessage(); + } catch (IOException io) { + log.warn("creating blog entry {}/{} failed", site.id(), entryId, io); + error = message("blog.error.ioError", "The entry could not be written."); + } + // NEVER blank the form on failure: re-render the editor with exactly what the author typed. + editorModel(model, site, parseEntry(site, entryId.isEmpty() ? "new-entry" : entryId, params), + parseBodies(site, params), true); + model.addAttribute("error", error); + return ConsoleScreen.LAYOUT_VIEW; + } + + @GetMapping("/__admin/blog/{id}/edit") + @PreAuthorize(PERMISSION) + public String editForm(@PathVariable("id") String id, Model model) { + SiteView site = boundTenancy(); + BlogEntry entry = store.read(site.id(), id) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "no such entry")); + Map bodies = new LinkedHashMap<>(); + for (Locale locale : site.locales()) { + bodies.put(locale.getLanguage(), store.readBody(site.id(), id, locale.getLanguage())); + } + editorModel(model, site, entry, bodies, false); + return ConsoleScreen.LAYOUT_VIEW; + } + + @PostMapping("/__admin/blog/{id}") + @PreAuthorize(PERMISSION) + public String update(@PathVariable("id") String id, @RequestParam MultiValueMap params, + RedirectAttributes redirect) { + SiteView site = boundTenancy(); + store.read(site.id(), id) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "no such entry")); + try { + validateForm(site, params); + save(site, id, params); + redirect.addFlashAttribute("flash", message("blog.flash.saved", "Saved.")); + } catch (IllegalArgumentException invalid) { + redirect.addFlashAttribute("error", + message("blog.error.invalid", "Some fields are invalid: ") + invalid.getMessage()); + } catch (IOException io) { + log.warn("saving blog entry {}/{} failed", site.id(), id, io); + redirect.addFlashAttribute("error", message("blog.error.ioError", "The entry could not be written.")); + } + return "redirect:/__admin/blog/" + id + "/edit"; + } + + @PostMapping("/__admin/blog/{id}/publish") + @PreAuthorize(PERMISSION) + public String togglePublished(@PathVariable("id") String id, RedirectAttributes redirect) { + SiteView site = boundTenancy(); + BlogEntry entry = store.read(site.id(), id) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "no such entry")); + try { + // Carry author and publishedOn through: toggling visibility is not an editorial change, and this + // rebuild lists every field explicitly, so anything forgotten here is silently erased on publish. + store.save(site.id(), new BlogEntry(entry.id(), entry.title(), entry.description(), + entry.locales(), entry.slug(), entry.localizedSlugs(), entry.customPath(), + !entry.published(), entry.publishedOn(), entry.author(), null), null); + changes.changed(site.id(), BlogContentSource.KEY, id); + redirect.addFlashAttribute("flash", entry.published() + ? message("blog.flash.unpublished", "Entry unpublished.") + : message("blog.flash.published", "Entry published.")); + } catch (IOException io) { + log.warn("toggling blog entry {}/{} failed", site.id(), id, io); + redirect.addFlashAttribute("error", message("blog.error.ioError", "The entry could not be written.")); + } + return "redirect:/__admin/blog"; + } + + @PostMapping("/__admin/blog/{id}/delete") + @PreAuthorize(PERMISSION) + public String delete(@PathVariable("id") String id, RedirectAttributes redirect) { + SiteView site = boundTenancy(); + try { + store.delete(site.id(), id); + changes.changed(site.id(), BlogContentSource.KEY, id); + redirect.addFlashAttribute("flash", message("blog.flash.deleted", "Entry deleted.")); + } catch (IOException io) { + log.warn("deleting blog entry {}/{} failed", site.id(), id, io); + redirect.addFlashAttribute("error", message("blog.error.ioError", "The entry could not be deleted.")); + } + return "redirect:/__admin/blog"; + } + + // --- shared ------------------------------------------------------------------------------------------------ + + /** Reads the editor form into the entry + bodies, persists, and announces the change. */ + private void save(SiteView site, String entryId, MultiValueMap params) throws IOException { + store.save(site.id(), parseEntry(site, entryId, params), parseBodies(site, params)); + changes.changed(site.id(), BlogContentSource.KEY, entryId); + } + + /** The editor form → an entry (the default language's slug field doubles as the base slug). */ + private static BlogEntry parseEntry(SiteView site, String entryId, MultiValueMap params) { + Map title = perLang(site, params, "title_"); + Map description = perLang(site, params, "description_"); + Map localizedSlugs = perLang(site, params, "slug_"); + List locales = new ArrayList<>(); + for (Locale locale : site.locales()) { + if (params.containsKey("locales_" + locale.getLanguage())) { + locales.add(locale.getLanguage()); + } + } + String defaultLang = site.defaultLocale().getLanguage(); + String slug = localizedSlugs.remove(defaultLang); + return new BlogEntry(entryId, title, description, locales, slug, localizedSlugs, + first(params, "customPath"), params.containsKey("published"), first(params, "publishedOn"), + first(params, "author"), null); + } + + private static Map parseBodies(SiteView site, MultiValueMap params) { + Map bodies = new LinkedHashMap<>(); + for (Locale locale : site.locales()) { + String lang = locale.getLanguage(); + bodies.put(lang, first(params, "body_" + lang)); + } + return bodies; + } + + /** + * Rejects URL inputs the kernel's fail-closed backstop would otherwise DISCARD SILENTLY (the console + * would flash "saved" while the entry quietly vanished from routing and listings): slugs must match the + * slug grammar; a custom path must be absolute, free of the index separator, and a path the kernel would + * serve content at ({@link ContentCatalogView#servablePath}: safe, not reserved, not an endpoint route). + */ + private void validateForm(SiteView site, MultiValueMap params) { + for (Locale locale : site.locales()) { + String slug = first(params, "slug_" + locale.getLanguage()); + if (slug != null && !slug.isBlank() && !SAFE_SLUG.matcher(slug.trim()).matches()) { + throw new IllegalArgumentException("slug (" + locale.getLanguage() + ")"); + } + } + String customPath = first(params, "customPath"); + if (customPath != null && !customPath.isBlank()) { + String p = customPath.trim(); + if (!p.startsWith("/") || p.contains("|") || p.contains(":") + || !catalog.servablePath(site.id(), p)) { + throw new IllegalArgumentException("customPath"); + } + } + } + + /** Populates the editor model, including the reverse advisory (which pages own this entry's URLs). */ + private void editorModel(Model model, SiteView site, BlogEntry entry, Map bodies, + boolean creating) { + List shadowedBy = new ArrayList<>(); + if (!creating) { + for (Locale locale : site.locales()) { + String lang = locale.getLanguage(); + // The REAL per-language URL (localized slug when set) — mirrors routing's own semantics. + String path = source.publicPath(site.id(), entry, lang); + catalog.pageAt(site.id(), path, locale) + .ifPresent(slug -> shadowedBy.add(slug + " (" + lang + ")")); + } + } + // Thymeleaf trap: a literal containing TWO '__' sequences inside a th.xml expression trips Thymeleaf's + // __…__ preprocessing — so the form action (two '/__admin' literals in a ternary) is computed HERE and + // passed as a plain model value the template reads with one ${formAction}. + model.addAttribute("formAction", creating ? "/__admin/blog/create" : "/__admin/blog/" + entry.id()); + model.addAttribute("entry", entry); + model.addAttribute("bodies", bodies); + model.addAttribute("creating", creating); + model.addAttribute("shadowedBy", shadowedBy); + model.addAttribute("siteLocaleTags", + site.locales().stream().map(Locale::getLanguage).toList()); + model.addAttribute("defaultLocaleTag", site.defaultLocale().getLanguage()); + model.addAttribute(ConsoleScreen.PAGE_TITLE_KEY, "blog.admin.title"); + model.addAttribute(ConsoleScreen.CONTENT_TEMPLATE, "__plugin__/blog/admin-edit"); + } + + private static Map perLang(SiteView site, MultiValueMap params, String prefix) { + Map values = new LinkedHashMap<>(); + for (Locale locale : site.locales()) { + String lang = locale.getLanguage(); + String value = first(params, prefix + lang); + if (value != null && !value.isBlank()) { + values.put(lang, value.trim()); + } + } + return values; + } + + private static String first(MultiValueMap params, String name) { + List values = params.get(name); + return (values == null || values.isEmpty()) ? null : values.get(0); + } + + /** + * The site this console request is bound to. Empty on the application console (there is no tenancy there) — + * a {@code 400}. + */ + private SiteView boundTenancy() { + return request.site() + .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no bound tenancy")); + } +} diff --git a/plugins/blog/src/main/java/mx/quest/blog/BlogConfig.java b/plugins/blog/src/main/java/mx/quest/blog/BlogConfig.java new file mode 100644 index 0000000..3b7ecca --- /dev/null +++ b/plugins/blog/src/main/java/mx/quest/blog/BlogConfig.java @@ -0,0 +1,50 @@ +package mx.quest.blog; + +import mx.quest.runway.spi.ContentSource; +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.SiteEventListener; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * The blog plugin's Spring wiring — the {@code mainClass} the host registers before context refresh. Beans are wired + * EXPLICITLY (never {@code @ComponentScan}), and every collaborator is a Runway SPI service the kernel provides: + *

    + *
  • {@link PluginSettings}, {@link PluginSiteFiles} and {@link ContentChanges} are plugin-scoped — the + * kernel binds each to this plugin because the injecting class ({@code BlogConfig}) comes from this plugin's + * jar, so they reach only {@code sites//plugins/blog.yml}, {@code sites//plugins/blog/} and this + * plugin's own content source;
  • + *
  • {@link ContentCatalogView}, {@link RequestContext} and {@link Messages} are kernel singletons.
  • + *
+ * The {@link BlogContentSource} bean is collected twice by type: as a {@link ContentSource} (routing, sitemap and + * llms.txt, URL maps and search light up with zero further wiring) and as a {@link SiteEventListener} (its index + * invalidation). The controller carries {@code @ConsoleScreen}, so the kernel renders it inside the operator shell. + * Every bean name starts with the plugin id ({@code blog…}) — the kernel's bean-name rule. + */ +@Configuration(proxyBeanMethods = false) +public class BlogConfig { + + @Bean + public BlogStore blogStore(PluginSiteFiles files) { + return new BlogStore(files); + } + + @Bean + public BlogContentSource blogContentSource(BlogStore blogStore, PluginSettings settings, + ContentCatalogView catalog) { + return new BlogContentSource(blogStore, settings, catalog); + } + + @Bean + public BlogAdminController blogAdminController(RequestContext request, BlogStore blogStore, + BlogContentSource blogContentSource, + ContentCatalogView catalog, ContentChanges changes, + Messages messages) { + return new BlogAdminController(request, blogStore, blogContentSource, catalog, changes, messages); + } +} diff --git a/plugins/blog/src/main/java/mx/quest/blog/BlogContentSource.java b/plugins/blog/src/main/java/mx/quest/blog/BlogContentSource.java new file mode 100644 index 0000000..32fde53 --- /dev/null +++ b/plugins/blog/src/main/java/mx/quest/blog/BlogContentSource.java @@ -0,0 +1,309 @@ +package mx.quest.blog; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneOffset; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +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.SettingsChange; +import mx.quest.runway.spi.model.SiteLifecycleEvent; +import mx.quest.runway.spi.model.SiteView; +import mx.quest.runway.spi.service.ContentCatalogView; +import mx.quest.runway.spi.service.PluginSettings; +import mx.quest.runway.spi.service.SiteEventListener; +import org.commonmark.parser.Parser; +import org.commonmark.renderer.html.HtmlRenderer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The blog as a kernel {@link ContentSource}: entries become first-class virtual pages — routed through the + * full locale-dispatch ladder, rendered in the tenant's master chrome around this plugin's own body template, + * listed in sitemap.xml/llms.txt with {@code hreflang} + {@code }, indexed by search, and linkable as + * {@code ${urls['blog:']}} — all host-provided; this class only answers the contract questions. + * + *

The contract, honored

+ *
    + *
  • {@link #enumerate}: published entries only, metadata-only ({@link BlogStore#list} reads + * {@code entry.yml} files, never a body), each with {@code updatedAt} from file times, cached until an + * announced change: a console save moves the render ETag with no explicit bump; a body edited on disk + * is served at once but under the OLD ETag until a site reload (docs/BLOG-PLUGIN.md §3).
  • + *
  • {@link #resolve}: an O(1) probe of a per-site {@code path|lang → id} index (printable {@code |}), + * rebuilt lazily after any invalidation — required because {@code content.arbitrary-paths} makes this + * source run on every routing miss of an enabled site.
  • + *
  • {@link #body}: Markdown → HTML via the bundled commonmark, fetched only for an actual 200 render. + * Entry Markdown is operator-authored, first-party trusted content (raw HTML passes through, exactly as + * a page author may write markup).
  • + *
  • {@link #indexableText}: the same rendered HTML, for search.
  • + *
+ * + *

Index invalidation: a SOURCE-phase {@link SiteEventListener}

+ * The console announces every mutation through {@code ContentChanges.changed}; the kernel delivers it back here as + * a {@code CONTENT} {@link CatalogChange} for this source's key, and this class drops the site's index. A site + * lifecycle event drops it too (a backup restore replaces the entry files wholesale), and so does a save of + * this plugin's own settings (a prefix change re-keys every URL). Running in the {@link Phase#SOURCE SOURCE} phase + * is what keeps consumers honest: the kernel delivers every SOURCE listener first, evicts its content listing once + * more, and only then lets sitemap and search consumers re-read — so none of them can rebuild from this source's + * stale index. With clustering ON, the kernel relays the change to every node and delivers it there too + * ({@code local == false}), so every node's index converges. + */ +public class BlogContentSource implements ContentSource, SiteEventListener { + + public static final String KEY = "blog"; + + private static final Logger log = LoggerFactory.getLogger(BlogContentSource.class); + + private final BlogStore store; + private final PluginSettings settings; + private final ContentCatalogView catalog; + private final Parser markdown = Parser.builder().build(); + private final HtmlRenderer html = HtmlRenderer.builder().build(); + + /** Per-site URL index: {@code path|lang → entryId}; dropped on any content/config/site change. */ + private final ConcurrentMap> index = new ConcurrentHashMap<>(); + /** Per-site enumerated refs — the metadata cache behind {@link #enumerate}, dropped by the SAME events, so + * the per-render urlMap and per-request sitemap don't re-read the entries tree every time. */ + private final ConcurrentMap> refs = new ConcurrentHashMap<>(); + + public BlogContentSource(BlogStore store, PluginSettings settings, ContentCatalogView catalog) { + this.store = store; + this.settings = settings; + this.catalog = catalog; + } + + @Override + public String key() { + return KEY; + } + + @Override + public Capabilities capabilities() { + // Custom paths escape the prefix; indexable-text opts this source into the search integration. + return Capabilities.of(CAP_ARBITRARY_PATHS, CAP_INDEXABLE_TEXT); + } + + /** The site's effective settings — the one place the source and the console read them. */ + public BlogSettings settings(String siteId) { + return BlogSettings.of(settings, catalog, siteId); + } + + /** + * The entry's indexable material for {@code locale}: the Markdown body rendered to HTML — the SAME + * transform the {@link #body} render uses. Engines strip HTML markup (they were built for page + * HTML bodies), so handing them the rendered HTML yields clean prose in the index and in result snippets; + * handing them the raw Markdown would leak {@code ## heading}, {@code **bold**} and {@code [text](url)} + * link syntax straight into the terms and the visible snippet. Empty when the entry has no body for this + * locale. + */ + @Override + public String indexableText(SiteView site, String id, Locale locale) { + String source = store.readBody(site.id(), id, locale.getLanguage()); + return source.isEmpty() ? "" : html.render(markdown.parse(source)); + } + + @Override + public List enumerate(SiteView site) { + BlogSettings current = settings(site.id()); + if (!current.enabled()) { + return List.of(); + } + return refs.computeIfAbsent(site.id(), siteId -> { + List out = new ArrayList<>(); + for (BlogEntry entry : store.list(siteId)) { + if (entry.published()) { + out.add(toRef(entry, current)); + } + } + return List.copyOf(out); + }); + } + + @Override + public Optional resolve(SiteView site, String path, Locale locale) { + String id = index.computeIfAbsent(site.id(), sid -> buildIndex(site)) + .get(path + '|' + locale.getLanguage()); + if (id == null) { + return Optional.empty(); + } + // Answer from the SAME cached refs the index was built from (one settings read, no torn view). + for (ContentRef ref : enumerate(site)) { + if (ref.id().equals(id)) { + return Optional.of(ref); + } + } + return Optional.empty(); + } + + @Override + public ContentBody body(SiteView site, String id, Locale locale) { + String source = store.readBody(site.id(), id, locale.getLanguage()); + if (source.isBlank()) { + return ContentBody.empty(); + } + // Editorial metadata the body template may render. Absent keys are simply not put, so a template can + // test for presence — an entry with no byline must render no byline, not an empty one. + Map attributes = new LinkedHashMap<>(); + store.read(site.id(), id).ifPresent(entry -> { + if (entry.publishedOn() != null) { + attributes.put("publishedOn", entry.publishedOn()); + } + if (entry.author() != null) { + attributes.put("author", entry.author()); + } + }); + return new ContentBody(html.render(markdown.parse(source)), attributes); + } + + // --- invalidation (SiteEventListener, SOURCE phase) -------------------------------------------------------- + + /** {@link Phase#SOURCE}: this source's own index must be dropped before any consumer re-reads the listing. */ + @Override + public Phase phase() { + return Phase.SOURCE; + } + + /** Any lifecycle event — including a backup restore, which replaced the entry files wholesale. */ + @Override + public void onSiteLifecycle(SiteLifecycleEvent event) { + drop(event.siteId()); + } + + /** This plugin's own settings were saved: a prefix or template change re-keys every URL and every ref. */ + @Override + public void onSettingsChanged(SettingsChange change) { + drop(change.siteId()); + } + + /** This source's own content changed (announced by the console, on this node or a peer). */ + @Override + public void onCatalogChanged(CatalogChange change) { + if (change.cause() == CatalogChange.Cause.CONTENT && KEY.equals(change.sourceKey())) { + drop(change.siteId()); + } + } + + private void drop(String siteId) { + index.remove(siteId); + refs.remove(siteId); + } + + // --- mapping ----------------------------------------------------------------------------------------------- + + /** Projects an entry onto the content noun under the site's current prefix settings. */ + private ContentRef toRef(BlogEntry entry, BlogSettings current) { + String defaultPath = entry.customPath() != null ? entry.customPath() + : current.pathFor(entry.effectiveSlug()); + Map localizedPaths = new LinkedHashMap<>(); + entry.localizedSlugs().forEach((lang, slug) -> + localizedPaths.put(lang, current.pathFor(slug))); + List locales = entry.locales().stream().map(Locale::forLanguageTag).toList(); + return new ContentRef(entry.id(), defaultPath, localizedPaths, locales, entry.title(), + entry.description(), null, current.bodyTemplate(), entry.published(), entry.updatedAt(), + false, null, null, Map.of(), entry.author(), publishedAt(entry)); + } + + /** + * The entry's own {@code publishedOn} as an instant, for {@link ContentRef#publishedAt()} — so each post + * carries ITS OWN publication date across the SPI boundary. + * + *

This is what makes per-post dates truthful. Without it, the discoverability plugin would have to take + * {@code datePublished} from the per-site {@code content.schema} block, which matches by path prefix — so ONE + * {@code /blog/*} entry would cover every post. A site's only honest options would be to emit no dates at all, + * or to assert a single date identically on every post: a statement false of nearly every page carrying it, + * and exactly the kind of untrue markup structured-data policy prohibits. + * + *

Interpreted at midnight UTC on the stated day, matching how the kernel's page editor parses its + * own date field, so a blog entry and a page dated the same day produce the same instant. + * + *

The entry's {@code author} travels the same way, so a post is attributed to whoever + * actually wrote it rather than to one name shared by every post on the site. + * + *

An unparseable value yields {@code null} — no date. {@code publishedOn} is free-form display text on + * the entry, so it can legitimately hold something that is not a date; asserting a wrong + * {@code datePublished} would be worse than asserting none, because a consumer is told to trust it. + */ + private static Instant publishedAt(BlogEntry entry) { + String raw = entry.publishedOn(); + if (raw == null || raw.isBlank()) { + return null; + } + try { + return LocalDate.parse(raw.trim()).atStartOfDay(ZoneOffset.UTC).toInstant(); + } catch (DateTimeParseException e) { + return null; + } + } + + /** + * One pass over the published refs → {@code path|lang → id} for O(1) miss-time resolution. Keys the FULL + * union of the site's locales plus the default (parity with the SPI's default {@code resolve}, which + * matches {@code pathFor(L)} for any lookup locale), with a locale's OWN localized slug taking precedence + * over another entry's fallback claim. Two entries claiming one (path, lang) is a same-source collision + * the kernel cannot see — logged loudly here; the deterministic winner is the explicit/localized claim, + * else first-listed. + */ + private Map buildIndex(SiteView site) { + Map paths = new HashMap<>(); + Locale siteDefault = site.defaultLocale(); + LinkedHashSet lookupLocales = new LinkedHashSet<>(); + lookupLocales.add(siteDefault); + lookupLocales.addAll(site.locales()); + for (ContentRef ref : enumerate(site)) { + for (Locale locale : lookupLocales) { + String key = ref.pathFor(locale) + '|' + locale.getLanguage(); + boolean explicit = ref.localizedPaths().containsKey(locale.getLanguage()) + || ref.hasLocale(locale, siteDefault); + String prior = explicit ? paths.put(key, ref.id()) : paths.putIfAbsent(key, ref.id()); + if (prior != null && !prior.equals(ref.id())) { + log.warn("blog entries '{}' and '{}' (site '{}') both claim '{}' — '{}' wins; give one a " + + "different slug", prior, ref.id(), site.id(), key, + explicit ? ref.id() : prior); + } + } + } + return Map.copyOf(paths); + } + + /** For the console: the entry's public path in the site's default URL space (list-screen links). */ + public String publicPath(String siteId, BlogEntry entry) { + return publicPath(siteId, entry, null); + } + + /** + * The entry's public path for one language ({@code null} = the default URL space): the localized slug when + * that language has one, else the default path — the exact semantics {@code toRef}/routing use, so the + * console's reverse advisory checks the REAL per-language URLs. + */ + public String publicPath(String siteId, BlogEntry entry, String lang) { + BlogSettings current = settings(siteId); + if (lang != null && entry.localizedSlugs().containsKey(lang)) { + return current.pathFor(entry.localizedSlugs().get(lang)); + } + return entry.customPath() != null ? entry.customPath() + : current.pathFor(entry.effectiveSlug()); + } + + /** Test hook: the index currently cached for a site (null = not built). */ + Map cachedIndex(String siteId) { + return index.get(siteId); + } + + /** Test hook: the refs currently cached for a site (null = not built). */ + List cachedRefs(String siteId) { + return refs.get(siteId); + } +} diff --git a/plugins/blog/src/main/java/mx/quest/blog/BlogEntry.java b/plugins/blog/src/main/java/mx/quest/blog/BlogEntry.java new file mode 100644 index 0000000..8e44e99 --- /dev/null +++ b/plugins/blog/src/main/java/mx/quest/blog/BlogEntry.java @@ -0,0 +1,97 @@ +package mx.quest.blog; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * One blog entry's metadata — the {@code entry.yml} document under + * {@code sites//plugins/blog/entries//}. Bodies live beside it as {@code body-.md} files + * (one per language), so enumerating entries never reads a body — the ContentSource contract's + * metadata/body split, made trivially honest by the file layout. + * + *

URLs: the entry serves at {@code /} (the per-tenant {@code prefix} setting), with optional + * per-language slug overrides ({@code localizedSlugs}) and an optional custom absolute path + * ({@code customPath}, e.g. {@code /announcing-v2}) that replaces the prefixed default-locale URL entirely + * (the reason this plugin declares {@code content.arbitrary-paths}). + * + * @param id the entry's stable identity — its folder name (never part of the YAML; re-applied + * from the folder on read, like a page's slug) + * @param title per-language titles ({@code lang → text}) + * @param description per-language descriptions + * @param locales the language codes this entry is published in (empty ⇒ site default only) + * @param slug the URL slug under the blog prefix ({@code null} ⇒ the id) + * @param localizedSlugs per-language slug overrides ({@code lang → slug}) + * @param customPath an absolute path override for the default locale ({@code /…}), or {@code null} + * @param published whether the entry is publicly visible + * @param publishedOn the display publication date (ISO {@code yyyy-MM-dd}), or {@code null} + * @param author display name credited for this entry, or {@code null} when unattributed. Free text + * on purpose — a real identity model (accounts, profiles, affiliations) is a much + * larger design, and blocking bylines on it would leave every entry unattributable + * meanwhile. Matches the kernel's page-level author so the two cannot drift + * @param updatedAt newest mtime of the entry's files — derived on read, never serialized; drives the + * sitemap {@code } AND the render ETag (re-read only after an announced change) + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public record BlogEntry(String id, Map title, Map description, + List locales, String slug, Map localizedSlugs, + String customPath, boolean published, String publishedOn, String author, + @JsonIgnore Instant updatedAt) { + + public BlogEntry { + title = normalize(title); + description = normalize(description); + locales = (locales == null) ? List.of() : List.copyOf(locales); + localizedSlugs = normalize(localizedSlugs); + slug = blankToNull(slug); + customPath = blankToNull(customPath); + publishedOn = blankToNull(publishedOn); + // Blank == unattributed: the editor posts "" for an untouched field, and an empty byline must not + // serialize into entry.yml or render as an empty author element. + author = blankToNull(author); + } + + /** This entry with its stable id applied (the folder name — never stored inside the YAML). */ + public BlogEntry withId(String id) { + return new BlogEntry(id, title, description, locales, slug, localizedSlugs, customPath, published, + publishedOn, author, updatedAt); + } + + /** This entry with the derived {@code updatedAt} applied (from the entry files' mtimes). */ + public BlogEntry withUpdatedAt(Instant updatedAt) { + return new BlogEntry(id, title, description, locales, slug, localizedSlugs, customPath, published, + publishedOn, author, updatedAt); + } + + /** The form serialized to {@code entry.yml}: no id (the folder carries it), no derived fields. */ + public BlogEntry forStorage() { + return new BlogEntry(null, title, description, locales, slug, localizedSlugs, customPath, published, + publishedOn, author, null); + } + + /** The effective URL slug under the blog prefix: the explicit {@link #slug}, else the id. */ + @JsonIgnore + public String effectiveSlug() { + return slug != null ? slug : id; + } + + private static Map normalize(Map raw) { + if (raw == null || raw.isEmpty()) { + return Map.of(); + } + Map clean = new LinkedHashMap<>(); + raw.forEach((k, v) -> { + if (k != null && !k.isBlank() && v != null && !v.isBlank()) { + clean.put(k.trim(), v.trim()); + } + }); + return java.util.Collections.unmodifiableMap(clean); + } + + private static String blankToNull(String value) { + return (value == null || value.isBlank()) ? null : value.trim(); + } +} diff --git a/plugins/blog/src/main/java/mx/quest/blog/BlogSettings.java b/plugins/blog/src/main/java/mx/quest/blog/BlogSettings.java new file mode 100644 index 0000000..ce90e7d --- /dev/null +++ b/plugins/blog/src/main/java/mx/quest/blog/BlogSettings.java @@ -0,0 +1,75 @@ +package mx.quest.blog; + +import mx.quest.runway.spi.model.SettingsView; +import mx.quest.runway.spi.service.ContentCatalogView; +import mx.quest.runway.spi.service.PluginSettings; + +/** + * The blog's effective per-site settings — typed reads over {@link PluginSettings} (live: a console save is visible + * on the next read; an absent settings file means the descriptor's defaults). Kept as one value object so the + * source, the console and the templates agree on defaults in exactly one place. + * + * @param enabled whether the blog serves at all on this site + * @param prefix the URL prefix entries serve under (normalized: leading {@code /}, no trailing {@code /}) + * @param template the entry body template name within this plugin's own namespace (the operator's pick) + */ +public record BlogSettings(boolean enabled, String prefix, String template) { + + public static final String PLUGIN_ID = "blog"; + + static final String DEFAULT_PREFIX = "/blog"; + static final String DEFAULT_TEMPLATE = "entry-classic"; + static final String MINIMAL_TEMPLATE = "entry-minimal"; + + /** + * The site's effective settings (descriptor defaults: enabled, {@code /blog}, {@code entry-classic}). + * + *

The prefix is checked with {@link ContentCatalogView#servablePath}: an unsafe or reserved prefix + * ({@code /__x}, {@code /app}, {@code /actuator}, a path with {@code |} or {@code ..}) would make every entry + * path fail the kernel's fail-closed re-filter and silently vanish from routing and listings, so it falls back + * to {@code /blog} instead. The question asked is "would the kernel serve an entry under this prefix?", so the + * probe is a child path of the prefix — that is where entries live. + * + * @param settings this plugin's per-site settings + * @param catalog the kernel's content surface (for its path rule; no content source is consulted) + * @param siteId the site + * @return the effective settings (never {@code null}) + */ + public static BlogSettings of(PluginSettings settings, ContentCatalogView catalog, String siteId) { + SettingsView view = settings.site(siteId); + boolean enabled = view.bool("enabled", true); + String prefix = normalizePrefix(view.string("prefix", DEFAULT_PREFIX)); + // Fail closed on the template name: it becomes part of a __plugin__/blog/ template lookup. + String template = MINIMAL_TEMPLATE.equals(view.string("template", DEFAULT_TEMPLATE)) + ? MINIMAL_TEMPLATE : DEFAULT_TEMPLATE; + if (!catalog.servablePath(siteId, join(prefix, "x"))) { + prefix = DEFAULT_PREFIX; + } + return new BlogSettings(enabled, prefix, template); + } + + /** The full logical body-template name the kernel resolves and namespace-validates. */ + public String bodyTemplate() { + return "__plugin__/" + PLUGIN_ID + "/" + template; + } + + /** An entry's public path under this prefix — joined without doubling when the prefix is the root. */ + public String pathFor(String slug) { + return join(prefix, slug); + } + + private static String join(String prefix, String slug) { + return "/".equals(prefix) ? "/" + slug : prefix + "/" + slug; + } + + private static String normalizePrefix(String raw) { + String p = raw.trim(); + if (!p.startsWith("/")) { + p = "/" + p; + } + while (p.endsWith("/") && p.length() > 1) { + p = p.substring(0, p.length() - 1); + } + return p; + } +} diff --git a/plugins/blog/src/main/java/mx/quest/blog/BlogStore.java b/plugins/blog/src/main/java/mx/quest/blog/BlogStore.java new file mode 100644 index 0000000..35c682a --- /dev/null +++ b/plugins/blog/src/main/java/mx/quest/blog/BlogStore.java @@ -0,0 +1,261 @@ +package mx.quest.blog; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.regex.Pattern; +import mx.quest.runway.spi.model.FileEntry; +import mx.quest.runway.spi.service.PluginSiteFiles; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.StreamWriteFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.dataformat.yaml.YAMLMapper; + +/** + * The blog's per-site file store, over the kernel's {@link PluginSiteFiles} (this plugin's own subtree, + * {@code sites//plugins/blog/}): {@code entries//entry.yml} (metadata) + + * {@code entries//body-.md} (one Markdown body per language). The layout has not changed across releases, + * so existing entries load unchanged. Everything lives in the site's own folder, so a full backup carries the whole + * blog with no {@code BackupParticipant}, and the kernel confines every path to the subtree (symbolic links + * included) — the store cannot reach another plugin's data or another site. + * + *

Metadata/body split on disk is what makes the ContentSource contract trivially honest: {@link #list} + * reads only {@code entry.yml} files (plus file times for {@code updatedAt}); {@link #readBody} is called only when a + * body is actually rendered or indexed. + * + *

Ids and language codes are validated against a strict grammar before ever forming a path — an id is a folder + * name, a language code a file-name fragment; neither may traverse (the kernel would refuse it anyway). + * + *

Concurrency. Each file write is atomic (the kernel writes a temporary file and renames it), so a public + * reader — the sitemap, a routing miss — never observes a half-written {@code entry.yml}. Two operators saving the + * same entry at once: the last save wins. + * + *

Freshness. The store announces nothing; the console calls {@code ContentChanges.changed} after every + * mutation. + */ +public class BlogStore { + + private static final Pattern SAFE_ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,98}[a-z0-9]|[a-z0-9]"); + private static final Pattern SAFE_LANG = Pattern.compile("[a-z]{2,8}"); + /** The entries folder, relative to this plugin's per-site subtree. */ + static final String ENTRIES = "entries"; + static final String METADATA = "entry.yml"; + + private static final Logger log = LoggerFactory.getLogger(BlogStore.class); + + /** + * The YAML codec: lenient on read, so a hand-written {@code entry.yml} that omits {@code published:} or + * carries a key this version does not know still loads (it defaults instead of failing) — and writes an entry back + * byte for byte ({@code BlogStoreTest} proves it on the fixture entries). Streams are never auto-closed: the + * caller owns them. + */ + private static final ObjectMapper YAML = YAMLMapper.builder() + .disable(StreamWriteFeature.AUTO_CLOSE_TARGET) + .disable(StreamReadFeature.AUTO_CLOSE_SOURCE) + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) + .build(); + + private final PluginSiteFiles files; + + public BlogStore(PluginSiteFiles files) { + this.files = files; + } + + /** + * Every entry of the site (published and not), newest publication date first, with {@code updatedAt} derived + * from file times. One unreadable entry is skipped with a WARN and never blanks the others. + * + * @throws UncheckedIOException if the entries folder itself cannot be listed + */ + public List list(String siteId) { + List dirs; + try { + dirs = files.list(siteId, ENTRIES); + } catch (IOException ex) { + throw new UncheckedIOException("listing blog entries of " + siteId, ex); + } + List out = new ArrayList<>(); + for (FileEntry dir : dirs) { + String id = dir.name(); + if (!dir.directory() || !SAFE_ID.matcher(id).matches()) { + continue; + } + // Per-ENTRY containment: one corrupt/hand-mangled entry.yml must never blank the whole blog + // (the corpus-level backstop upstream would otherwise drop the entire source). + try { + read(siteId, id).ifPresent(out::add); + } catch (RuntimeException ex) { + log.warn("skipping unreadable blog entry {}/{}: {}", siteId, id, ex.toString()); + } + } + out.sort((a, b) -> { + // Newest first for the console: by publishedOn (desc, nulls last), then id for stability. + String pa = a.publishedOn() == null ? "" : a.publishedOn(); + String pb = b.publishedOn() == null ? "" : b.publishedOn(); + int byDate = pb.compareTo(pa); + return byDate != 0 ? byDate : a.id().compareTo(b.id()); + }); + return out; + } + + /** + * One entry by id, or empty (also empty for an unsafe id — never a path probe — and for a malformed + * {@code entry.yml}, which is logged). + * + * @throws UncheckedIOException if the file exists but cannot be read + */ + public Optional read(String siteId, String entryId) { + if (!SAFE_ID.matcher(entryId).matches()) { + return Optional.empty(); + } + String path = metadataPath(entryId); + Optional text; + try { + text = files.readText(siteId, path); + } catch (IOException ex) { + throw new UncheckedIOException("reading blog entry " + siteId + "/" + entryId, ex); + } + if (text.isEmpty()) { + return Optional.empty(); + } + BlogEntry parsed; + try { + parsed = YAML.readValue(text.get(), BlogEntry.class); + } catch (RuntimeException parseFailure) { + // A malformed file is THIS entry's problem, never the corpus's: absent + a WARN naming the file. + log.warn("unparseable blog entry {}/{} — treated as absent: {}", siteId, path, parseFailure.toString()); + return Optional.empty(); + } + if (parsed == null) { + return Optional.empty(); + } + return Optional.of(parsed.withId(entryId).withUpdatedAt(newestModification(siteId, entryId))); + } + + /** + * Creates or replaces an entry's metadata, and any bodies given ({@code lang → markdown}; a {@code null} body + * map leaves bodies untouched, a blank body deletes that language's file). The caller announces the change + * afterwards — the store never does. + * + * @throws IllegalArgumentException for an unsafe id or language code (nothing is written), or a body over the + * kernel's write cap + * @throws IOException when a write fails (for example, the site folder does not exist) + */ + public void save(String siteId, BlogEntry entry, Map bodies) throws IOException { + requireSafeId(entry.id()); + if (bodies != null) { + bodies.keySet().forEach(BlogStore::requireSafeLang); // validate ALL before writing ANY + } + files.writeText(siteId, metadataPath(entry.id()), YAML.writeValueAsString(entry.forStorage())); + if (bodies != null) { + for (Map.Entry body : bodies.entrySet()) { + String path = bodyPath(entry.id(), body.getKey()); + if (body.getValue() == null || body.getValue().isBlank()) { + files.delete(siteId, path); + } else { + files.writeText(siteId, path, body.getValue()); + } + } + } + } + + /** + * Deletes an entry (its folder and every file in it; symbolic links are removed, never followed). Unknown and + * unsafe ids are a no-op. + */ + public void delete(String siteId, String entryId) throws IOException { + if (!SAFE_ID.matcher(entryId).matches()) { + return; + } + files.deleteTree(siteId, ENTRIES + "/" + entryId); + } + + /** + * The entry's Markdown body for {@code lang}, or {@code ""} when that language has none (or the id or language + * is unsafe). + * + * @throws UncheckedIOException if the body exists but cannot be read (including one over the kernel's cap) + */ + public String readBody(String siteId, String entryId, String lang) { + if (!SAFE_ID.matcher(entryId).matches() || !SAFE_LANG.matcher(lang).matches()) { + return ""; + } + try { + return files.readText(siteId, bodyPath(entryId, lang)).orElse(""); + } catch (IOException ex) { + throw new UncheckedIOException("reading blog body " + siteId + "/" + entryId + "/" + lang, ex); + } + } + + /** The languages that have a body file for {@code entryId}, sorted. */ + public List bodyLangs(String siteId, String entryId) { + if (!SAFE_ID.matcher(entryId).matches()) { + return List.of(); + } + List langs = new ArrayList<>(); + for (FileEntry file : entryFiles(siteId, entryId)) { + String name = file.name(); + if (!file.directory() && name.startsWith("body-") && name.endsWith(".md")) { + langs.add(name.substring("body-".length(), name.length() - ".md".length())); + } + } + langs.sort(String::compareTo); + return langs; + } + + static void requireSafeId(String id) { + if (id == null || !SAFE_ID.matcher(id).matches()) { + throw new IllegalArgumentException("invalid blog entry id: '" + id + "' (lowercase letters, " + + "digits and hyphens; no ':' — the composite blog: identity must stay unambiguous)"); + } + } + + private static String requireSafeLang(String lang) { + if (lang == null || !SAFE_LANG.matcher(lang).matches()) { + throw new IllegalArgumentException("invalid language code: '" + lang + "'"); + } + return lang; + } + + /** + * The newest modification time of the entry's files — {@code updatedAt}, which drives the sitemap + * {@code } and the render {@code ETag} once the source re-lists (after an announced change). + * {@code null} when no time is known. + */ + private Instant newestModification(String siteId, String entryId) { + Instant newest = null; + for (FileEntry file : entryFiles(siteId, entryId)) { + Instant at = file.lastModified(); + if (!file.directory() && !Instant.EPOCH.equals(at) && (newest == null || at.isAfter(newest))) { + newest = at; + } + } + return newest; + } + + private List entryFiles(String siteId, String entryId) { + try { + return files.list(siteId, ENTRIES + "/" + entryId); + } catch (IOException ex) { + // An unreadable folder contributes no file times and no body languages; the entry still lists. + log.debug("listing blog entry {}/{} failed: {}", siteId, entryId, ex.toString()); + return List.of(); + } + } + + private static String metadataPath(String entryId) { + return ENTRIES + "/" + entryId + "/" + METADATA; + } + + private static String bodyPath(String entryId, String lang) { + return ENTRIES + "/" + entryId + "/body-" + requireSafeLang(lang) + ".md"; + } +} diff --git a/plugins/blog/src/test/java/mx/quest/blog/BlogAdminControllerTest.java b/plugins/blog/src/test/java/mx/quest/blog/BlogAdminControllerTest.java new file mode 100644 index 0000000..5bcf2ec --- /dev/null +++ b/plugins/blog/src/test/java/mx/quest/blog/BlogAdminControllerTest.java @@ -0,0 +1,369 @@ +package mx.quest.blog; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import mx.quest.runway.spi.model.CatalogChange; +import mx.quest.runway.spi.model.SiteView; +import mx.quest.runway.spi.service.ConsoleScreen; +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.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ExtendedModelMap; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.server.ResponseStatusException; +import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap; + +/** + * {@link BlogAdminController} over SPI fakes: the form → entry parse (per-language fields, the default-language slug + * as base slug, published checkbox), the {@code ContentChanges} announcement after every mutation (the platform's + * freshness rule — and, delivered back, the source's own index drop), the reverse advisory through + * {@code ContentCatalogView.pageAt}, the bound tenancy through {@code RequestContext}, console messages through + * {@code Messages}, and the console-screen contract (annotation, paths, POST-only mutations, the permission gate). + */ +class BlogAdminControllerTest { + + private static final Locale EN = Locale.ENGLISH; + private static final Locale ES = Locale.of("es"); + + private record Fixture(BlogAdminController controller, BlogStore store, EventDispatch events, + FakeContentCatalog catalog, BlogContentSource source) { + } + + private static Fixture fixture(Path tmp, boolean bound) throws IOException { + Files.createDirectories(tmp.resolve("acme")); + BlogStore store = new BlogStore(new TempDirSiteFiles(tmp, "blog")); + FakeContentCatalog catalog = new FakeContentCatalog().site("acme").route("/sitemap.xml"); + BlogContentSource source = new BlogContentSource(store, new FakePluginSettings(), catalog); + EventDispatch events = new EventDispatch("blog", Set.of(BlogContentSource.KEY)).listener(source); + FakeSiteServices kernel = new FakeSiteServices() + .site(new SiteView("acme", "Acme", EN, List.of(EN, ES), null)) + .message("acme", "blog.flash.created", "Entrada creada."); + if (bound) { + kernel.current("acme"); + } + BlogAdminController controller = new BlogAdminController(kernel, store, source, catalog, events, kernel); + return new Fixture(controller, store, events, catalog, source); + } + + private static Fixture fixture(Path tmp) throws IOException { + return fixture(tmp, true); + } + + private static MultiValueMap form() { + MultiValueMap params = new LinkedMultiValueMap<>(); + params.add("title_en", "My first post"); + params.add("title_es", "Mi primera entrada"); + params.add("description_en", "The very first."); + params.add("slug_en", "first"); // the default language's slug = the base slug + params.add("slug_es", "primera"); + params.add("body_en", "Hello **world**."); + params.add("body_es", "Hola **mundo**."); + params.add("locales_en", "on"); + params.add("locales_es", "on"); + params.add("published", "on"); + params.add("publishedOn", "2026-07-17"); + params.add("author", "Jane Doe"); + return params; + } + + private static List announcedIds(Fixture f) { + List ids = new ArrayList<>(); + for (CatalogChange c : f.events().announced()) { + assertEquals(BlogContentSource.KEY, c.sourceKey(), "always this plugin's own source"); + assertEquals("acme", c.siteId(), "always the bound site"); + ids.add(c.id()); + } + return ids; + } + + @Test + void createParsesTheFormAndAnnouncesTheChange(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp); + RedirectAttributesModelMap redirect = new RedirectAttributesModelMap(); + String view = f.controller().create("First-Post ", form(), new ExtendedModelMap(), redirect); + assertEquals("redirect:/__admin/blog/first-post/edit", view, "the id is trimmed and lower-cased"); + + BlogEntry saved = f.store().read("acme", "first-post").orElseThrow(); + assertEquals("My first post", saved.title().get("en")); + assertEquals("The very first.", saved.description().get("en")); + assertEquals("first", saved.slug(), "the default language's slug field becomes the base slug"); + assertEquals(Map.of("es", "primera"), saved.localizedSlugs()); + assertEquals(List.of("en", "es"), saved.locales()); + assertTrue(saved.published()); + assertEquals("2026-07-17", saved.publishedOn()); + assertEquals("Jane Doe", saved.author()); + assertEquals("Hello **world**.", f.store().readBody("acme", "first-post", "en")); + assertEquals("Hola **mundo**.", f.store().readBody("acme", "first-post", "es")); + + assertEquals(List.of("first-post"), announcedIds(f), "one announcement, after the write"); + assertEquals("Entry created.", redirect.getFlashAttributes().get("flash"), + "console words come from Messages.console (its fallback here)"); + assertTrue(f.events().failures().isEmpty()); + } + + @Test + void theAnnouncementReachesTheSourceSoTheNewEntryRoutesAtOnce(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp); + SiteView site = new SiteView("acme", "Acme", EN, List.of(EN, ES), null); + assertTrue(f.source().resolve(site, "/blog/first", EN).isEmpty(), "builds (and caches) an empty index"); + f.controller().create("first-post", form(), new ExtendedModelMap(), new RedirectAttributesModelMap()); + assertEquals("first-post", f.source().resolve(site, "/blog/first", EN).orElseThrow().id(), + "the source's SOURCE-phase listener dropped its stale index"); + } + + @Test + void anInvalidIdReRendersTheEditorWithTheTypedStateNothingWritten(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp); + ExtendedModelMap model = new ExtendedModelMap(); + String view = f.controller().create("Bad:Id", form(), model, new RedirectAttributesModelMap()); + assertEquals(ConsoleScreen.LAYOUT_VIEW, view, "failure RE-RENDERS the editor — never a blank form"); + assertNotNull(model.getAttribute("error"), "the error message is in the model"); + BlogEntry typed = (BlogEntry) model.getAttribute("entry"); + assertEquals("My first post", typed.title().get("en"), "everything the author typed is preserved"); + assertEquals("__plugin__/blog/admin-edit", model.getAttribute(ConsoleScreen.CONTENT_TEMPLATE)); + assertEquals(Boolean.TRUE, model.getAttribute("creating")); + assertTrue(f.store().list("acme").isEmpty(), "nothing was written"); + assertTrue(f.events().announced().isEmpty(), "nothing was announced"); + } + + @Test + void reservedAndDuplicateIdsAreRejected(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp); + for (String reserved : List.of("create", "new")) { + ExtendedModelMap model = new ExtendedModelMap(); + assertEquals(ConsoleScreen.LAYOUT_VIEW, + f.controller().create(reserved, form(), model, new RedirectAttributesModelMap())); + assertEquals("That id is reserved — pick another.", model.getAttribute("error")); + assertTrue(f.store().read("acme", reserved).isEmpty(), reserved + " would collide with the route table"); + } + f.controller().create("post", form(), new ExtendedModelMap(), new RedirectAttributesModelMap()); + var other = form(); + other.set("title_en", "Another"); + ExtendedModelMap model = new ExtendedModelMap(); + assertEquals(ConsoleScreen.LAYOUT_VIEW, + f.controller().create("post", other, model, new RedirectAttributesModelMap())); + assertEquals("An entry with that id already exists.", model.getAttribute("error")); + assertEquals("My first post", f.store().read("acme", "post").orElseThrow().title().get("en"), + "the existing entry is untouched"); + } + + @Test + void anUnsafeSlugOrCustomPathIsRejectedNotSilentlyDiscarded(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp); + var bad = form(); + bad.set("slug_es", "Bad Slug!"); + ExtendedModelMap model = new ExtendedModelMap(); + assertEquals(ConsoleScreen.LAYOUT_VIEW, f.controller().create("post", bad, model, + new RedirectAttributesModelMap())); + assertTrue(String.valueOf(model.getAttribute("error")).contains("slug (es)")); + assertTrue(f.store().read("acme", "post").isEmpty(), "an invalid slug never persists"); + + // Each of these would be dropped by the kernel's fail-closed re-filter (or is not even a path). + for (String path : List.of("no-leading-slash", "/a|b", "/a:b", "/__admin/x", "/app/x", "/sitemap.xml", + "/x/../y")) { + var badPath = form(); + badPath.set("customPath", path); + ExtendedModelMap m = new ExtendedModelMap(); + assertEquals(ConsoleScreen.LAYOUT_VIEW, + f.controller().create("post2", badPath, m, new RedirectAttributesModelMap()), path); + assertTrue(String.valueOf(m.getAttribute("error")).contains("customPath"), path); + assertTrue(f.store().read("acme", "post2").isEmpty(), path + ": an invalid custom path never persists"); + } + var goodPath = form(); + goodPath.set("customPath", " /announcing-v2 "); + f.controller().create("post3", goodPath, new ExtendedModelMap(), new RedirectAttributesModelMap()); + assertEquals("/announcing-v2", f.store().read("acme", "post3").orElseThrow().customPath()); + assertEquals(List.of("post3"), announcedIds(f), "only the valid save was announced"); + } + + @Test + void theFullLifecycleRoundTripsAndAnnouncesEveryMutation(@TempDir Path tmp) throws IOException { + // create → update (slug change + published checkbox ABSENT = silent unpublish, the intended + // full-state-form UX) → publish-toggle twice (ONLY the flag flips) → delete (folder gone). + Fixture f = fixture(tmp); + f.controller().create("post", form(), new ExtendedModelMap(), new RedirectAttributesModelMap()); + + var update = form(); + update.set("slug_en", "renamed"); + update.remove("published"); + RedirectAttributesModelMap saved = new RedirectAttributesModelMap(); + assertEquals("redirect:/__admin/blog/post/edit", f.controller().update("post", update, saved)); + assertEquals("Saved.", saved.getFlashAttributes().get("flash")); + BlogEntry updated = f.store().read("acme", "post").orElseThrow(); + assertEquals("renamed", updated.slug(), "the slug change persisted"); + assertFalse(updated.published(), "checkbox absent ⇒ unpublished (full-state form semantics)"); + assertEquals("Mi primera entrada", updated.title().get("es"), "other fields intact"); + + RedirectAttributesModelMap toggled = new RedirectAttributesModelMap(); + assertEquals("redirect:/__admin/blog", f.controller().togglePublished("post", toggled)); + assertEquals("Entry published.", toggled.getFlashAttributes().get("flash")); + BlogEntry republished = f.store().read("acme", "post").orElseThrow(); + assertTrue(republished.published(), "toggle flips ONLY the flag"); + assertEquals("renamed", republished.slug(), "the positional rebuild kept every other field"); + assertEquals("2026-07-17", republished.publishedOn()); + RedirectAttributesModelMap untoggled = new RedirectAttributesModelMap(); + f.controller().togglePublished("post", untoggled); + assertEquals("Entry unpublished.", untoggled.getFlashAttributes().get("flash")); + assertFalse(f.store().read("acme", "post").orElseThrow().published()); + + RedirectAttributesModelMap deleted = new RedirectAttributesModelMap(); + assertEquals("redirect:/__admin/blog", f.controller().delete("post", deleted)); + assertEquals("Entry deleted.", deleted.getFlashAttributes().get("flash")); + assertTrue(f.store().read("acme", "post").isEmpty(), "deleted"); + assertEquals(List.of("post", "post", "post", "post", "post"), announcedIds(f), + "create, update, publish, unpublish, delete — each announced"); + } + + @Test + void anInvalidUpdateFlashesTheErrorAndWritesNothing(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp); + f.controller().create("post", form(), new ExtendedModelMap(), new RedirectAttributesModelMap()); + var bad = form(); + bad.set("customPath", "/__nope"); + bad.set("title_en", "Changed"); + RedirectAttributesModelMap redirect = new RedirectAttributesModelMap(); + assertEquals("redirect:/__admin/blog/post/edit", f.controller().update("post", bad, redirect)); + assertTrue(String.valueOf(redirect.getFlashAttributes().get("error")).contains("customPath")); + assertEquals("My first post", f.store().read("acme", "post").orElseThrow().title().get("en")); + assertEquals(1, f.events().announced().size(), "only the create"); + } + + @Test + void unknownEntriesAre404(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp); + assertEquals(404, assertThrows(ResponseStatusException.class, + () -> f.controller().editForm("ghost", new ExtendedModelMap())).getStatusCode().value()); + assertEquals(404, assertThrows(ResponseStatusException.class, + () -> f.controller().update("ghost", form(), new RedirectAttributesModelMap())).getStatusCode().value()); + assertEquals(404, assertThrows(ResponseStatusException.class, + () -> f.controller().togglePublished("ghost", new RedirectAttributesModelMap())) + .getStatusCode().value()); + assertTrue(f.store().read("acme", "ghost").isEmpty(), "an update never creates"); + } + + @Test + void withoutABoundTenancyEveryScreenIs400(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, false); + assertEquals(400, assertThrows(ResponseStatusException.class, + () -> f.controller().list(new ExtendedModelMap())).getStatusCode().value(), + "the application console has no site: RequestContext.site() is empty there"); + assertEquals(400, assertThrows(ResponseStatusException.class, + () -> f.controller().create("x", form(), new ExtendedModelMap(), new RedirectAttributesModelMap())) + .getStatusCode().value()); + assertEquals(400, assertThrows(ResponseStatusException.class, + () -> f.controller().delete("x", new RedirectAttributesModelMap())).getStatusCode().value()); + } + + @Test + void theListModelCarriesRowsPathsAndTheEnabledFlag(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp); + BlogStoreTest.install131(tmp, "acme"); + ExtendedModelMap model = new ExtendedModelMap(); + assertEquals(ConsoleScreen.LAYOUT_VIEW, f.controller().list(model)); + @SuppressWarnings("unchecked") + List rows = (List) model.getAttribute("rows"); + assertEquals(List.of("launch", "no-author", "hello-world", "draft-post"), + rows.stream().map(r -> r.entry().id()).toList(), "every entry, drafts included, newest first"); + assertEquals("/announcing-v2", rows.get(0).publicPath()); + assertEquals("/blog/hello-world", rows.get(2).publicPath()); + assertEquals(Boolean.TRUE, model.getAttribute("blogEnabled")); + assertEquals("__plugin__/blog/admin-list", model.getAttribute(ConsoleScreen.CONTENT_TEMPLATE)); + assertEquals("blog.admin.title", model.getAttribute(ConsoleScreen.PAGE_TITLE_KEY)); + } + + @Test + void theEditorModelCarriesTheReverseAdvisoryWhenAPageOwnsThePath(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp); + f.controller().create("first-post", form(), new ExtendedModelMap(), new RedirectAttributesModelMap()); + f.catalog().page("acme", "/blog/first", EN, "about"); + f.catalog().page("acme", "/blog/first", ES, "wrong-locale-claim"); + f.catalog().page("acme", "/blog/primera", ES, "acerca"); + + ExtendedModelMap model = new ExtendedModelMap(); + assertEquals(ConsoleScreen.LAYOUT_VIEW, f.controller().editForm("first-post", model)); + assertEquals(List.of("about (en)", "acerca (es)"), model.getAttribute("shadowedBy"), + "each language's REAL URL is checked in that language's URL space"); + assertEquals("__plugin__/blog/admin-edit", model.getAttribute(ConsoleScreen.CONTENT_TEMPLATE)); + assertEquals("/__admin/blog/first-post", model.getAttribute("formAction")); + assertEquals(List.of("en", "es"), model.getAttribute("siteLocaleTags")); + assertEquals("en", model.getAttribute("defaultLocaleTag")); + @SuppressWarnings("unchecked") + Map bodies = (Map) model.getAttribute("bodies"); + assertEquals(Map.of("en", "Hello **world**.", "es", "Hola **mundo**."), bodies); + + ExtendedModelMap creating = new ExtendedModelMap(); + f.controller().createForm(creating); + assertEquals(List.of(), creating.getAttribute("shadowedBy"), "no advisory before the entry exists"); + assertEquals("/__admin/blog/create", creating.getAttribute("formAction")); + } + + /** Toggling publish/unpublish must not erase the byline (the positional rebuild is a known-recurring hazard). */ + @Test + void togglingPublishPreservesTheAuthor(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp); + f.store().save("acme", new BlogEntry("post", Map.of("en", "Post"), Map.of(), List.of("en"), + null, Map.of(), null, true, "2026-03-04", "Jane Doe", null), Map.of("en", "# Hi")); + f.controller().togglePublished("post", new RedirectAttributesModelMap()); + BlogEntry hidden = f.store().read("acme", "post").orElseThrow(); + assertFalse(hidden.published(), "precondition: the toggle actually flipped visibility"); + assertEquals("Jane Doe", hidden.author(), "unpublishing must not un-attribute the entry"); + f.controller().togglePublished("post", new RedirectAttributesModelMap()); + assertEquals("Jane Doe", f.store().read("acme", "post").orElseThrow().author()); + assertEquals("# Hi", f.store().readBody("acme", "post", "en"), "a toggle never touches a body"); + } + + @Test + void itIsAConsoleScreenWhoseMutationsArePermissionGatedPosts() { + Class type = BlogAdminController.class; + assertNotNull(type.getAnnotation(Controller.class)); + assertNotNull(type.getAnnotation(ConsoleScreen.class), "the kernel renders it inside the operator shell"); + int gets = 0; + int posts = 0; + for (Method m : type.getDeclaredMethods()) { + GetMapping get = m.getAnnotation(GetMapping.class); + PostMapping post = m.getAnnotation(PostMapping.class); + if (get == null && post == null) { + continue; + } + String[] paths = get != null ? get.value() : post.value(); + for (String path : paths) { + assertTrue(path.equals("/__admin/blog") || path.startsWith("/__admin/blog/"), + m.getName() + ": every mapping lies under /__admin/blog (" + path + ")"); + } + PreAuthorize gate = m.getAnnotation(PreAuthorize.class); + assertNotNull(gate, m.getName() + " is permission-gated"); + assertEquals("@authz.may('blog|manage')", gate.value()); + if (get != null) { + gets++; + assertTrue(Set.of("list", "createForm", "editForm").contains(m.getName()), + m.getName() + ": a GET only renders"); + } else { + posts++; + } + } + assertEquals(3, gets); + assertEquals(4, posts, "create, update, publish toggle, delete — each a CSRF-checked POST"); + } +} diff --git a/plugins/blog/src/test/java/mx/quest/blog/BlogAdminTemplatesRenderTest.java b/plugins/blog/src/test/java/mx/quest/blog/BlogAdminTemplatesRenderTest.java new file mode 100644 index 0000000..0bf9b61 --- /dev/null +++ b/plugins/blog/src/test/java/mx/quest/blog/BlogAdminTemplatesRenderTest.java @@ -0,0 +1,160 @@ +package mx.quest.blog; + +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.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * Renders the console templates ({@code admin-list}, {@code admin-edit}) through the real decoupled-logic pipeline + * with the models the controller builds — a binding typo (a {@code /} where {@code //} belongs, a broken selector) is + * a RUNTIME failure the unit tests can't see; this test turns it into a build failure. And it holds the templates to + * the {@code @ConsoleScreen} contract: the only shell variables they read are {@code _csrf} (and their own + * controller's model), they reach no bean, and every {@code #{…}} key is in this plugin's own bundle. + */ +class BlogAdminTemplatesRenderTest { + + /** What the controller puts in the model for these templates — the plugin's own variables. */ + private static final Set OWN_MODEL = Set.of("rows", "row", "blogEnabled", "entry", "bodies", "creating", + "shadowedBy", "siteLocaleTags", "defaultLocaleTag", "formAction", "lang"); + /** What the shell promises a console screen's content template (SPI {@code ConsoleScreen}). */ + private static final Set SHELL_CONTRACT = Set.of("_csrf", "tenantSiteId"); + + private static String live(String file) throws IOException { + return Files.readString(Path.of("templates", file), StandardCharsets.UTF_8).replaceAll("(?s)", ""); + } + + private static Map withCsrf(Map vars) { + Map all = new HashMap<>(vars); + // The shell's CsrfToken, as SpEL reads it (parameterName, token). + all.put("_csrf", Map.of("parameterName", "_csrf", "token", "tok-123")); + return all; + } + + @Test + void theConsoleTemplatesReadOnlyTheirOwnModelAndThePromisedShellVariables() throws IOException { + Pattern root = Pattern.compile("\\$\\{\\s*!?\\s*([A-Za-z_@#][\\w]*)"); + Pattern message = Pattern.compile("#\\{([^}(]+)"); + Set bundle = BlogConfigTest.keys("i18n/messages.properties"); + Set roots = new TreeSet<>(); + for (String file : List.of("admin-list.th.xml", "admin-edit.th.xml")) { + String logic = live(file); + Matcher m = root.matcher(logic); + while (m.find()) { + roots.add(m.group(1)); + } + Matcher k = message.matcher(logic); + while (k.find()) { + assertTrue(bundle.contains(k.group(1).trim()), file + ": #{" + k.group(1) + + "} is not in this plugin's bundle (no kernel console key is promised)"); + } + } + for (String r : roots) { + assertFalse(r.startsWith("@"), "no bean reference in the console templates: " + r); + assertTrue(r.startsWith("#") || OWN_MODEL.contains(r) || SHELL_CONTRACT.contains(r), + "a variable neither the controller nor the shell contract provides: " + r); + } + assertTrue(roots.contains("_csrf"), "every mutating form carries the CSRF token"); + } + + @Test + void theListScreenRendersRowsBadgesPostFormsAndCsrf(@TempDir Path tmp) { + BlogEntry published = new BlogEntry("hello", Map.of("en", "Hello"), Map.of(), List.of("en", "es"), + null, Map.of(), null, true, "2026-07-17", null, null); + BlogEntry draft = new BlogEntry("secret", Map.of("en", "Secret"), Map.of(), List.of(), + null, Map.of(), null, false, null, null, null); + String html = new TemplateHarness(tmp).render("__plugin__/blog/admin-list", Locale.ENGLISH, withCsrf(Map.of( + "rows", List.of(new BlogAdminController.EntryRow(published, "/blog/hello"), + new BlogAdminController.EntryRow(draft, "/blog/secret")), + "blogEnabled", true))); + + assertTrue(html.contains("/blog/hello") && html.contains("/blog/secret"), "the resolved public paths"); + assertTrue(html.contains("en, es"), "the languages"); + assertTrue(html.contains("2026-07-17"), "the date renders"); + assertTrue(html.contains(">Published<") && html.contains(">Draft<"), "the plugin's badges"); + assertTrue(html.contains("bg-green-lt") && html.contains("bg-yellow-lt")); + assertTrue(html.contains("href=\"/__admin/blog/hello/edit\""), "the edit link (a GET that only renders)"); + assertTrue(html.contains("method=\"post\" action=\"/__admin/blog/hello/publish\""), "publish is a POST"); + assertTrue(html.contains("method=\"post\" action=\"/__admin/blog/secret/delete\""), "delete is a POST"); + assertEquals(4, html.split("name=\"_csrf\" value=\"tok-123\"", -1).length - 1, + "every mutating form (2 rows × publish + delete) carries the console's CSRF token"); + assertFalse(html.contains("href=\"/__admin/blog/hello/publish\"") || html.contains("/delete\" href"), + "no link points at a mutation"); + assertTrue(html.contains(">Site<"), "the pretitle comes from the plugin's own bundle"); + assertFalse(html.contains("??"), "every message key resolved"); + assertFalse(html.contains("id=\"bl-disabled\""), "no banner when enabled"); + assertFalse(html.contains("id=\"bl-empty\""), "no empty row with entries"); + } + + @Test + void theListScreenShowsTheEmptyRowAndTheDisabledBanner(@TempDir Path tmp) { + TemplateHarness harness = new TemplateHarness(tmp); + String disabled = harness.render("__plugin__/blog/admin-list", Locale.of("es"), withCsrf(Map.of( + "rows", List.of(), "blogEnabled", false))); + assertTrue(disabled.contains("id=\"bl-disabled\""), "disabled banner present"); + assertTrue(disabled.contains("id=\"bl-empty\""), "the empty row"); + assertTrue(disabled.contains(">Sitio<"), "Spanish console words from the plugin's bundle"); + assertFalse(disabled.contains("??")); + } + + @Test + void theEditorRendersPerLanguageCardsForBothCreateAndEdit(@TempDir Path tmp) { + TemplateHarness harness = new TemplateHarness(tmp); + BlogEntry entry = new BlogEntry("hello", Map.of("en", "Hello", "es", "Hola"), + Map.of("en", "Desc"), List.of("en"), "hello-slug", Map.of("es", "hola-slug"), + "/custom", true, "2026-07-17", "Jane Doe", null); + Map vars = Map.of( + "formAction", "/__admin/blog/hello", + "entry", entry, + "bodies", Map.of("en", "# Body EN", "es", ""), + "creating", false, + "shadowedBy", List.of("about (en)"), + "siteLocaleTags", List.of("en", "es"), + "defaultLocaleTag", "en"); + String html = harness.render("__plugin__/blog/admin-edit", Locale.ENGLISH, withCsrf(vars)); + + assertTrue(html.contains("method=\"post\" action=\"/__admin/blog/hello\""), "edit mode POSTs to the entry"); + assertTrue(html.contains("name=\"_csrf\" value=\"tok-123\""), "with the console's CSRF token"); + assertTrue(html.contains("name=\"title_en\"") && html.contains("name=\"title_es\""), + "one language card per site locale, fields renamed per language"); + assertTrue(html.contains("value=\"Hello\"") && html.contains("value=\"Hola\""), "titles prefilled"); + assertTrue(html.contains("value=\"hello-slug\""), "the default language's slug is the base slug"); + assertTrue(html.contains("value=\"hola-slug\""), "the localized slug prefills"); + assertTrue(html.contains("name=\"body_en\"") && html.contains("# Body EN"), "the Markdown body prefills"); + assertTrue(html.contains("value=\"/custom\""), "the custom path prefills"); + assertTrue(html.contains("value=\"Jane Doe\""), "the author prefills"); + assertTrue(html.contains("name=\"locales_en\" checked"), "a published language is ticked"); + assertTrue(html.contains("readonly"), "the id is readonly on edit"); + assertTrue(html.contains("about (en)"), "the reverse advisory renders the winning page"); + assertTrue(html.contains("en · default"), "the default language is marked"); + assertFalse(html.contains("??"), "every message key resolved"); + + Map creating = Map.of( + "formAction", "/__admin/blog/create", + "entry", new BlogEntry("new-entry", Map.of(), Map.of(), List.of(), null, Map.of(), + null, false, null, null, null), + "bodies", Map.of(), + "creating", true, + "shadowedBy", List.of(), + "siteLocaleTags", List.of("en"), + "defaultLocaleTag", "en"); + String createHtml = harness.render("__plugin__/blog/admin-edit", Locale.ENGLISH, withCsrf(creating)); + assertTrue(createHtml.contains("action=\"/__admin/blog/create\""), "create mode posts to /create"); + assertFalse(createHtml.contains("readonly"), "the id is editable on create"); + assertFalse(createHtml.contains("id=\"be-shadowed\""), "no advisory on create"); + } +} diff --git a/plugins/blog/src/test/java/mx/quest/blog/BlogConfigTest.java b/plugins/blog/src/test/java/mx/quest/blog/BlogConfigTest.java new file mode 100644 index 0000000..d422b96 --- /dev/null +++ b/plugins/blog/src/test/java/mx/quest/blog/BlogConfigTest.java @@ -0,0 +1,195 @@ +package mx.quest.blog; + +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.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.Reader; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import mx.quest.runway.spi.ContentSource; +import mx.quest.runway.spi.model.SiteView; +import mx.quest.runway.spi.service.ContentCatalogView; +import mx.quest.runway.spi.service.ContentChanges; +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.yaml.snakeyaml.Yaml; + +/** + * The plugin's contract with the host, checked at build time: the wiring over SPI services only, the bean-name rule, + * the descriptor (SPI floor, release version, no personal data, the settings the code reads), the i18n bundles, and + * that the compiled classes link nothing of the host but the SPI — the same things the kernel's load-time checks + * warn about (and refuse from Runway 1.0). + */ +class BlogConfigTest { + + private static final String PREFIX = "blog"; + + static Set 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()); + } + + @SuppressWarnings("unchecked") + private static Map descriptor() throws IOException { + try (Reader in = Files.newBufferedReader(Path.of("plugin.yml"), StandardCharsets.UTF_8)) { + return (Map) new Yaml().load(in); + } + } + + private static Set beanMethodNames() { + return Arrays.stream(BlogConfig.class.getDeclaredMethods()) + .filter(m -> m.isAnnotationPresent(Bean.class)) + .map(Method::getName) + .collect(Collectors.toCollection(TreeSet::new)); + } + + @Test + void wiresEverythingFromSpiServicesUnderPrefixedNames(@TempDir Path sites) throws IOException { + Files.createDirectories(sites.resolve("acme")); + FakeSiteServices kernel = new FakeSiteServices() + .site(new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null)) + .current("acme"); + try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) { + ctx.registerBean(PluginSettings.class, () -> new FakePluginSettings()); + ctx.registerBean(PluginSiteFiles.class, () -> new TempDirSiteFiles(sites, "blog")); + ctx.registerBean(ContentCatalogView.class, () -> new FakeContentCatalog().site("acme")); + ctx.registerBean(ContentChanges.class, () -> new EventDispatch("blog", Set.of("blog"))); + ctx.registerBean(FakeSiteServices.class, () -> kernel); + ctx.register(BlogConfig.class); + ctx.refresh(); + + assertEquals(Set.of("blogStore", "blogContentSource", "blogAdminController"), + new TreeSet<>(Arrays.stream(ctx.getBeanDefinitionNames()) + .filter(n -> n.startsWith("blog") && !n.equals("blogConfig")).toList()), + "the mainClass itself is registered by the host as plugin:blog"); + BlogContentSource source = ctx.getBean("blogContentSource", BlogContentSource.class); + assertSame(source, ctx.getBean(ContentSource.class), "collected as the site's content source"); + assertSame(source, ctx.getBean(SiteEventListener.class), "…and as its own index's listener"); + assertEquals("blog", source.key()); + ctx.getBean("blogStore", BlogStore.class).save("acme", new BlogEntry("hi", Map.of("en", "Hi"), Map.of(), + List.of("en"), null, Map.of(), null, true, null, null, null), Map.of("en", "x")); + assertTrue(Files.isRegularFile(sites.resolve("acme/plugins/blog/entries/hi/entry.yml")), + "the store writes through the injected PluginSiteFiles"); + org.springframework.ui.ExtendedModelMap model = new org.springframework.ui.ExtendedModelMap(); + ctx.getBean("blogAdminController", BlogAdminController.class).list(model); + assertEquals(1, ((List) model.getAttribute("rows")).size(), + "the controller reads the bound site through RequestContext"); + } + } + + @Test + void everyBeanNameStartsWithThePluginId() { + assertEquals(Set.of("blogStore", "blogContentSource", "blogAdminController"), beanMethodNames()); + for (Method m : BlogConfig.class.getDeclaredMethods()) { + Bean bean = m.getAnnotation(Bean.class); + if (bean != null) { + for (String alias : bean.name()) { + assertTrue(alias.startsWith(PREFIX), "an explicit bean name must start with " + PREFIX + ": " + alias); + } + } + } + } + + @Test + void theDescriptorDeclaresTheSpiFloorAndTheReleaseVersion() throws IOException { + Map yml = descriptor(); + assertEquals("blog", yml.get("id")); + assertEquals(BlogConfig.class.getName(), yml.get("mainClass")); + 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("runway-plugin-blog\\s*([^<]+)") + .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"); + assertTrue(pom.contains("2026-10-21T18:56:00Z")); + assertFalse(pom.contains("runway-app"), "no runway-app dependency in any scope"); + } + + @Test + @SuppressWarnings("unchecked") + void theDescriptorDeclaresNoPersonalDataAndTheSettingsTheCodeReads() throws IOException { + Map yml = descriptor(); + assertNull(yml.get("siteData"), "blog entries are published content the site's operators author, not personal data"); + List> schema = (List>) yml.get("siteSettings"); + Map byKey = new java.util.HashMap<>(); + schema.forEach(s -> byKey.put(String.valueOf(s.get("key")), s.get("default"))); + assertEquals(Map.of("enabled", true, "prefix", BlogSettings.DEFAULT_PREFIX, + "template", BlogSettings.DEFAULT_TEMPLATE), byKey, "the code's fallbacks match the declared defaults"); + List> permissions = (List>) yml.get("permissions"); + assertEquals(List.of("settings", "manage"), permissions.stream().map(p -> p.get("id")).toList()); + List> menu = (List>) yml.get("menu"); + assertEquals("/__admin/blog", menu.get(0).get("path")); + assertEquals("blog|manage", menu.get(0).get("permission")); + } + + @Test + void theEnglishAndSpanishBundlesDefineTheSameKeysAndEveryDescriptorLabel() throws IOException { + Set en = keys("i18n/messages.properties"); + assertEquals(en, keys("i18n/messages_es.properties")); + String yml = Files.readString(Path.of("plugin.yml"), StandardCharsets.UTF_8); + Matcher label = Pattern.compile("label: (blog\\.[\\w.]+)").matcher(yml); + int found = 0; + while (label.find()) { + found++; + assertTrue(en.contains(label.group(1)), "descriptor label without words: " + label.group(1)); + } + assertEquals(6, found, "2 permissions, 3 settings, 1 menu entry"); + } + + @Test + void theCompiledClassesLinkNoHostInternals() throws IOException { + Path classes = Path.of("target", "classes"); + Pattern host = Pattern.compile("mx[/.]quest[/.]runway[/.](?!spi[/.])[\\w/.$]*"); + List problems = new ArrayList<>(); + int scanned = 0; + try (Stream 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 >= 6, "the compiled classes were found (" + scanned + ")"); + assertTrue(problems.isEmpty(), "host linkage: " + problems); + } +} diff --git a/plugins/blog/src/test/java/mx/quest/blog/BlogContentSourceTest.java b/plugins/blog/src/test/java/mx/quest/blog/BlogContentSourceTest.java new file mode 100644 index 0000000..58ff2f0 --- /dev/null +++ b/plugins/blog/src/test/java/mx/quest/blog/BlogContentSourceTest.java @@ -0,0 +1,372 @@ +package mx.quest.blog; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +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.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.HashMap; +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.ContentSource; +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.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.TempDirSiteFiles; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * {@link BlogContentSource} against the ContentSource contract: published-only metadata enumeration, the O(1) URL + * index (prefix + localized slugs + custom paths), Markdown bodies fetched only via {@code body()}, the per-site enable + * switch and prefix setting (through {@code PluginSettings}, with the kernel's path rule) — and its index invalidation + * as a {@code SOURCE}-phase {@link SiteEventListener}, driven by the testkit's {@link EventDispatch} in the kernel's + * delivery order. + */ +class BlogContentSourceTest { + + private static final Locale EN = Locale.ENGLISH; + private static final Locale ES = Locale.of("es"); + private static final SiteView SITE = new SiteView("acme", "Acme", EN, List.of(EN, ES), null); + + private record Fixture(BlogStore store, BlogContentSource source, FakePluginSettings settings, + EventDispatch events) { + } + + private static Fixture fixture(Path tmp, Map cfg) throws IOException { + Files.createDirectories(tmp.resolve("acme")); + BlogStore store = new BlogStore(new TempDirSiteFiles(tmp, "blog")); + FakePluginSettings settings = new FakePluginSettings() + .defaults(Map.of("enabled", true, "prefix", "/blog", "template", "entry-classic")) + .site("acme", cfg); + FakeContentCatalog catalog = new FakeContentCatalog().site("acme").route("/sitemap.xml"); + BlogContentSource source = new BlogContentSource(store, settings, catalog); + EventDispatch events = new EventDispatch("blog", Set.of(BlogContentSource.KEY)).listener(source); + return new Fixture(store, source, settings, events); + } + + private static BlogEntry entry(String id, boolean published) { + return new BlogEntry(id, Map.of("en", "T-" + id, "es", "ES-" + id), Map.of("en", "D"), + List.of("en", "es"), null, Map.of("es", id + "-es"), null, published, "2026-07-17", null, null); + } + + private static Map byId(BlogContentSource source) { + Map out = new HashMap<>(); + for (ContentRef r : source.enumerate(SITE)) { + out.put(r.id(), r); + } + return out; + } + + @Test + void enumeratesPublishedEntriesAsRefsUnderThePrefix(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of()); + f.store().save("acme", entry("hello", true), Map.of("en", "# Hi")); + f.store().save("acme", entry("draft", false), null); + + List refs = f.source().enumerate(SITE); + assertEquals(1, refs.size(), "unpublished entries are never enumerated (draft-leak fail-closed)"); + ContentRef ref = refs.get(0); + assertEquals("hello", ref.id()); + assertEquals("/blog/hello", ref.pathFor(EN), "default prefix + slug"); + assertEquals("/blog/hello-es", ref.pathFor(ES), "localized slug under the same prefix"); + assertEquals("T-hello", ref.titleFor(EN)); + assertEquals("D", ref.descriptionFor(EN)); + assertEquals(List.of(EN, ES), ref.locales()); + assertEquals("__plugin__/blog/entry-classic", ref.bodyTemplate(), "the default template setting"); + assertTrue(ref.published()); + assertNotNull(ref.updatedAt(), "file-time-derived — a body edit moves the ETag automatically"); + assertEquals(BlogContentSource.KEY, f.source().key()); + } + + @Test + void entriesWrittenBy131EnumerateAndResolveUnchanged(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of()); + BlogStoreTest.install131(tmp, "acme"); + Map refs = byId(f.source()); + assertEquals(Set.of("hello-world", "no-author", "launch"), refs.keySet(), "the draft stays out"); + assertEquals("/blog/hello-world", refs.get("hello-world").pathFor(EN)); + assertEquals("/blog/hola-mundo", refs.get("hello-world").pathFor(ES)); + assertEquals("Jane Doe", refs.get("hello-world").author()); + assertNull(refs.get("no-author").author(), "the entry with no author stays unattributed"); + assertEquals(Instant.parse("2026-08-01T00:00:00Z"), refs.get("no-author").publishedAt()); + assertEquals("/announcing-v2", refs.get("launch").pathFor(EN), "the custom path survives"); + assertEquals("launch", f.source().resolve(SITE, "/announcing-v2", EN).orElseThrow().id()); + assertTrue(f.source().body(SITE, "hello-world", EN).bodyHtml().contains("bold")); + } + + @Test + void resolvesThroughTheIndexIncludingCustomPaths(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of()); + f.store().save("acme", entry("hello", true), null); + f.store().save("acme", new BlogEntry("launch", Map.of("en", "Launch"), Map.of(), List.of("en"), + null, Map.of(), "/announcing-v2", true, null, null, null), null); + + assertEquals("hello", f.source().resolve(SITE, "/blog/hello", EN).orElseThrow().id()); + assertEquals("hello", f.source().resolve(SITE, "/blog/hello-es", ES).orElseThrow().id(), + "the localized slug resolves under its own locale"); + assertEquals(Optional.empty(), f.source().resolve(SITE, "/blog/hello-es", EN), + "a localized slug never doubles as another locale's URL"); + assertEquals("launch", f.source().resolve(SITE, "/announcing-v2", EN).orElseThrow().id(), + "a custom path escapes the prefix (the arbitrary-paths capability)"); + assertEquals(Optional.empty(), f.source().resolve(SITE, "/blog/nope", EN)); + assertTrue(f.source().capabilities().has(ContentSource.CAP_ARBITRARY_PATHS)); + } + + @Test + void itIsASourcePhaseListener(@TempDir Path tmp) throws IOException { + assertEquals(SiteEventListener.Phase.SOURCE, fixture(tmp, Map.of()).source().phase(), + "its own index must drop BEFORE sitemap/search consumers re-read the listing"); + } + + @Test + void itsOwnContentChangeDropsTheIndexAndTheRefs(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of()); + f.store().save("acme", entry("hello", true), null); + f.source().resolve(SITE, "/blog/hello", EN); + assertNotNull(f.source().cachedIndex("acme"), "index built lazily on first resolve"); + assertNotNull(f.source().cachedRefs("acme")); + + // What the console calls after a save — delivered back as a CONTENT change for this source's key. + f.store().save("acme", entry("second", true), null); + f.events().changed("acme", BlogContentSource.KEY, "second"); + assertNull(f.source().cachedIndex("acme"), "own-content change drops the index"); + assertNull(f.source().cachedRefs("acme"), "…and the enumerated refs"); + assertEquals("second", f.source().resolve(SITE, "/blog/second", EN).orElseThrow().id(), + "the next probe sees the new entry"); + assertTrue(f.events().failures().isEmpty()); + } + + @Test + void aReplayedChangeFromAPeerNodeDropsItToo(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of()); + f.store().save("acme", entry("hello", true), null); + f.source().resolve(SITE, "/blog/hello", EN); + f.events().catalog(new CatalogChange("acme", CatalogChange.Cause.CONTENT, BlogContentSource.KEY, null, + "blog", List.of(), List.of(), false)); + assertNull(f.source().cachedIndex("acme"), "local == false still converges this node's index"); + } + + @Test + void otherChangesLeaveTheIndexAlone(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of()); + f.store().save("acme", entry("hello", true), null); + f.source().resolve(SITE, "/blog/hello", EN); + Map built = f.source().cachedIndex("acme"); + + f.events().page("acme", "about", List.of(), List.of()); + f.events().catalog(new CatalogChange("acme", CatalogChange.Cause.CONTENT, "products", "x", "shop", + List.of(), List.of(), true)); + f.events().settings("acme", "search"); + f.events().catalog(new CatalogChange("globex", CatalogChange.Cause.CONTENT, BlogContentSource.KEY, "x", + "blog", List.of(), List.of(), true)); + assertTrue(built == f.source().cachedIndex("acme"), + "a page write, another source's change, another plugin's settings, another site: kept"); + } + + @Test + void itsOwnSettingsSaveDropsTheIndexAndRekeysEveryUrl(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of()); + f.store().save("acme", entry("hello", true), null); + assertEquals("/blog/hello", f.source().enumerate(SITE).get(0).pathFor(EN)); + f.source().resolve(SITE, "/blog/hello", EN); + + f.settings().site("acme", Map.of("prefix", "/news")); + f.events().settings("acme", "blog"); + assertNull(f.source().cachedIndex("acme"), "a prefix change re-keys every URL — dropped"); + assertEquals("/news/hello", f.source().enumerate(SITE).get(0).pathFor(EN)); + assertEquals("hello", f.source().resolve(SITE, "/news/hello", EN).orElseThrow().id()); + assertEquals(Optional.empty(), f.source().resolve(SITE, "/blog/hello", EN), "the old URL is gone"); + } + + @Test + void everyLifecycleEventDropsTheIndex(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of()); + f.store().save("acme", entry("hello", true), null); + for (SiteLifecycleEvent.Kind kind : SiteLifecycleEvent.Kind.values()) { + f.source().resolve(SITE, "/blog/hello", EN); + assertNotNull(f.source().cachedIndex("acme")); + f.events().lifecycle("acme", kind, kind == SiteLifecycleEvent.Kind.RESTORED); + assertNull(f.source().cachedIndex("acme"), kind + " drops it (a restore replaced the files wholesale)"); + } + } + + @Test + void bodyRendersMarkdownAndCarriesThePublicationDate(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of()); + f.store().save("acme", entry("hello", true), Map.of("en", "# Title\n\nSome **bold** text.")); + + ContentBody body = f.source().body(SITE, "hello", EN); + assertTrue(body.bodyHtml().contains("

Title

"), "markdown heading rendered"); + assertTrue(body.bodyHtml().contains("bold"), "markdown emphasis rendered"); + assertEquals("2026-07-17", body.attributes().get("publishedOn")); + assertEquals("", f.source().body(SITE, "hello", ES).bodyHtml(), "no es body → empty (soft)"); + } + + @Test + void aCorruptEntryNeverBlanksTheRestOfTheBlog(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of()); + f.store().save("acme", entry("good", true), Map.of("en", "fine")); + Path corrupt = tmp.resolve("acme/plugins/blog/entries/broken"); + Files.createDirectories(corrupt); + Files.writeString(corrupt.resolve("entry.yml"), "title: [unclosed"); + + List refs = f.source().enumerate(SITE); + assertEquals(1, refs.size(), "the good entry survives its corrupt sibling"); + assertEquals("good", f.source().resolve(SITE, "/blog/good", EN).orElseThrow().id()); + } + + @Test + void twoEntriesClaimingOnePathResolveDeterministically(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of()); + f.store().save("acme", new BlogEntry("one", Map.of("en", "One"), Map.of(), List.of("en"), + "shared", Map.of(), null, true, "2026-01-02", null, null), null); + f.store().save("acme", new BlogEntry("two", Map.of("en", "Two"), Map.of(), List.of("en"), + "shared", Map.of(), null, true, "2026-01-01", null, null), null); + String winner = f.source().resolve(SITE, "/blog/shared", EN).orElseThrow().id(); + f.events().changed("acme", BlogContentSource.KEY, null); + assertEquals(winner, f.source().resolve(SITE, "/blog/shared", EN).orElseThrow().id(), + "one deterministic winner, the same after a rebuild"); + } + + @Test + void aDisabledSiteServesAndListsNothing(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of("enabled", false)); + f.store().save("acme", entry("hello", true), null); + assertTrue(f.source().enumerate(SITE).isEmpty()); + assertEquals(Optional.empty(), f.source().resolve(SITE, "/blog/hello", EN)); + assertTrue(!f.source().settings("acme").enabled()); + } + + @Test + void aCustomPrefixRekeysEveryUrl(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of("prefix", "news/")); + f.store().save("acme", entry("hello", true), null); + assertEquals("/news/hello", f.source().enumerate(SITE).get(0).pathFor(EN), "normalized: leading /, no trailing"); + assertEquals("hello", f.source().resolve(SITE, "/news/hello", EN).orElseThrow().id()); + } + + @Test + void theRootPrefixServesEntriesAtTheTopLevel(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of("prefix", "/")); + f.store().save("acme", entry("hello", true), null); + assertEquals("/hello", f.source().enumerate(SITE).get(0).pathFor(EN), "never '//hello'"); + } + + @Test + void aPrefixTheKernelWouldNotServeFallsBackToBlog(@TempDir Path tmp) throws IOException { + for (String bad : List.of("/__admin", "/app", "/actuator", "/a|b", "/x/../y")) { + Fixture f = fixture(tmp.resolve("p" + Math.abs(bad.hashCode())), Map.of("prefix", bad)); + assertEquals("/blog", f.source().settings("acme").prefix(), + bad + ": entries under it would silently vanish — the default is used instead"); + } + for (String ok : List.of("/sitemap.xml", "/login", "/news/archive")) { + assertEquals(ok, fixture(tmp.resolve("ok" + Math.abs(ok.hashCode())), Map.of("prefix", ok)) + .source().settings("acme").prefix(), ok + ": only the path an entry would get is checked"); + } + } + + @Test + void theTemplateSettingFailsClosedToClassic(@TempDir Path tmp) throws IOException { + assertEquals("__plugin__/blog/entry-minimal", + fixture(tmp.resolve("a"), Map.of("template", "entry-minimal")).source().settings("acme").bodyTemplate()); + assertEquals("__plugin__/blog/entry-classic", + fixture(tmp.resolve("b"), Map.of("template", "../../evil")).source().settings("acme").bodyTemplate(), + "an unknown template name never reaches the template lookup"); + } + + @Test + void indexableTextIsRenderedHtmlPerLocaleSoEnginesStripCleanly(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of()); + f.store().save("acme", entry("hello", true), + Map.of("en", "# Hi\n\nRunway makes [hosting](/x) simple.", "es", "# Hola")); + + assertTrue(f.source().capabilities().has(ContentSource.CAP_INDEXABLE_TEXT), + "the blog opts into the search seam — entries are first-class search citizens"); + String en = f.source().indexableText(SITE, "hello", EN); + assertTrue(en.contains("

Hi

"), "heading rendered, not left as '# Hi': " + en); + assertTrue(en.contains("hosting"), "link rendered, not left as Markdown syntax: " + en); + assertTrue(f.source().indexableText(SITE, "hello", ES).contains("

Hola

"), "per-locale material"); + assertEquals("", f.source().indexableText(SITE, "hello", Locale.FRENCH), + "an untranslated locale indexes as metadata only, never an error"); + assertEquals("", f.source().indexableText(SITE, "no-such-entry", EN), "an unknown id degrades to empty"); + } + + /** Each entry carries ITS OWN publication date across the SPI boundary (not one shared schema block). */ + @Test + void eachEntryCarriesItsOwnPublicationDate(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of()); + f.store().save("acme", new BlogEntry("older", Map.of("en", "Older"), Map.of(), List.of("en"), + null, Map.of(), null, true, "2026-03-04", null, null), null); + f.store().save("acme", new BlogEntry("newer", Map.of("en", "Newer"), Map.of(), List.of("en"), + null, Map.of(), null, true, "2026-09-10", null, null), null); + Map refs = byId(f.source()); + assertEquals(Instant.parse("2026-03-04T00:00:00Z"), refs.get("older").publishedAt()); + assertEquals(Instant.parse("2026-09-10T00:00:00Z"), refs.get("newer").publishedAt()); + assertNotEquals(refs.get("older").publishedAt(), refs.get("newer").publishedAt()); + } + + /** A free-form publishedOn yields NO date rather than a guess (a wrong datePublished is worse than none). */ + @Test + void anUnparseablePublishedOnYieldsNoDateRatherThanAGuess(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of()); + f.store().save("acme", new BlogEntry("freeform", Map.of("en", "Freeform"), Map.of(), List.of("en"), + null, Map.of(), null, true, "last spring", null, null), null); + f.store().save("acme", new BlogEntry("undated", Map.of("en", "Undated"), Map.of(), List.of("en"), + null, Map.of(), null, true, null, null, null), null); + assertNull(byId(f.source()).get("freeform").publishedAt(), "a non-date must not become a fabricated instant"); + assertNull(byId(f.source()).get("undated").publishedAt()); + } + + /** Each entry carries ITS OWN author across the SPI boundary, so structured data attributes the right person. */ + @Test + void eachEntryCarriesItsOwnAuthor(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of()); + f.store().save("acme", new BlogEntry("ada", Map.of("en", "Ada"), Map.of(), List.of("en"), + null, Map.of(), null, true, "2026-03-04", "Jane Doe", null), null); + f.store().save("acme", new BlogEntry("anon", Map.of("en", "Anon"), Map.of(), List.of("en"), + null, Map.of(), null, true, "2026-03-04", " ", null), null); + assertEquals("Jane Doe", byId(f.source()).get("ada").author()); + assertNull(byId(f.source()).get("anon").author(), "a blank byline must normalise to absent"); + } + + /** The byline reaches the RENDER attributes too — and is absent, not empty, when the entry has none. */ + @Test + void theAuthorReachesTheRenderAttributes(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of()); + f.store().save("acme", new BlogEntry("ada", Map.of("en", "Ada"), Map.of(), List.of("en"), + null, Map.of(), null, true, "2026-03-04", "Jane Doe", null), Map.of("en", "# Hello")); + f.store().save("acme", new BlogEntry("anon", Map.of("en", "Anon"), Map.of(), List.of("en"), + null, Map.of(), null, true, null, null, null), Map.of("en", "# Hi")); + assertEquals("Jane Doe", f.source().body(SITE, "ada", EN).attributes().get("author")); + assertEquals(Map.of(), f.source().body(SITE, "anon", EN).attributes(), + "an unattributed, undated entry puts nothing into the render attributes"); + } + + @Test + void publicPathsFollowTheRoutingSemantics(@TempDir Path tmp) throws IOException { + Fixture f = fixture(tmp, Map.of()); + BlogEntry custom = new BlogEntry("launch", Map.of("en", "L"), Map.of(), List.of("en", "es"), "v2", + Map.of("es", "lanzamiento"), "/announcing-v2", true, null, null, null); + assertEquals("/announcing-v2", f.source().publicPath("acme", custom)); + assertEquals("/blog/lanzamiento", f.source().publicPath("acme", custom, "es"), "the localized slug"); + assertEquals("/announcing-v2", f.source().publicPath("acme", custom, "en")); + BlogEntry plain = new BlogEntry("plain", Map.of("en", "P"), Map.of(), List.of("en"), "slugged", + Map.of(), null, true, null, null, null); + assertEquals("/blog/slugged", f.source().publicPath("acme", plain)); + } +} diff --git a/plugins/blog/src/test/java/mx/quest/blog/BlogEntryTemplateContractTest.java b/plugins/blog/src/test/java/mx/quest/blog/BlogEntryTemplateContractTest.java new file mode 100644 index 0000000..f4ba222 --- /dev/null +++ b/plugins/blog/src/test/java/mx/quest/blog/BlogEntryTemplateContractTest.java @@ -0,0 +1,200 @@ +package mx.quest.blog; + +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.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import mx.quest.runway.spi.model.ContentBody; +import mx.quest.runway.spi.model.ContentRef; +import mx.quest.runway.spi.model.SiteView; +import mx.quest.runway.spi.testkit.FakeContentCatalog; +import mx.quest.runway.spi.testkit.FakePluginSettings; +import mx.quest.runway.spi.testkit.TempDirSiteFiles; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * The entry body templates against the documented body-template render model — the SPI contract on + * {@code ContentSource} / {@code ContentRef.bodyTemplate} for {@code ${master}} and {@code ${content.*}}. The kernel + * promises exactly {@code master}, {@code content.{id, sourceKey, title, description, bodyHtml, attributes, updatedAt}}, + * {@code locale} and {@code urls}; nothing else. + * + *
    + *
  • Statically: every {@code ${…}} expression in the shipped entry templates starts from one of those four + * variables, and every {@code content.} key it reads is one the contract lists.
  • + *
  • Dynamically: an entry stored by {@link BlogStore} and projected by {@link BlogContentSource} renders through + * the real decoupled templates with a model built exactly to the contract — the tenant's master chrome around + * the Markdown body, the plugin's own labels, and the byline in each of its four states.
  • + *
+ * The real kernel render (routing, the locale ladder, the master resolution) is exercised by + * {@code scripts/verify-against-host.sh}. + */ +class BlogEntryTemplateContractTest { + + private static final Set MODEL_ROOTS = Set.of("master", "content", "locale", "urls"); + private static final Set CONTENT_KEYS = + Set.of("id", "sourceKey", "title", "description", "bodyHtml", "attributes", "updatedAt"); + private static final List ENTRY_TEMPLATES = List.of("entry-classic", "entry-minimal"); + + private static final Locale EN = Locale.ENGLISH; + private static final Locale ES = Locale.of("es"); + private static final SiteView SITE = new SiteView("acme", "Acme", EN, List.of(EN, ES), null); + + private static String liveLogic(String template) throws IOException { + return Files.readString(Path.of("templates", template + ".th.xml"), StandardCharsets.UTF_8) + .replaceAll("(?s)", ""); + } + + @Test + void theEntryTemplatesReadOnlyTheDocumentedRenderModel() throws IOException { + Pattern expression = Pattern.compile("\\$\\{([^}]*)}"); + Pattern root = Pattern.compile("^\\s*([A-Za-z_][\\w]*)"); + Pattern contentKey = Pattern.compile("\\bcontent\\.(\\w+)"); + Set roots = new TreeSet<>(); + Set keys = new TreeSet<>(); + for (String template : ENTRY_TEMPLATES) { + Matcher m = expression.matcher(liveLogic(template)); + while (m.find()) { + Matcher r = root.matcher(m.group(1)); + assertTrue(r.find(), template + ": an expression with no variable root: ${" + m.group(1) + "}"); + roots.add(r.group(1)); + Matcher k = contentKey.matcher(m.group(1)); + while (k.find()) { + keys.add(k.group(1)); + } + } + } + assertTrue(MODEL_ROOTS.containsAll(roots), "variables outside the contract: " + roots); + assertTrue(CONTENT_KEYS.containsAll(keys), "content keys outside the contract: " + keys); + assertEquals(Set.of("master", "content", "urls"), roots, "the templates use the chrome, the payload and links"); + } + + @Test + void theEntryTemplatesReferenceNoBeanAndOnlyThePluginsOwnMessages() throws IOException { + Set bundle = BlogConfigTest.keys("i18n/messages.properties"); + Pattern message = Pattern.compile("#\\{([^}(]+)"); + for (String template : ENTRY_TEMPLATES) { + String logic = liveLogic(template); + assertFalse(logic.matches("(?s).*\\$\\{\\s*@.*"), template + " must not reach a bean (not in the contract)"); + Matcher m = message.matcher(logic); + while (m.find()) { + assertTrue(bundle.contains(m.group(1).trim()), template + ": #{" + m.group(1) + + "} is not in this plugin's bundle (a public page renders with the site's bundle + ours)"); + } + } + } + + /** The model the kernel builds for a source item's 200 render, exactly as the SPI documents it. */ + private static Map contractModel(String master, ContentRef ref, ContentBody body, Locale locale) { + Map content = new HashMap<>(); + content.put("id", ref.id()); + content.put("sourceKey", BlogContentSource.KEY); + content.put("title", ref.titleFor(locale)); + content.put("description", ref.descriptionFor(locale)); + content.put("bodyHtml", body.bodyHtml()); + content.put("attributes", body.attributes()); + content.put("updatedAt", ref.updatedAt() == null ? "" : ref.updatedAt().toString()); + return Map.of("master", master, "content", Map.copyOf(content), "locale", locale, + "urls", Map.of("index", "/", "blog:" + ref.id(), ref.pathFor(locale))); + } + + private record Rig(TemplateHarness harness, BlogStore store, BlogContentSource source, String master) { + + String render(String id, Locale locale) { + ContentRef ref = source.enumerate(SITE).stream().filter(r -> r.id().equals(id)).findFirst().orElseThrow(); + return harness.render(ref.bodyTemplate(), locale, + contractModel(master, ref, source.body(SITE, id, locale), locale)); + } + } + + private static Rig rig(Path tmp, Map settings) throws IOException { + Path sites = tmp.resolve("sites"); + Files.createDirectories(sites.resolve("acme")); + BlogStore store = new BlogStore(new TempDirSiteFiles(sites, "blog")); + BlogContentSource source = new BlogContentSource(store, new FakePluginSettings().site("acme", settings), + new FakeContentCatalog().site("acme")); + TemplateHarness harness = new TemplateHarness(tmp.resolve("templates")); + String master = harness.master("sites/acme/_master", + "ACME-MASTER" + + "
acme header
" + + "
m
" + + "
acme footer
"); + return new Rig(harness, store, source, master); + } + + private static BlogEntry entry(String id, String publishedOn, String author) { + return new BlogEntry(id, Map.of("en", "My first post", "es", "Mi primera entrada"), + Map.of("en", "The very first."), List.of("en", "es"), null, Map.of("es", "primera-entrada"), + null, true, publishedOn, author, null); + } + + @Test + void aMarkdownEntryRendersInsideTheTenantsChromeWithPluginLabels(@TempDir Path tmp) throws IOException { + Rig rig = rig(tmp, Map.of()); + rig.store().save("acme", entry("first-post", "2026-07-17", null), + Map.of("en", "Hello **world**.", "es", "Hola **mundo**.")); + + String html = rig.render("first-post", EN); + assertTrue(html.contains("ACME-MASTER"), "the TENANT's master head wraps the entry"); + assertTrue(html.contains("acme header") && html.contains("acme footer"), "tenant chrome seams"); + assertTrue(html.contains("My first post"), "the entry title"); + assertTrue(html.contains("Hello world."), "the Markdown body, rendered"); + assertTrue(html.contains("Published on 2026-07-17") && html.contains("datetime=\"2026-07-17\""), + "the plugin's own #{} label + the publication date"); + assertTrue(html.contains("href=\"/\""), "the back link reads urls['index']"); + + String es = rig.render("first-post", ES); + assertTrue(es.contains("Mi primera entrada") && es.contains("Hola mundo."), "the es payload"); + assertTrue(es.contains("Publicado el 2026-07-17"), "the plugin's es label"); + } + + @Test + void anAuthoredEntryRendersAByline(@TempDir Path tmp) throws IOException { + Rig rig = rig(tmp, Map.of()); + rig.store().save("acme", entry("authored", "2026-07-17", "Jane Doe"), Map.of("en", "Body.")); + String html = rig.render("authored", EN); + assertTrue(html.contains("By Jane Doe"), () -> "expected a rendered byline; got:\n" + html); + assertTrue(html.contains("2026-07-17"), "the date still renders alongside it"); + } + + /** The meta line used to render only with a date; an undated but authored post must keep its byline. */ + @Test + void anUndatedButAuthoredEntryStillRendersItsByline(@TempDir Path tmp) throws IOException { + Rig rig = rig(tmp, Map.of()); + rig.store().save("acme", entry("undated", null, "Richard Roe"), Map.of("en", "Body.")); + String html = rig.render("undated", EN); + assertTrue(html.contains("By Richard Roe"), () -> "an undated entry must still show its byline:\n" + html); + assertFalse(html.contains("Published on"), "…and must not show an empty date label"); + } + + @Test + void anEntryWithNeitherAuthorNorDateRendersNoMetaLine(@TempDir Path tmp) throws IOException { + Rig rig = rig(tmp, Map.of()); + rig.store().save("acme", entry("bare", null, null), Map.of("en", "Body.")); + String html = rig.render("bare", EN); + assertFalse(html.contains("blog-entry-meta"), () -> "no meta line when there is nothing in it:\n" + html); + } + + @Test + void theMinimalTemplateRendersTitleAndBodyOnly(@TempDir Path tmp) throws IOException { + Rig rig = rig(tmp, Map.of("template", "entry-minimal")); + rig.store().save("acme", entry("min", "2026-07-17", "Jane Doe"), Map.of("en", "Just **this**.")); + String html = rig.render("min", EN); + assertTrue(html.contains("ACME-MASTER") && html.contains("acme footer"), "the same tenant chrome"); + assertTrue(html.contains("My first post") && html.contains("Just this."), "title + body"); + assertFalse(html.contains("Jane Doe") || html.contains("Published on") || html.contains("entry-back"), + "no byline, no date, no back link"); + } +} diff --git a/plugins/blog/src/test/java/mx/quest/blog/BlogStoreTest.java b/plugins/blog/src/test/java/mx/quest/blog/BlogStoreTest.java new file mode 100644 index 0000000..cecaad3 --- /dev/null +++ b/plugins/blog/src/test/java/mx/quest/blog/BlogStoreTest.java @@ -0,0 +1,266 @@ +package mx.quest.blog; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.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.nio.file.attribute.FileTime; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; +import mx.quest.runway.spi.testkit.TempDirSiteFiles; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * {@link BlogStore} over the kernel's {@code PluginSiteFiles} (the testkit's {@link TempDirSiteFiles}, which applies + * the kernel's confinement rules): the {@code entries//entry.yml} + {@code body-.md} layout under the + * site's own folder, the metadata/body split, id/lang safety, the derived {@code updatedAt} — and that entries + * written by blog 1.3.1 (the fixture under {@code src/test/resources/fixtures/blog-1.3.1}, produced by the + * 1.3.1 store itself) load unchanged, and are written back byte for byte. + */ +class BlogStoreTest { + + static final Path FIXTURE = Path.of("src/test/resources/fixtures/blog-1.3.1/entries"); + + private static BlogStore store(Path sites) throws IOException { + Files.createDirectories(sites.resolve("acme")); + Files.createDirectories(sites.resolve("globex")); + return new BlogStore(new TempDirSiteFiles(sites, "blog")); + } + + private static BlogEntry entry(String id) { + return new BlogEntry(id, Map.of("en", "Hello", "es", "Hola"), Map.of("en", "First post"), + List.of("en", "es"), null, Map.of("es", "hola-mundo"), null, true, "2026-07-17", null, null); + } + + /** Copies the 1.3.1 entries into a site's plugin subtree, exactly where 1.3.1 kept them. */ + static Path install131(Path sites, String siteId) throws IOException { + Path entries = sites.resolve(siteId).resolve("plugins/blog/entries"); + try (Stream walk = Files.walk(FIXTURE)) { + for (Path from : walk.toList()) { + Path to = entries.resolve(FIXTURE.relativize(from).toString()); + if (Files.isDirectory(from)) { + Files.createDirectories(to); + } else { + Files.copy(from, to); + } + } + } + return entries; + } + + @Test + void saveAndReadRoundTripWithBodies(@TempDir Path sites) throws IOException { + BlogStore store = store(sites); + store.save("acme", entry("hello-world"), Map.of("en", "# Hi\n\nBody.", "es", "# Hola")); + + BlogEntry read = store.read("acme", "hello-world").orElseThrow(); + assertEquals("hello-world", read.id(), "the folder name is the id (never stored in the YAML)"); + assertEquals("Hello", read.title().get("en")); + assertEquals("hola-mundo", read.localizedSlugs().get("es")); + assertEquals("hello-world", read.effectiveSlug(), "no explicit slug → the id"); + assertTrue(read.published()); + assertNotNull(read.updatedAt(), "updatedAt derived from file times"); + assertEquals("# Hi\n\nBody.", store.readBody("acme", "hello-world", "en")); + assertEquals("", store.readBody("acme", "hello-world", "fr"), "no body for that language → empty"); + assertEquals(List.of("en", "es"), store.bodyLangs("acme", "hello-world")); + + // The files land inside the site's own folder, in the plugin's subtree — the backup-completeness guarantee. + Path dir = sites.resolve("acme/plugins/blog/entries/hello-world"); + assertTrue(Files.isRegularFile(dir.resolve("entry.yml"))); + assertTrue(Files.isRegularFile(dir.resolve("body-en.md"))); + assertFalse(Files.readString(dir.resolve("entry.yml")).contains("hello-world"), + "the id is never written into the YAML"); + } + + @Test + void entriesWrittenBy131LoadUnchanged(@TempDir Path sites) throws IOException { + BlogStore store = store(sites); + install131(sites, "acme"); + + assertEquals(List.of("launch", "no-author", "hello-world", "draft-post"), + store.list("acme").stream().map(BlogEntry::id).toList(), + "all four, newest publication date first, undated last"); + + BlogEntry hello = store.read("acme", "hello-world").orElseThrow(); + assertEquals(Map.of("en", "Hello world", "es", "Hola mundo"), hello.title()); + assertEquals(Map.of("en", "The very first post.", "es", "La primera entrada."), hello.description()); + assertEquals(List.of("en", "es"), hello.locales()); + assertEquals(Map.of("es", "hola-mundo"), hello.localizedSlugs()); + assertTrue(hello.published()); + assertEquals("2026-07-17", hello.publishedOn()); + assertEquals("Jane Doe", hello.author()); + assertNotNull(hello.updatedAt()); + assertEquals("# Hello\n\nSome **bold** words and a [link](/about).\n", + store.readBody("acme", "hello-world", "en")); + assertEquals(List.of("en", "es"), store.bodyLangs("acme", "hello-world")); + + BlogEntry unattributed = store.read("acme", "no-author").orElseThrow(); + assertNull(unattributed.author(), "an entry 1.3.1 wrote without an author loads unattributed"); + assertEquals("2026-08-01", unattributed.publishedOn()); + assertTrue(unattributed.published()); + + BlogEntry launch = store.read("acme", "launch").orElseThrow(); + assertEquals("v2", launch.slug()); + assertEquals("/announcing-v2", launch.customPath()); + assertEquals("Richard Roe", launch.author()); + + BlogEntry draft = store.read("acme", "draft-post").orElseThrow(); + assertFalse(draft.published()); + assertNull(draft.publishedOn()); + } + + @Test + void savingAn131EntryBackWritesTheSameBytes(@TempDir Path sites) throws IOException { + BlogStore store = store(sites); + Path entries = install131(sites, "acme"); + for (String id : List.of("hello-world", "no-author", "launch", "draft-post")) { + String before = Files.readString(entries.resolve(id).resolve("entry.yml"), StandardCharsets.UTF_8); + store.save("acme", store.read("acme", id).orElseThrow(), null); + assertEquals(before, Files.readString(entries.resolve(id).resolve("entry.yml"), StandardCharsets.UTF_8), + id + ": entry.yml is written back exactly as the 1.3.1 store wrote it"); + } + } + + @Test + void aHandWrittenEntryWithMissingAndUnknownKeysStillLoads(@TempDir Path sites) throws IOException { + BlogStore store = store(sites); + Path dir = sites.resolve("acme/plugins/blog/entries/by-hand"); + Files.createDirectories(dir); + Files.writeString(dir.resolve("entry.yml"), "title:\n en: \"By hand\"\nfutureKey: 42\n"); + BlogEntry entry = store.read("acme", "by-hand").orElseThrow(); + assertEquals("By hand", entry.title().get("en")); + assertFalse(entry.published(), "an omitted 'published:' defaults (lenient), never fails the entry"); + } + + @Test + void anEmptyEntryFileIsAbsent(@TempDir Path sites) throws IOException { + BlogStore store = store(sites); + Path dir = sites.resolve("acme/plugins/blog/entries/empty"); + Files.createDirectories(dir); + Files.writeString(dir.resolve("entry.yml"), ""); + assertTrue(store.read("acme", "empty").isEmpty()); + assertTrue(store.list("acme").isEmpty()); + } + + @Test + void updatedAtIsTheNewestFileTimeOfTheEntry(@TempDir Path sites) throws IOException { + BlogStore store = store(sites); + store.save("acme", entry("post"), Map.of("en", "body")); + Path dir = sites.resolve("acme/plugins/blog/entries/post"); + Files.setLastModifiedTime(dir.resolve("entry.yml"), FileTime.from(Instant.parse("2026-01-01T00:00:00Z"))); + Files.setLastModifiedTime(dir.resolve("body-en.md"), FileTime.from(Instant.parse("2026-03-01T00:00:00Z"))); + assertEquals(Instant.parse("2026-03-01T00:00:00Z"), store.read("acme", "post").orElseThrow().updatedAt(), + "a body-only edit moves updatedAt (and so the ETag and )"); + Files.setLastModifiedTime(dir.resolve("entry.yml"), FileTime.from(Instant.parse("2026-05-01T00:00:00Z"))); + assertEquals(Instant.parse("2026-05-01T00:00:00Z"), store.read("acme", "post").orElseThrow().updatedAt()); + } + + @Test + void aBlankBodyDeletesThatLanguagesFile(@TempDir Path sites) throws IOException { + BlogStore store = store(sites); + store.save("acme", entry("post"), Map.of("en", "text", "es", "texto")); + Map bodies = new java.util.HashMap<>(); + bodies.put("es", " "); + bodies.put("fr", null); + store.save("acme", entry("post"), bodies); + assertEquals("text", store.readBody("acme", "post", "en"), "untouched language kept"); + assertEquals("", store.readBody("acme", "post", "es"), "blanked language's file removed"); + assertEquals(List.of("en"), store.bodyLangs("acme", "post")); + } + + @Test + void deleteRemovesTheWholeEntry(@TempDir Path sites) throws IOException { + BlogStore store = store(sites); + store.save("acme", entry("gone"), Map.of("en", "x", "es", "y")); + store.save("acme", entry("kept"), Map.of("en", "z")); + store.delete("acme", "gone"); + assertTrue(store.read("acme", "gone").isEmpty()); + assertFalse(Files.exists(sites.resolve("acme/plugins/blog/entries/gone"))); + assertTrue(store.read("acme", "kept").isPresent(), "only that entry"); + store.delete("acme", "never-existed"); + store.delete("acme", "../escape"); + assertTrue(Files.isDirectory(sites.resolve("acme/plugins/blog/entries")), "unsafe ids are a no-op"); + } + + @Test + void unsafeIdsNeverTouchThePathAndUnsafeLangsThrowBeforeWriting(@TempDir Path sites) throws IOException { + BlogStore store = store(sites); + assertTrue(store.read("acme", "../escape").isEmpty(), "a traversal id is an empty read, not a probe"); + assertTrue(store.read("acme", "has:colon").isEmpty(), "':' is out — blog: must stay unambiguous"); + assertEquals("", store.readBody("acme", "x", "../en"), "a traversal lang reads empty"); + assertEquals("", store.readBody("acme", "../x", "en"), "a traversal id reads empty"); + assertEquals(List.of(), store.bodyLangs("acme", "../x")); + assertThrows(IllegalArgumentException.class, + () -> store.save("acme", entry("post"), Map.of("../en", "x")), "an unsafe lang never writes"); + assertTrue(store.read("acme", "post").isEmpty(), "…not even the metadata"); + assertThrows(IllegalArgumentException.class, () -> BlogStore.requireSafeId("Bad:Id")); + assertThrows(IllegalArgumentException.class, () -> BlogStore.requireSafeId(null)); + assertThrows(IllegalArgumentException.class, () -> store.save("acme", entry("-bad"), null)); + } + + @Test + void listSortsNewestFirstAndSkipsForeignFoldersAndFiles(@TempDir Path sites) throws IOException { + BlogStore store = store(sites); + store.save("acme", new BlogEntry("older", Map.of("en", "Old"), Map.of(), List.of("en"), null, + Map.of(), null, true, "2026-01-01", null, null), null); + store.save("acme", new BlogEntry("newer", Map.of("en", "New"), Map.of(), List.of("en"), null, + Map.of(), null, true, "2026-07-01", null, null), null); + store.save("acme", new BlogEntry("a-same-day", Map.of("en", "A"), Map.of(), List.of("en"), null, + Map.of(), null, true, "2026-07-01", null, null), null); + Files.createDirectories(sites.resolve("acme/plugins/blog/entries/.hidden-junk")); + Files.writeString(sites.resolve("acme/plugins/blog/entries/stray-file"), "x"); + Files.createDirectories(sites.resolve("acme/plugins/blog/entries/no-metadata")); + + assertEquals(List.of("a-same-day", "newer", "older"), + store.list("acme").stream().map(BlogEntry::id).toList(), + "newest publication date first, then id; non-conforming folders, files and empty folders skipped"); + } + + @Test + void aCorruptEntryIsSkippedNotFatal(@TempDir Path sites) throws IOException { + BlogStore store = store(sites); + store.save("acme", entry("good"), Map.of("en", "fine")); + Path corrupt = sites.resolve("acme/plugins/blog/entries/broken"); + Files.createDirectories(corrupt); + Files.writeString(corrupt.resolve("entry.yml"), "title: [unclosed"); + assertEquals(List.of("good"), store.list("acme").stream().map(BlogEntry::id).toList()); + assertTrue(store.read("acme", "broken").isEmpty()); + } + + @Test + void aSymlinkedEntryFolderCannotLeadOutOfTheSubtree(@TempDir Path sites) throws IOException { + BlogStore store = store(sites); + store.save("acme", entry("good"), Map.of("en", "fine")); + // Another site's data, reached through a link planted inside acme's blog folder. + store.save("globex", entry("secret"), Map.of("en", "globex only")); + Files.createSymbolicLink(sites.resolve("acme/plugins/blog/entries/secret"), + sites.resolve("globex/plugins/blog/entries/secret")); + assertEquals(List.of("good"), store.list("acme").stream().map(BlogEntry::id).toList(), + "a link is never listed"); + assertThrows(IllegalArgumentException.class, () -> store.read("acme", "secret"), + "reading through the link is refused by the kernel's real-path rule"); + } + + @Test + void sitesAreIsolated(@TempDir Path sites) throws IOException { + BlogStore store = store(sites); + store.save("acme", entry("post"), Map.of("en", "acme text")); + assertTrue(store.list("globex").isEmpty()); + assertEquals("", store.readBody("globex", "post", "en")); + } + + @Test + void aSiteWithNoBlogFolderListsNothing(@TempDir Path sites) throws IOException { + assertTrue(store(sites).list("acme").isEmpty()); + } +} diff --git a/plugins/blog/src/test/java/mx/quest/blog/TemplateHarness.java b/plugins/blog/src/test/java/mx/quest/blog/TemplateHarness.java new file mode 100644 index 0000000..83843f1 --- /dev/null +++ b/plugins/blog/src/test/java/mx/quest/blog/TemplateHarness.java @@ -0,0 +1,86 @@ +package mx.quest.blog; + +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.Locale; +import java.util.Map; +import java.util.stream.Stream; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.context.support.ReloadableResourceBundleMessageSource; +import org.springframework.core.convert.support.DefaultConversionService; +import org.thymeleaf.context.Context; +import org.thymeleaf.spring6.SpringTemplateEngine; +import org.thymeleaf.spring6.expression.ThymeleafEvaluationContext; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.FileTemplateResolver; + +/** + * Renders this plugin's SHIPPED templates ({@code templates/*.html} + their decoupled {@code .th.xml} logic) with + * Thymeleaf's own Spring engine — no kernel class. The templates are copied under the logical names the kernel uses + * ({@code __plugin__/blog/}), a site master can be added next to them, and {@code #{…}} resolves from this + * plugin's own bundles ({@code i18n/messages*.properties}), as the kernel appends them. + * + *

What this cannot see is anything the kernel adds beyond the documented render model — which is the point: a + * template that renders here needs nothing but the contract. + */ +final class TemplateHarness { + + private final Path root; + private final SpringTemplateEngine engine; + + TemplateHarness(Path root) { + this.root = root; + try { + Path target = root.resolve("__plugin__/blog"); + Files.createDirectories(target); + try (Stream files = Files.list(Path.of("templates"))) { + for (Path file : files.toList()) { + Files.copy(file, target.resolve(file.getFileName().toString())); + } + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + FileTemplateResolver resolver = new FileTemplateResolver(); + resolver.setPrefix(root.toAbsolutePath() + "/"); + resolver.setSuffix(".html"); + resolver.setTemplateMode(TemplateMode.HTML); + resolver.setCharacterEncoding("UTF-8"); + resolver.setUseDecoupledLogic(true); + resolver.setCacheable(false); + ReloadableResourceBundleMessageSource messages = new ReloadableResourceBundleMessageSource(); + messages.setBasename("file:" + Path.of("i18n/messages").toAbsolutePath()); + messages.setDefaultEncoding("UTF-8"); + messages.setFallbackToSystemLocale(false); + engine = new SpringTemplateEngine(); + engine.setTemplateResolver(resolver); + engine.setTemplateEngineMessageSource(messages); + } + + /** Writes a site master ({@code .html} + an empty logic file) and returns its logical name. */ + String master(String name, String html) { + try { + Path file = root.resolve(name + ".html"); + Files.createDirectories(file.getParent()); + Files.writeString(file, html, StandardCharsets.UTF_8); + Files.writeString(root.resolve(name + ".th.xml"), "", + StandardCharsets.UTF_8); + return name; + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + String render(String template, Locale locale, Map vars) { + GenericApplicationContext app = new GenericApplicationContext(); + app.refresh(); + Context ctx = new Context(locale); + vars.forEach(ctx::setVariable); + ctx.setVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME, + new ThymeleafEvaluationContext(app, DefaultConversionService.getSharedInstance())); + return engine.process(template, ctx); + } +} diff --git a/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/draft-post/body-en.md b/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/draft-post/body-en.md new file mode 100644 index 0000000..cb452bf --- /dev/null +++ b/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/draft-post/body-en.md @@ -0,0 +1 @@ +Not yet. diff --git a/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/draft-post/entry.yml b/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/draft-post/entry.yml new file mode 100644 index 0000000..512e0f6 --- /dev/null +++ b/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/draft-post/entry.yml @@ -0,0 +1,8 @@ +--- +title: + en: "Work in progress" +description: {} +locales: +- "en" +localizedSlugs: {} +published: false diff --git a/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/hello-world/body-en.md b/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/hello-world/body-en.md new file mode 100644 index 0000000..1006f4d --- /dev/null +++ b/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/hello-world/body-en.md @@ -0,0 +1,3 @@ +# Hello + +Some **bold** words and a [link](/about). diff --git a/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/hello-world/body-es.md b/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/hello-world/body-es.md new file mode 100644 index 0000000..aa5af2c --- /dev/null +++ b/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/hello-world/body-es.md @@ -0,0 +1,3 @@ +# Hola + +Unas palabras **en negrita**. diff --git a/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/hello-world/entry.yml b/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/hello-world/entry.yml new file mode 100644 index 0000000..bdc8682 --- /dev/null +++ b/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/hello-world/entry.yml @@ -0,0 +1,15 @@ +--- +title: + es: "Hola mundo" + en: "Hello world" +description: + es: "La primera entrada." + en: "The very first post." +locales: +- "en" +- "es" +localizedSlugs: + es: "hola-mundo" +published: true +publishedOn: "2026-07-17" +author: "Jane Doe" diff --git a/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/launch/body-en.md b/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/launch/body-en.md new file mode 100644 index 0000000..b55e30c --- /dev/null +++ b/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/launch/body-en.md @@ -0,0 +1 @@ +Version two is here. diff --git a/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/launch/entry.yml b/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/launch/entry.yml new file mode 100644 index 0000000..78f557c --- /dev/null +++ b/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/launch/entry.yml @@ -0,0 +1,12 @@ +--- +title: + en: "Announcing v2" +description: {} +locales: +- "en" +slug: "v2" +localizedSlugs: {} +customPath: "/announcing-v2" +published: true +publishedOn: "2026-09-10" +author: "Richard Roe" diff --git a/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/no-author/body-en.md b/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/no-author/body-en.md new file mode 100644 index 0000000..537dfae --- /dev/null +++ b/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/no-author/body-en.md @@ -0,0 +1 @@ +Written before bylines existed. diff --git a/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/no-author/entry.yml b/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/no-author/entry.yml new file mode 100644 index 0000000..dd6a502 --- /dev/null +++ b/plugins/blog/src/test/resources/fixtures/blog-1.3.1/entries/no-author/entry.yml @@ -0,0 +1,10 @@ +--- +title: + en: "Unattributed" +description: + en: "Nobody signed this." +locales: +- "en" +localizedSlugs: {} +published: true +publishedOn: "2026-08-01" diff --git a/plugins/blog/templates/admin-edit.html b/plugins/blog/templates/admin-edit.html new file mode 100644 index 0000000..9dcf67f --- /dev/null +++ b/plugins/blog/templates/admin-edit.html @@ -0,0 +1,96 @@ + + +Blog entry + +

+ + + + + +
+ + +
+

Entry

+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+
+
+ + +
+
+

en

+
+ +
+
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+
+ + +
+
+ + diff --git a/plugins/blog/templates/admin-edit.th.xml b/plugins/blog/templates/admin-edit.th.xml new file mode 100644 index 0000000..2ac3f19 --- /dev/null +++ b/plugins/blog/templates/admin-edit.th.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/blog/templates/admin-list.html b/plugins/blog/templates/admin-list.html new file mode 100644 index 0000000..b0ad510 --- /dev/null +++ b/plugins/blog/templates/admin-list.html @@ -0,0 +1,63 @@ + + +Blog + +
+ + + + +
+
+ + + + + + + + + + + + + + + + + + + + + + +
EntryPathLanguagesDateStatusActions
No entries yet.
id———status +
+ Edit +
+ + +
+
+ + +
+
+
+
+
+
+ + diff --git a/plugins/blog/templates/admin-list.th.xml b/plugins/blog/templates/admin-list.th.xml new file mode 100644 index 0000000..a6811d9 --- /dev/null +++ b/plugins/blog/templates/admin-list.th.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/blog/templates/entry-classic.html b/plugins/blog/templates/entry-classic.html new file mode 100644 index 0000000..ea36bd7 --- /dev/null +++ b/plugins/blog/templates/entry-classic.html @@ -0,0 +1,31 @@ + + + + + Blog entry + + + + + +
+
+
+

Entry title

+ +
+
+

The entry body renders here.

+
+ +
+
+ +
Site footer (from the master at render)
+ + diff --git a/plugins/blog/templates/entry-classic.th.xml b/plugins/blog/templates/entry-classic.th.xml new file mode 100644 index 0000000..994eb8a --- /dev/null +++ b/plugins/blog/templates/entry-classic.th.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + diff --git a/plugins/blog/templates/entry-minimal.html b/plugins/blog/templates/entry-minimal.html new file mode 100644 index 0000000..ec58471 --- /dev/null +++ b/plugins/blog/templates/entry-minimal.html @@ -0,0 +1,22 @@ + + + + + Blog entry + + + + + +
+
+

Entry title

+
+

The entry body renders here.

+
+
+
+ +
Site footer (from the master at render)
+ + diff --git a/plugins/blog/templates/entry-minimal.th.xml b/plugins/blog/templates/entry-minimal.th.xml new file mode 100644 index 0000000..594be7b --- /dev/null +++ b/plugins/blog/templates/entry-minimal.th.xml @@ -0,0 +1,11 @@ + + + + + + + + + + diff --git a/plugins/carousel-manager/CHANGELOG.md b/plugins/carousel-manager/CHANGELOG.md new file mode 100644 index 0000000..cb1f69f --- /dev/null +++ b/plugins/carousel-manager/CHANGELOG.md @@ -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 `carousel-manager`: an image/slide carousel content widget — slides configured per site, +placed on any page with a `data-widget` anchor; self-contained CSS and JavaScript, no external libraries. Requires SPI `1.0.0` (Runway `1.0.0` or later). Licensed under the GNU AGPL v3.0 with an additional permission for +plugins (`LICENSE`, `LICENSE-EXCEPTION`). diff --git a/plugins/carousel-manager/LICENSE b/plugins/carousel-manager/LICENSE new file mode 100644 index 0000000..dba13ed --- /dev/null +++ b/plugins/carousel-manager/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/plugins/carousel-manager/LICENSE-EXCEPTION b/plugins/carousel-manager/LICENSE-EXCEPTION new file mode 100644 index 0000000..b634521 --- /dev/null +++ b/plugins/carousel-manager/LICENSE-EXCEPTION @@ -0,0 +1,44 @@ +Runway — additional permission for plugins +(an additional permission under section 7 of the GNU Affero General Public License, version 3) + +Copyright (C) 2026 Quest ICT SAS de CV + +Runway is free software: you can redistribute it and/or modify it under the terms of the +GNU Affero General Public License as published by the Free Software Foundation, version 3 +(the file LICENSE), with the additional permission below. Runway is distributed in the hope +that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public +License for more details. + +1. Definitions + + "Runway" means the Runway kernel and every Runway plugin whose source carries this file. + + "Published SPI" means the public classes and interfaces of the runway-spi artifact + (the package mx.quest.runway.spi and its subpackages), together with the public classes + and interfaces of any package named "spi" that a part of Runway publishes for other + plugins to use (for example mx.quest.search.spi). + + "Plugin" means an independent module that Runway loads as a plugin, that interacts with + Runway only through the Published SPI, and that is not based on any part of Runway other + than the Published SPI. + +2. Permission + + As an additional permission, the copyright holder gives you permission to combine Runway + with Plugins, and to convey and run the resulting combination, without the terms of the + GNU Affero General Public License applying to those Plugins. You may license, convey and + run your Plugins under terms of your choice, provided that you continue to meet the terms + of the GNU Affero General Public License for Runway itself, including offering the + Corresponding Source of Runway, and of any modification you make to it, as that license + requires. + +3. Testing + + Compiling a Plugin's tests against the runway-spi-testkit artifact, and running them, does + not by itself make the Plugin subject to the GNU Affero General Public License. + +4. Modified versions + + If you modify Runway, you may extend this additional permission to your version, but you + are not obliged to do so. If you do not wish to, delete this file from your version. diff --git a/plugins/carousel-manager/README.md b/plugins/carousel-manager/README.md new file mode 100644 index 0000000..322e022 --- /dev/null +++ b/plugins/carousel-manager/README.md @@ -0,0 +1,39 @@ +# Runway Carousel Manager plugin + +An image/slide **carousel** content widget for [Runway](../README.md): configure slides per site, then drop the +carousel onto any page with a `data-widget` anchor. Self-contained CSS + JS, no external libraries. + +- **Plugin id:** `carousel-manager` — install folder `external/plugins/carousel-manager/` +- **Java package:** `mx.quest.carousel` · **SPI:** `ContentWidget` (`key = "carousel"`) and the service + `PluginSettings` — it links **only the SPI**, no kernel class +- **Version 2.1.0** · built against Runway 1.0.0; needs a kernel whose SPI is **1.0.0 or later** + (`requiresSpi: ">=1.0.0"`; an older kernel blocks it with a reason). What changed: [`CHANGELOG.md`](CHANGELOG.md). + +## Use it + +1. On the carousel settings page, add slides (one per line): `imageUrl | caption | link`. +2. Put an anchor on a page: `
`. + +Settings: auto-advance interval (0 = off), show captions, show controls. See +[`docs/CAROUSEL-PLUGIN.md`](docs/CAROUSEL-PLUGIN.md). + +> Note: this plugin does not yet declare a `widgetSettings:` schema, so the host's per-placement widget config +> (`/__admin/widgets`) does not apply to it and every `carousel/*` anchor on a site shows the same configured +> slides (one carousel per site). + +## Build + +```bash +export JAVA_HOME=/path/to/jdk-25 +mvn -q verify # jar + target/carousel-manager/ + the .zip +HOST_JAR=/path/to/runway-app--exec.jar scripts/verify-against-host.sh # boot a packaged host with it +``` + +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. + +## License + +GNU Affero General Public License v3.0 with an additional permission for plugins (`LICENSE`, `LICENSE-EXCEPTION`), +copyright Quest ICT SAS de CV. The permission means that a plugin which uses only the published SPI may carry any +license. diff --git a/plugins/carousel-manager/docs/CAROUSEL-PLUGIN.md b/plugins/carousel-manager/docs/CAROUSEL-PLUGIN.md new file mode 100644 index 0000000..50fce43 --- /dev/null +++ b/plugins/carousel-manager/docs/CAROUSEL-PLUGIN.md @@ -0,0 +1,83 @@ +# Runway Carousel Manager — design & reference + +> The reference for a **`ContentWidget`** plugin with **per-tenant content config** and bundled +> front-end assets. Grounded in the Runway kernel as built. + +## 1. What it does + +A `ContentWidget` (`key = "carousel"`) that renders an image carousel from the site's per-tenant configuration +wherever a page carries `
`. It emits self-contained markup that pulls +in its own stylesheet and script (`/__plugin/carousel-manager/static/carousel.{css,js}`); the JS handles +auto-advance, prev/next, and pause-on-hover, and is idempotent so multiple carousels on a page don't double-bind. +With no slides configured the widget renders nothing. + +## 2. Configuration (per-tenant, applied immediately) + +| Key | Type | Default | Notes | +|---|---|---|---| +| `slides` | **text** | — | One slide per line: `imageUrl \| caption \| link`. `text` (not `list`) so a caption with a comma survives. Image required; caption/link optional. | +| `intervalSeconds` | int (0–60) | `5` | Auto-advance interval; `0` disables auto-play. | +| `showCaptions` | boolean | `true` | Overlay captions on slides. | +| `showControls` | boolean | `true` | Show prev/next controls (only when >1 slide). | + +Read live through the SPI service **`PluginSettings.site(siteId)`**, which answers a `SettingsView`: the +descriptor defaults above overlaid by what the site saved. A save applies immediately (the host evicts the cached +view on every node). The code fallbacks equal the descriptor defaults, so the widget renders the same either way; +`intervalSeconds` is clamped to `0..60`; a hand-edited value that does not parse falls back to the default. The +`settings` control point gates the editor. Every emitted value (image URL, caption, link) is HTML-escaped by +`Html.escape`. + +## 3. One slide set per site (documented) + +The host supports per-placement widget config (a `widgetSettings:` schema in `plugin.yml`, edited per anchor at +`/__admin/widgets`, delivered in `WidgetView.config()`), but this plugin does not declare a schema yet — so +`config()` is empty for it and every `carousel/*` anchor on a site renders the **same** configured slides from the +flat per-tenant `siteSettings` (one carousel per site). Distinct carousels per placement need this plugin to +declare a `widgetSettings:` schema and read `config()`; the widget already threads `instanceId` through for that. + +## 4. Inventory + +| Piece | Type | File | +|---|---|---| +| `mainClass` `@Configuration` | `CarouselConfig` | wires the widget (`carouselManagerWidget`) + admin model (`carouselManagerAdminModel`), each given the injected `PluginSettings` | +| Widget | `CarouselWidget` (`ContentWidget` `carousel`) | parse slides → render markup | +| Slide model | `Slide` | parse `imageUrl \| caption \| link` | +| Console model | `CarouselAdminModel` + `templates/` | dashboard card + admin status, read as `${@carouselManagerAdminModel.slideCount(tenantSiteId)}` | +| Front-end | `static/carousel.css`, `static/carousel.js`, `static/carousel-help.html` | self-contained assets | +| i18n (EN/ES) | `i18n/` | settings + console labels | + +## 5. What it links: the SPI only + +The plugin's compiled classes reference nothing of the kernel outside `mx.quest.runway.spi`, which is the contract +the Runway kernel enforces (its loader refuses a non-essential plugin that links host classes). Concretely: + +- **Settings:** `mx.quest.runway.spi.service.PluginSettings`, injected as a `@Bean` method parameter of + `CarouselConfig`. The host binds it to `carousel-manager` by the jar `CarouselConfig` was loaded from — no id is + passed, so the plugin can only read its own settings. +- **Bean names** start with the plugin id in lowerCamelCase (`carouselManager…`): plugins share the host's bean + namespace, and the kernel refuses other names. +- **Descriptor:** `requiresSpi: ">=1.0.0"` — the plugin is built against the Runway 1.0.0 SPI. An older kernel + blocks the plugin with a reason rather than failing to wire it. +- **Build:** `pom.xml` depends on `runway-spi` (and `runway-spi-testkit` for tests), never on `runway-app`, so a + host import does not compile. `CarouselConfigTest` also scans the compiled classes' constant pools for any + `mx/quest/runway/` name outside `spi/`, checks every bean name's prefix, and checks that every + `${@bean…}` the templates use is one of the plugin's own beans. + +## 6. Verify + +`HOST_JAR=… scripts/verify-against-host.sh` builds the plugin offline (run `mvn verify` once first, so that its +dependencies are in the local Maven repository), boots the packaged host (wizard, then ACTIVE) with it installed, +and asserts: + +- it loads — `plugins: 1 registered, 0 blocked` — with **zero** host-linkage findings and zero + bean-name/surface findings, and no WARN/ERROR line names it; +- it serves its static assets; +- signed in as the site owner, a slide set saved on its settings page is counted on the status fragment and + on the dashboard card, and renders (both slides, the comma caption intact, the saved interval) on the seeded + About page, into which the script plants a `data-widget="carousel/hero"` anchor before the ACTIVE boot. + +Without `HOST_JAR` it takes the jar matching the host pom's version from the `runway-app/target` of the kernel +this plugin sits in (`HOST_TARGET` names another build directory); `JAVA_HOME` must name a JDK 25 and `MVN` names +Maven (default: `mvn` on the PATH). It never runs `mvn install`. `VERIFY_TMPDIR` sets where the throwaway deployment goes, `VERIFY_LOG_DIR` keeps the host +logs. The widget's rendering rules (parsing, escaping, flags, clamping, defaults, per-site isolation) are covered +by `CarouselWidgetTest`. Never `spring-boot:run`. diff --git a/plugins/carousel-manager/i18n/messages.properties b/plugins/carousel-manager/i18n/messages.properties new file mode 100644 index 0000000..eb8c726 --- /dev/null +++ b/plugins/carousel-manager/i18n/messages.properties @@ -0,0 +1,19 @@ +# Runway Carousel Manager plugin — English strings. + +# Grantable permission (permissions matrix label) +carousel.perm.settings=Configure carousel + +# Per-tenant settings form labels +carousel.set.slides=Slides (one per line: imageUrl | caption | link) +carousel.set.interval=Auto-advance seconds (0 = off) +carousel.set.captions=Show captions +carousel.set.controls=Show previous/next controls + +# Dashboard card +carousel.card.title=Carousel +carousel.card.slides=slides + +# Admin status fragment +carousel.admin.title=Carousel status +carousel.admin.slides=Configured slides +carousel.admin.help=Carousel help & reference diff --git a/plugins/carousel-manager/i18n/messages_es.properties b/plugins/carousel-manager/i18n/messages_es.properties new file mode 100644 index 0000000..8f8e7c9 --- /dev/null +++ b/plugins/carousel-manager/i18n/messages_es.properties @@ -0,0 +1,19 @@ +# Runway Carousel Manager plugin — cadenas en español. + +# Permiso otorgable (etiqueta de la matriz de permisos) +carousel.perm.settings=Configurar carrusel + +# Etiquetas del formulario de configuración por sitio +carousel.set.slides=Diapositivas (una por línea: urlImagen | leyenda | enlace) +carousel.set.interval=Segundos de avance automático (0 = desactivado) +carousel.set.captions=Mostrar leyendas +carousel.set.controls=Mostrar controles anterior/siguiente + +# Tarjeta del panel +carousel.card.title=Carrusel +carousel.card.slides=diapositivas + +# Fragmento de estado (admin) +carousel.admin.title=Estado del carrusel +carousel.admin.slides=Diapositivas configuradas +carousel.admin.help=Ayuda y referencia del carrusel diff --git a/plugins/carousel-manager/plugin.yml b/plugins/carousel-manager/plugin.yml new file mode 100644 index 0000000..85bbff4 --- /dev/null +++ b/plugins/carousel-manager/plugin.yml @@ -0,0 +1,35 @@ +# ============================================================================= +# Runway Carousel Manager plugin — descriptor +# An image/slide carousel a site manager configures per site and drops onto any +# page with a data-widget anchor. Content widget + per-tenant slide config. +# The install folder name MUST equal this `id`: external/plugins/carousel-manager/. +# ============================================================================= +id: carousel-manager +name: Carousel Manager +version: 2.1.0 + +# The @Configuration registered before refresh. Package mx.quest.carousel lives OUTSIDE mx.quest.runway. +mainClass: mx.quest.carousel.CarouselConfig + +# Built against the Runway 1.0.0 SPI (service tier: PluginSettings). A kernel below SPI 1.0.0 BLOCKS this +# plugin at startup with a reason, instead of failing to wire it (no PluginSettings bean to inject). +requiresSpi: ">=1.0.0" + +# No hard dependency (always loads); NOT essential. + +# --- Grantable control-point permission (gates the per-tenant slide editor) ------------------------------ +permissions: + - { id: settings, realm: tenant, label: carousel.perm.settings, defaultRoles: [] } + +# --- Per-tenant settings (tenant-owned content; over sites//plugins/carousel-manager.yml) ------------ +# `slides` is a `text` (verbatim, multi-line) field — one "imageUrl | caption | link" per line — NOT a +# `list`, whose comma-splitting would break a caption containing a comma. +siteSettings: + - { key: slides, type: text, label: carousel.set.slides } + - { key: intervalSeconds, type: int, default: 5, range: "0..60", label: carousel.set.interval } + - { key: showCaptions, type: boolean, default: true, label: carousel.set.captions } + - { key: showControls, type: boolean, default: true, label: carousel.set.controls } + +# --- Tenant dashboard card (fragment resolves to __plugin__/carousel-manager/dashboard) ------------------ +dashboardCards: + - { realm: tenant, order: 50, fragment: dashboard, permission: "carousel-manager|settings" } diff --git a/plugins/carousel-manager/pom.xml b/plugins/carousel-manager/pom.xml new file mode 100644 index 0000000..271a102 --- /dev/null +++ b/plugins/carousel-manager/pom.xml @@ -0,0 +1,146 @@ + + + 4.0.0 + + + + org.springframework.boot + spring-boot-starter-parent + 4.0.6 + + + + mx.quest + runway-plugin-carousel-manager + 2.1.0 + jar + Runway Carousel Manager Plugin + + + GNU Affero General Public License v3.0, with the Runway additional permission for plugins + https://www.gnu.org/licenses/agpl-3.0.txt + repo + See LICENSE and LICENSE-EXCEPTION. + + + + An image/slide carousel content widget for Runway: a site manager configures slides per site and drops + the carousel onto any page with a data-widget anchor. Self-contained CSS + JS, no external libraries. + + + + 25 + 25 + UTF-8 + + 2026-10-21T18:56:00Z + 1.0.0 + + + + + mx.quest + runway-spi + ${runway.version} + + + + mx.quest + runway-spi-testkit + ${runway.version} + test + + + org.springframework.boot + spring-boot-starter + provided + + + org.springframework.boot + spring-boot-starter-test + test + + + + + runway-plugin-carousel-manager + + + maven-antrun-plugin + + + assemble-plugin-folder + package + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/carousel-manager/scripts/verify-against-host.sh b/plugins/carousel-manager/scripts/verify-against-host.sh new file mode 100755 index 0000000..e8ea1c7 --- /dev/null +++ b/plugins/carousel-manager/scripts/verify-against-host.sh @@ -0,0 +1,134 @@ +#!/usr/bin/env bash +# Build this plugin, drop it into a throwaway Runway deployment, boot the PACKAGED host in ACTIVE mode, and +# smoke-test it end to end: it loads with ZERO host-linkage and bean-name/surface findings (the SPI 1.0.0 +# contract), serves its static assets, and — signed in as the site owner — a slide set saved on its settings +# page shows on the console card and renders on a page carrying a data-widget anchor (the anchor is planted in +# the seeded About page before the ACTIVE boot). 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--exec.jar the kernel to verify against (default: the HOST_TARGET jar +# MATCHING the host pom's version) +# VERIFY_TMPDIR=/dir where the throwaway deployment goes (default: $TMPDIR or /tmp) +# VERIFY_LOG_DIR=/dir keep copies of the host's wizard/ACTIVE logs there (evidence) +# The script never runs `mvn install` (nothing is written to ~/.m2): it packages this plugin offline against +# whatever runway-spi is already in the local repository. +set -uo pipefail + +HERE="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)" +# JAVA_HOME must name a JDK 25. MVN (default: `mvn` on the PATH) and HOST_TARGET (default: see above) can be set in the environment. +if [ -z "${JAVA_HOME:-}" ] || [ ! -x "$JAVA_HOME/bin/java" ]; then echo "set JAVA_HOME to a JDK 25"; exit 2; fi +export JAVA_HOME +JAVA="$JAVA_HOME/bin/java" +MVN="${MVN:-mvn}" +# Default host: the kernel at the root of the repository this plugin sits in (plugins//), 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=Carousel-Admin-2026; SITE_USER=owner; SITE_PW=Carousel-Site-2026 +[ -n "$PORT" ] || PORT="$(python3 -c 'import socket;s=socket.socket();s.bind(("",0));print(s.getsockname()[1]);s.close()')" +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:.*\(.*\).*:\1:p' "$HOST_TARGET/../pom.xml" | head -1)" + JAR="$HOST_TARGET/runway-app-$HOST_VERSION-exec.jar" +fi +[ -f "$JAR" ] || { echo "no host exec jar $JAR — build the host (mvn -pl runway-app package) or set HOST_JAR"; exit 1; } +echo "[verify] host jar: $JAR" + +SCRATCH="$(mktemp -d "${VERIFY_TMPDIR:-${TMPDIR:-/tmp}}/carousel-verify.XXXXXX")" +cleanup() { + [ -z "${VERIFY_LOG_DIR:-}" ] || { mkdir -p "$VERIFY_LOG_DIR" && cp "$SCRATCH"/*.log "$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 +mkdir -p "$SCRATCH/external/plugins" +cp -r "$HERE/target/carousel-manager" "$SCRATCH/external/plugins/carousel-manager" + +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="$SCRATCH/external" ) >"$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 + +# A page carrying the widget anchor: the seeded About page, edited on disk before the ACTIVE boot reads it. +ABOUT="$SCRATCH/external/sites/default/templates/about.html" +[ -f "$ABOUT" ] || { echo "the wizard did not seed $ABOUT"; exit 1; } +sed -i 's|
|
|' "$ABOUT" + +echo "[verify] booting host (ACTIVE) ..." +boot "$SCRATCH/active.log" +wait_for "$SCRATCH/active.log" "Started RunwayApplication" 90 || { echo "ACTIVE did not start"; tail -20 "$SCRATCH/active.log"; exit 1; } + +LOG="$SCRATCH/active.log" +echo "== plugin load (SPI 1.0.0 contract) ==" +ck "plugin registered, 0 blocked" "grep -qE 'plugins: 1 registered, 0 blocked' '$LOG'" +ck "not blocked / quarantined" "! grep -qE \"plugin 'carousel-manager' is blocked|plugin-quarantine\" '$LOG'" +# Host linkage and the surface rules: the kernel BLOCKS such a plugin and logs "linkage scan: " / the surface +# reason; the patterns also match the warning wording ("uses host internals", "… allowed until Runway 1.0"), so +# either form fails the check. +ck "ZERO host-linkage findings" "! grep -qE \"uses host internals|plugin 'carousel-manager' linkage scan\" '$LOG'" +ck "ZERO bean-name/surface findings" "! grep -qE \"plugin 'carousel-manager'.*(allowed until Runway 1.0|bean name|may not contribute)\" '$LOG'" +ck "no WARN/ERROR names the plugin" "! grep -E ' (WARN|ERROR) ' '$LOG' | grep -q 'carousel'" +ck "no key collision / degraded" "! grep -qiE 'collision|duplicate key|degraded' '$LOG'" + +echo "== static assets ==" +ck "carousel.css served" "curl -s -o /dev/null -w '%{http_code}' '$BASE/__plugin/carousel-manager/static/carousel.css' | grep -q 200" +ck "carousel.js served" "curl -s -o /dev/null -w '%{http_code}' '$BASE/__plugin/carousel-manager/static/carousel.js' | grep -q 200" +ck "help page served" "curl -s -o /dev/null -w '%{http_code}' '$BASE/__plugin/carousel-manager/static/carousel-help.html' | grep -q 200" + +echo "== settings → console card → widget (PluginSettings in the real host) ==" +JAR_C="$SCRATCH/cookies.txt" +SETTINGS="$BASE/__admin/plugins/carousel-manager/settings" +c() { curl -s -H 'Accept-Language: en' -c "$JAR_C" -b "$JAR_C" "$@"; } +token() { grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//'; } +ck "unconfigured: the anchor renders nothing" "! curl -s '$BASE/about' | grep -q 'rw-carousel'" +LOGIN_TOKEN="$(c "$BASE/login" | token)" +c -o /dev/null -X POST "$BASE/login" --data-urlencode "username=$SITE_USER" --data-urlencode "password=$SITE_PW" \ + --data-urlencode "_csrf=$LOGIN_TOKEN" +c "$SETTINGS" > "$SCRATCH/settings-1.html" +ck "settings page renders the status card (0 slides)" "grep -q 'id=\"ca-slides\">0<' '$SCRATCH/settings-1.html'" +c -o /dev/null -X POST "$SETTINGS" \ + --data-urlencode $'slides=/img/one.jpg | Fast, fresh | /menu\n/img/two.jpg | Second' \ + --data-urlencode "intervalSeconds=7" --data-urlencode "showCaptions=true" --data-urlencode "showControls=true" \ + --data-urlencode "_csrf=$(token < "$SCRATCH/settings-1.html")" +c "$SETTINGS" > "$SCRATCH/settings-2.html" +ck "after save: the status card counts 2 slides" "grep -q 'id=\"ca-slides\">2<' '$SCRATCH/settings-2.html'" +c "$BASE/__admin" > "$SCRATCH/dashboard.html" +ck "the dashboard card counts 2 slides" "grep -q 'id=\"cc-slides\">2<' '$SCRATCH/dashboard.html'" +curl -s "$BASE/about" > "$SCRATCH/about.html" +ck "the widget renders both slides" "grep -q 'src=\"/img/one.jpg\"' '$SCRATCH/about.html' && grep -q 'src=\"/img/two.jpg\"' '$SCRATCH/about.html'" +ck "…with the comma caption intact" "grep -q '>Fast, fresh' '$SCRATCH/about.html'" +ck "…and the saved interval" "grep -q 'data-interval=\"7\"' '$SCRATCH/about.html'" + +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" diff --git a/plugins/carousel-manager/src/main/java/mx/quest/carousel/CarouselAdminModel.java b/plugins/carousel-manager/src/main/java/mx/quest/carousel/CarouselAdminModel.java new file mode 100644 index 0000000..3fc3bde --- /dev/null +++ b/plugins/carousel-manager/src/main/java/mx/quest/carousel/CarouselAdminModel.java @@ -0,0 +1,21 @@ +package mx.quest.carousel; + +import mx.quest.runway.spi.service.PluginSettings; + +/** + * Read-only status model for the console surfaces (dashboard card + admin fragment), read by template bean name, + * e.g. {@code ${@carouselManagerAdminModel.slideCount(tenantSiteId)}}. + */ +public class CarouselAdminModel { + + private final PluginSettings settings; + + public CarouselAdminModel(PluginSettings settings) { + this.settings = settings; + } + + /** How many valid slides the site has configured (the same count the widget would render). */ + public int slideCount(String siteId) { + return CarouselWidget.slides(settings.site(siteId)).size(); + } +} diff --git a/plugins/carousel-manager/src/main/java/mx/quest/carousel/CarouselConfig.java b/plugins/carousel-manager/src/main/java/mx/quest/carousel/CarouselConfig.java new file mode 100644 index 0000000..92515a3 --- /dev/null +++ b/plugins/carousel-manager/src/main/java/mx/quest/carousel/CarouselConfig.java @@ -0,0 +1,34 @@ +package mx.quest.carousel; + +import mx.quest.runway.spi.ContentWidget; +import mx.quest.runway.spi.service.PluginSettings; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * The plugin's {@code mainClass} — the single {@code @Configuration} registered into the host context before + * refresh. Beans are wired EXPLICITLY (no {@code @ComponentScan}). The package {@code mx.quest.carousel} lives + * OUTSIDE {@code mx.quest.runway} so the host never double-scans it, and the plugin links nothing but the SPI. + * + *

Bean names start with the plugin id in lowerCamelCase ({@code carouselManager…}): plugins share the + * host's bean namespace, and the host refuses any other name. The templates read + * the admin model by that name ({@code ${@carouselManagerAdminModel…}}). + * + *

{@link PluginSettings} is injected as a {@code @Bean} method parameter of this class, which comes from the + * plugin's own jar — that is what binds the instance to {@code carousel-manager}'s settings; no id is passed. + * The {@link CarouselWidget} is a list-collected {@code ContentWidget} SPI — a plain {@code @Bean}, NEVER + * {@code @Primary}. + */ +@Configuration(proxyBeanMethods = false) +public class CarouselConfig { + + @Bean + public ContentWidget carouselManagerWidget(PluginSettings settings) { + return new CarouselWidget(settings); + } + + @Bean + public CarouselAdminModel carouselManagerAdminModel(PluginSettings settings) { + return new CarouselAdminModel(settings); + } +} diff --git a/plugins/carousel-manager/src/main/java/mx/quest/carousel/CarouselWidget.java b/plugins/carousel-manager/src/main/java/mx/quest/carousel/CarouselWidget.java new file mode 100644 index 0000000..388018e --- /dev/null +++ b/plugins/carousel-manager/src/main/java/mx/quest/carousel/CarouselWidget.java @@ -0,0 +1,104 @@ +package mx.quest.carousel; + +import java.util.ArrayList; +import java.util.List; +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.PluginSettings; + +/** + * The {@code carousel} content widget: a site manager drops + * {@code

} on a page and the host asks this widget to render an + * image carousel from the site's per-tenant configuration. It emits self-contained markup that references the + * plugin's own stylesheet and script ({@code /__plugin/carousel-manager/static/carousel.{css,js}}) — the script + * is idempotent, so multiple carousels on a page are fine. + * + *

One slide set per site: this plugin declares no {@code widgetSettings:} schema, so the host's + * per-placement config ({@code WidgetView.config()}, edited at {@code /__admin/widgets}) stays empty for it and + * every {@code carousel/*} anchor on a site renders the SAME configured slide set. Distinct carousels per + * placement need this plugin to declare such a schema and read {@code config()}; the {@code instanceId} is + * already carried through for that. With no slides configured the widget renders nothing + * ({@link RenderFragment#empty()}). + * + *

Settings come from {@link PluginSettings#site(String)}: the descriptor's {@code siteSettings:} + * defaults overlaid by what the site saved. The code fallbacks below equal the descriptor defaults + * ({@code intervalSeconds: 5}, {@code showCaptions: true}, {@code showControls: true}), so the widget renders the + * same whether or not the host applied them; {@code intervalSeconds} is clamped to the declared {@code 0..60}. + */ +public class CarouselWidget implements ContentWidget { + + private static final String STATIC = "/__plugin/carousel-manager/static"; + + private final PluginSettings settings; + + public CarouselWidget(PluginSettings settings) { + this.settings = settings; + } + + @Override + public String key() { + return "carousel"; + } + + @Override + public RenderFragment render(WidgetView view) { + SettingsView cfg = settings.site(view.site().id()); + List slides = slides(cfg); + if (slides.isEmpty()) { + return RenderFragment.empty(); + } + long interval = cfg.integer("intervalSeconds", 5, 0, 60); + boolean captions = cfg.bool("showCaptions", true); + boolean controls = cfg.bool("showControls", true); + + StringBuilder b = new StringBuilder(512); + b.append("") + .append("

"); + if (controls && slides.size() > 1) { + b.append("") + .append(""); + } + b.append("
"); + return RenderFragment.of(b.toString()); + } + + /** Parses the per-tenant {@code slides} text (one {@code imageUrl | caption | link} per line). */ + static List slides(SettingsView cfg) { + List out = new ArrayList<>(); + for (String line : cfg.string("slides", "").split("\\R")) { + Slide slide = Slide.parse(line); + if (slide != null) { + out.add(slide); + } + } + return out; + } + + @Override + public Capabilities capabilities() { + return Capabilities.of("widget.carousel"); + } +} diff --git a/plugins/carousel-manager/src/main/java/mx/quest/carousel/Html.java b/plugins/carousel-manager/src/main/java/mx/quest/carousel/Html.java new file mode 100644 index 0000000..b94c6d8 --- /dev/null +++ b/plugins/carousel-manager/src/main/java/mx/quest/carousel/Html.java @@ -0,0 +1,20 @@ +package mx.quest.carousel; + +/** + * Minimal HTML escaping for the values the carousel widget interpolates (image URLs, captions, links from the + * per-tenant config). The plugin owns escaping of its own output so a hand-entered caption or URL can never + * inject markup into a rendered page. + */ +final class Html { + + private Html() { + } + + static String escape(String value) { + if (value == null || value.isEmpty()) { + return ""; + } + return value.replace("&", "&").replace("<", "<").replace(">", ">") + .replace("\"", """).replace("'", "'"); + } +} diff --git a/plugins/carousel-manager/src/main/java/mx/quest/carousel/Slide.java b/plugins/carousel-manager/src/main/java/mx/quest/carousel/Slide.java new file mode 100644 index 0000000..b6d7ae2 --- /dev/null +++ b/plugins/carousel-manager/src/main/java/mx/quest/carousel/Slide.java @@ -0,0 +1,28 @@ +package mx.quest.carousel; + +/** + * One carousel slide, parsed from a per-tenant {@code slides} list entry of the form + * {@code imageUrl | caption | linkUrl} (caption and link optional). Immutable; all fields already trimmed and + * HTML-escaped at render time by the widget. + * + * @param imageUrl the slide image URL (required — a slide with no image is dropped) + * @param caption the optional caption text ({@code ""} if none) + * @param link the optional link the slide navigates to when clicked ({@code ""} if none) + */ +record Slide(String imageUrl, String caption, String link) { + + /** Parses one {@code imageUrl | caption | linkUrl} entry; returns {@code null} if it has no usable image. */ + static Slide parse(String entry) { + if (entry == null || entry.isBlank()) { + return null; + } + String[] parts = entry.split("\\|", 3); + String image = parts[0].strip(); + if (image.isEmpty()) { + return null; + } + String caption = parts.length > 1 ? parts[1].strip() : ""; + String link = parts.length > 2 ? parts[2].strip() : ""; + return new Slide(image, caption, link); + } +} diff --git a/plugins/carousel-manager/src/test/java/mx/quest/carousel/CarouselAdminModelTest.java b/plugins/carousel-manager/src/test/java/mx/quest/carousel/CarouselAdminModelTest.java new file mode 100644 index 0000000..ab0aeea --- /dev/null +++ b/plugins/carousel-manager/src/test/java/mx/quest/carousel/CarouselAdminModelTest.java @@ -0,0 +1,22 @@ +package mx.quest.carousel; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Map; +import mx.quest.runway.spi.testkit.FakePluginSettings; +import org.junit.jupiter.api.Test; + +/** The console status model counts the slides the widget would render, per site. */ +class CarouselAdminModelTest { + + @Test + void countsOnlyRenderableSlidesPerSite() { + FakePluginSettings settings = new FakePluginSettings() + .site("acme", Map.of("slides", "/img/a.jpg | A\n\n | no image | /x\n/img/b.jpg")) + .site("other", Map.of("slides", "/img/c.jpg")); + CarouselAdminModel model = new CarouselAdminModel(settings); + assertEquals(2, model.slideCount("acme"), "blank lines and image-less lines are not slides"); + assertEquals(1, model.slideCount("other")); + assertEquals(0, model.slideCount("unconfigured")); + } +} diff --git a/plugins/carousel-manager/src/test/java/mx/quest/carousel/CarouselConfigTest.java b/plugins/carousel-manager/src/test/java/mx/quest/carousel/CarouselConfigTest.java new file mode 100644 index 0000000..b1ba2a8 --- /dev/null +++ b/plugins/carousel-manager/src/test/java/mx/quest/carousel/CarouselConfigTest.java @@ -0,0 +1,125 @@ +package mx.quest.carousel; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import mx.quest.runway.spi.ContentWidget; +import mx.quest.runway.spi.service.PluginSettings; +import mx.quest.runway.spi.testkit.FakePluginSettings; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; + +/** + * The plugin's contract with the host, checked at build time: the wiring, the bean-name rule, the bean names the + * templates reference, the descriptor floor, and that the compiled classes link nothing of the host but the SPI — + * the same things the kernel's load-time checks refuse. + */ +class CarouselConfigTest { + + private static final String PREFIX = "carouselManager"; + + private static Set beanMethodNames() { + return Arrays.stream(CarouselConfig.class.getDeclaredMethods()) + .filter(m -> m.isAnnotationPresent(Bean.class)) + .map(Method::getName) + .collect(Collectors.toCollection(TreeSet::new)); + } + + @Test + void wiresTheWidgetAndTheAdminModelUnderPrefixedNames() { + try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) { + ctx.registerBean(PluginSettings.class, + () -> new FakePluginSettings().site("acme", Map.of("slides", "/img/a.jpg\n/img/b.jpg"))); + ctx.register(CarouselConfig.class); + ctx.refresh(); + assertInstanceOf(CarouselWidget.class, ctx.getBean("carouselManagerWidget", ContentWidget.class)); + assertEquals(2, ctx.getBean("carouselManagerAdminModel", CarouselAdminModel.class).slideCount("acme"), + "the admin model reads the injected settings"); + } + } + + @Test + void everyBeanNameStartsWithThePluginIdInLowerCamelCase() { + Set names = beanMethodNames(); + assertEquals(Set.of("carouselManagerWidget", "carouselManagerAdminModel"), names); + for (Method m : CarouselConfig.class.getDeclaredMethods()) { + Bean bean = m.getAnnotation(Bean.class); + if (bean != null) { + for (String alias : bean.name()) { + assertTrue(alias.startsWith(PREFIX), "an explicit bean name must start with " + PREFIX + ": " + alias); + } + } + } + } + + @Test + void everyBeanTheTemplatesReferenceIsOneOfOurs() throws IOException { + Set referenced = new TreeSet<>(); + try (Stream files = Files.list(Path.of("templates"))) { + for (Path file : files.filter(p -> p.toString().endsWith(".th.xml")).toList()) { + String text = Files.readString(file, StandardCharsets.UTF_8); + Matcher m = Pattern.compile("\\$\\{\\s*@(\\w+)").matcher(text); + while (m.find()) { + referenced.add(m.group(1)); + } + } + } + assertFalse(referenced.isEmpty(), "the console templates read the admin model"); + assertTrue(beanMethodNames().containsAll(referenced), "templates reference unknown beans: " + referenced); + } + + @Test + void theDescriptorDeclaresTheSpiFloorAndTheReleaseVersion() throws IOException { + String yml = Files.readString(Path.of("plugin.yml"), StandardCharsets.UTF_8); + assertTrue(yml.contains("\nrequiresSpi: \">=1.0.0\"\n"), "built for the frozen SPI 1.0.0 contract"); + String pom = Files.readString(Path.of("pom.xml"), StandardCharsets.UTF_8); + Matcher version = Pattern.compile("runway-plugin-carousel-manager\\s*([^<]+)") + .matcher(pom); + assertTrue(version.find()); + assertTrue(yml.contains("\nversion: " + version.group(1) + "\n"), "plugin.yml and pom.xml agree on the version"); + assertFalse(pom.contains("runway-app"), "no runway-app dependency in any scope"); + } + + @Test + void theCompiledClassesLinkNoHostInternals() throws IOException { + Path classes = Path.of("target", "classes"); + Pattern host = Pattern.compile("mx[/.]quest[/.]runway[/.](?!spi[/.])[\\w/.$]*"); + List problems = new ArrayList<>(); + int scanned = 0; + try (Stream 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 >= 4, "the compiled classes were found (" + scanned + ")"); + assertTrue(problems.isEmpty(), "host linkage: " + problems); + } +} diff --git a/plugins/carousel-manager/src/test/java/mx/quest/carousel/CarouselWidgetTest.java b/plugins/carousel-manager/src/test/java/mx/quest/carousel/CarouselWidgetTest.java new file mode 100644 index 0000000..2095a32 --- /dev/null +++ b/plugins/carousel-manager/src/test/java/mx/quest/carousel/CarouselWidgetTest.java @@ -0,0 +1,206 @@ +package mx.quest.carousel; + +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.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import mx.quest.runway.spi.model.PageMeta; +import mx.quest.runway.spi.model.RenderFragment; +import mx.quest.runway.spi.model.SiteView; +import mx.quest.runway.spi.model.WidgetView; +import mx.quest.runway.spi.testkit.FakePluginSettings; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * The carousel widget: slide parsing, rendering, escaping, setting gating, defaults and clamping, and the + * empty-when-unconfigured case — against the SPI testkit's {@link FakePluginSettings}, configured with the + * descriptor's real {@code siteSettings:} defaults (read from {@code plugin.yml}) the way the kernel applies them. + */ +class CarouselWidgetTest { + + private FakePluginSettings settings; + private CarouselWidget widget; + + @BeforeEach + void setUp() throws IOException { + settings = new FakePluginSettings().defaults(descriptorDefaults()); + widget = new CarouselWidget(settings); + } + + /** The {@code default:} of every {@code siteSettings:} entry in {@code plugin.yml}, typed as the kernel types them. */ + static Map descriptorDefaults() throws IOException { + String yml = Files.readString(Path.of("plugin.yml"), StandardCharsets.UTF_8); + Matcher m = Pattern.compile("\\{\\s*key:\\s*(\\w+)\\s*,\\s*type:\\s*(\\w+)[^}]*?default:\\s*([^,}]+?)\\s*[,}]") + .matcher(yml); + Map out = new LinkedHashMap<>(); + while (m.find()) { + String raw = m.group(3); + Object value = switch (m.group(2)) { + case "boolean" -> Boolean.valueOf(raw); + case "int" -> Long.valueOf(raw); + default -> raw; + }; + out.put(m.group(1), value); + } + return out; + } + + private String html(String siteId) { + SiteView site = new SiteView(siteId, "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null); + PageMeta page = new PageMeta("home", "Home", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false); + RenderFragment fragment = widget.render(new WidgetView(site, page, Locale.ENGLISH, "hero", false, Map.of())); + return fragment.isEmpty() ? "" : fragment.html(); + } + + private String render(Map stored) { + settings.site("acme", stored); + return html("acme"); + } + + private static String attr(String html, String name) { + Matcher m = Pattern.compile(name + "=\"([^\"]*)\"").matcher(html); + return m.find() ? m.group(1) : null; + } + + @Test + void keyIsCarousel() { + assertEquals("carousel", widget.key()); + } + + @Test + void rendersConfiguredSlidesWithCaptionsAndLinks() { + String html = render(Map.of("slides", "/img/a.jpg | Welcome | /about\n/img/b.jpg | Our work | /work")); + assertTrue(html.contains("src=\"/img/a.jpg\""), "first slide image"); + assertTrue(html.contains("src=\"/img/b.jpg\""), "second slide image"); + assertTrue(html.contains(">Welcome"), "caption rendered"); + assertTrue(html.contains("href=\"/about\""), "link rendered"); + assertTrue(html.contains("/__plugin/carousel-manager/static/carousel.css"), "references the plugin CSS"); + assertTrue(html.contains("/__plugin/carousel-manager/static/carousel.js"), "references the plugin JS"); + assertEquals(1, html.split("is-active", -1).length - 1, "exactly the first slide is active"); + assertTrue(html.indexOf("is-active") < html.indexOf("/img/a.jpg"), "…and it is the first one"); + } + + @Test + void anImageOnlySlideNeedsNoCaptionOrLink() { + String html = render(Map.of("slides", "/img/solo.jpg")); + assertTrue(html.contains("src=\"/img/solo.jpg\"")); + assertFalse(html.contains("Fast, fresh, local"), "the text setting is never comma-split"); + assertTrue(html.contains("src=\"/img/b.jpg\""), "a CRLF line ending separates slides"); + } + + @Test + void captionsAndControlsHonorTheirFlags() { + String noCaptions = render(Map.of("slides", "/img/a.jpg | Hi | /x\n/img/b.jpg | Yo | /y", + "showCaptions", false)); + assertFalse(noCaptions.contains("rw-carousel-caption"), "captions off ⇒ no caption element"); + assertTrue(noCaptions.contains("alt=\"Hi\""), "…the caption still serves as the image's alt text"); + String noControls = render(Map.of("slides", "/img/a.jpg\n/img/b.jpg", "showControls", false)); + assertFalse(noControls.contains("rw-carousel-next"), "controls off ⇒ no next button"); + assertEquals("false", attr(noControls, "data-controls")); + } + + @Test + void flagsStoredAsTextAreReadToo() { + String html = render(Map.of("slides", "/img/a.jpg | Hi\n/img/b.jpg", "showCaptions", "off", + "showControls", "no")); + assertFalse(html.contains("rw-carousel-caption"), "\"off\" turns captions off"); + assertFalse(html.contains("rw-carousel-next"), "\"no\" turns controls off"); + } + + @Test + void theDefaultsShowCaptionsAndControlsAndAdvanceEveryFiveSeconds() { + String html = render(Map.of("slides", "/img/a.jpg | Hi | /x\n/img/b.jpg")); + assertEquals("5", attr(html, "data-interval")); + assertEquals("true", attr(html, "data-controls")); + assertTrue(html.contains("rw-carousel-prev") && html.contains("rw-carousel-next"), "two slides ⇒ controls"); + assertTrue(html.contains("rw-carousel-caption"), "captions on by default"); + } + + @Test + void controlsNeedMoreThanOneSlide() { + String html = render(Map.of("slides", "/img/a.jpg")); + assertFalse(html.contains("rw-carousel-prev"), "a single slide has nothing to step through"); + } + + @Test + void theIntervalIsReadAndClampedToTheDeclaredRange() { + assertEquals("12", attr(render(Map.of("slides", "/img/a.jpg", "intervalSeconds", 12L)), "data-interval")); + assertEquals("12", attr(render(Map.of("slides", "/img/a.jpg", "intervalSeconds", "12")), "data-interval")); + assertEquals("0", attr(render(Map.of("slides", "/img/a.jpg", "intervalSeconds", 0L)), "data-interval"), + "0 = auto-advance off"); + assertEquals("60", attr(render(Map.of("slides", "/img/a.jpg", "intervalSeconds", 600L)), "data-interval")); + assertEquals("0", attr(render(Map.of("slides", "/img/a.jpg", "intervalSeconds", -3L)), "data-interval")); + assertEquals("5", attr(render(Map.of("slides", "/img/a.jpg", "intervalSeconds", "soon")), "data-interval"), + "an unparsable hand-edited value falls back to the default"); + } + + @Test + void codeFallbacksEqualTheDescriptorDefaults() throws IOException { + Map declared = descriptorDefaults(); + assertEquals(Map.of("intervalSeconds", 5L, "showCaptions", true, "showControls", true), declared, + "plugin.yml declares the defaults this test (and the docs) assume"); + String slides = "/img/a.jpg | Hi | /x\n/img/b.jpg | Yo"; + String withDefaults = render(Map.of("slides", slides)); + widget = new CarouselWidget(new FakePluginSettings().site("acme", Map.of("slides", slides))); + assertEquals(withDefaults, html("acme"), "the widget renders the same with or without the host's defaults"); + } + + @Test + void eachSiteRendersItsOwnSlides() { + settings.site("acme", Map.of("slides", "/img/acme.jpg")); + settings.site("other", Map.of("slides", "/img/other.jpg")); + assertTrue(html("acme").contains("/img/acme.jpg") && !html("acme").contains("/img/other.jpg")); + assertTrue(html("other").contains("/img/other.jpg") && !html("other").contains("/img/acme.jpg")); + assertTrue(html("nobody").isEmpty(), "a site with nothing saved renders nothing"); + } + + @Test + void aCraftedCaptionOrUrlIsEscaped() { + String html = render(Map.of("slides", "/img/a.jpg\" onerror=\"x | | javascript:\"x")); + assertFalse(html.contains(""), "the caption is HTML-escaped, never injected"); + assertTrue(html.contains("<script>"), "…it appears escaped"); + assertFalse(html.contains("\" onerror=\""), "an image URL cannot break out of its attribute"); + assertTrue(html.contains("src=\"/img/a.jpg" onerror="x\"")); + assertTrue(html.contains("href=\"javascript:"x\""), "the link's quote is escaped too"); + } + + @Test + void anUnsafeSiteIdIsRefusedNotRead() { + SiteView site = new SiteView("../etc", "x", Locale.ENGLISH, List.of(Locale.ENGLISH), null); + PageMeta page = new PageMeta("home", "Home", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false); + assertThrows(IllegalArgumentException.class, + () -> widget.render(new WidgetView(site, page, Locale.ENGLISH, "hero", false, Map.of())), + "the settings service refuses it; the host's containment turns that into an empty widget"); + } + + @Test + void declaresItsCapability() { + assertTrue(widget.capabilities().toString().contains("widget.carousel")); + } +} diff --git a/plugins/carousel-manager/static/carousel-help.html b/plugins/carousel-manager/static/carousel-help.html new file mode 100644 index 0000000..4882fbb --- /dev/null +++ b/plugins/carousel-manager/static/carousel-help.html @@ -0,0 +1,42 @@ + + + + + + + Carousel plugin — help & reference + + + +

Carousel — help & reference

+

The Carousel Manager plugin adds a configurable image/slide carousel you can place on any page.

+ +

1. Configure the slides

+

On the carousel settings page, fill Slides — one slide per line, fields separated by a pipe + (|):

+
/static/img/hero1.jpg | Welcome to Acme | /about
+/static/img/hero2.jpg | Our latest work  | /work
+/static/img/hero3.jpg
+

Only the image URL is required; the caption and the click-through link are optional. Other settings: the + auto-advance interval (seconds; 0 disables auto-play), whether to show captions, and whether to + show the previous/next controls.

+ +

2. Place the carousel on a page

+

Add an anchor where the carousel should appear (the id and data-widget must be on the + same element):

+
<div id="hero" data-widget="carousel/hero"></div>
+

The widget renders your configured slides there, pulling in its own stylesheet and script automatically. With + no slides configured it renders nothing.

+ +

Note: one carousel per site (for now)

+

This plugin does not yet declare a per-placement widget configuration (Runway supports one), so every + carousel/* anchor on a site shows the same configured slides. Distinct carousels per + page need that declaration in a later version — the widget already carries the instance id for it.

+ + diff --git a/plugins/carousel-manager/static/carousel.css b/plugins/carousel-manager/static/carousel.css new file mode 100644 index 0000000..cc628ac --- /dev/null +++ b/plugins/carousel-manager/static/carousel.css @@ -0,0 +1,71 @@ +/* Runway Carousel Manager — styles. Served at /__plugin/carousel-manager/static/carousel.css. + Neutral defaults so it inherits the site's look; override any .rw-carousel* rule from your own CSS. */ + +.rw-carousel { + position: relative; + overflow: hidden; + max-width: 100%; + border-radius: .5rem; + background: #000; +} + +.rw-carousel-track { + position: relative; + width: 100%; +} + +.rw-carousel-slide { + margin: 0; + display: none; +} + +.rw-carousel-slide.is-active { + display: block; +} + +.rw-carousel-img { + display: block; + width: 100%; + height: auto; + object-fit: cover; +} + +.rw-carousel-caption { + position: absolute; + left: 0; + right: 0; + bottom: 0; + margin: 0; + padding: .75rem 1rem; + color: #fff; + background: linear-gradient(transparent, rgba(0, 0, 0, .6)); + font: 500 1rem/1.3 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; +} + +.rw-carousel-link { + display: block; +} + +.rw-carousel-prev, +.rw-carousel-next { + position: absolute; + top: 50%; + transform: translateY(-50%); + border: 0; + width: 2.5rem; + height: 2.5rem; + border-radius: 50%; + background: rgba(0, 0, 0, .4); + color: #fff; + font-size: 1.5rem; + line-height: 1; + cursor: pointer; +} + +.rw-carousel-prev { left: .5rem; } +.rw-carousel-next { right: .5rem; } + +.rw-carousel-prev:hover, +.rw-carousel-next:hover { + background: rgba(0, 0, 0, .65); +} diff --git a/plugins/carousel-manager/static/carousel.js b/plugins/carousel-manager/static/carousel.js new file mode 100644 index 0000000..d0c7892 --- /dev/null +++ b/plugins/carousel-manager/static/carousel.js @@ -0,0 +1,49 @@ +/* Runway Carousel Manager — behaviour. Served at /__plugin/carousel-manager/static/carousel.js. + Idempotent: initializes every .rw-carousel not already initialized, so the widget can include this script + once per instance without double-binding. No dependencies. */ +(function () { + "use strict"; + + function init(root) { + if (root.dataset.rwInit === "1") { return; } + root.dataset.rwInit = "1"; + + var slides = Array.prototype.slice.call(root.querySelectorAll(".rw-carousel-slide")); + if (slides.length === 0) { return; } + var index = slides.findIndex(function (s) { return s.classList.contains("is-active"); }); + if (index < 0) { index = 0; } + + function show(i) { + index = (i + slides.length) % slides.length; + slides.forEach(function (s, k) { s.classList.toggle("is-active", k === index); }); + } + + var prev = root.querySelector(".rw-carousel-prev"); + var next = root.querySelector(".rw-carousel-next"); + if (prev) { prev.addEventListener("click", function () { show(index - 1); pause(); }); } + if (next) { next.addEventListener("click", function () { show(index + 1); pause(); }); } + + var interval = parseInt(root.dataset.interval, 10); + var timer = null; + function play() { + if (!(interval > 0) || slides.length < 2) { return; } + timer = window.setInterval(function () { show(index + 1); }, interval * 1000); + } + function pause() { if (timer) { window.clearInterval(timer); timer = null; } } + + root.addEventListener("mouseenter", pause); + root.addEventListener("mouseleave", play); + show(index); + play(); + } + + function scan() { + Array.prototype.forEach.call(document.querySelectorAll(".rw-carousel"), init); + } + + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", scan); + } else { + scan(); + } +})(); diff --git a/plugins/carousel-manager/templates/admin.html b/plugins/carousel-manager/templates/admin.html new file mode 100644 index 0000000..0388bbb --- /dev/null +++ b/plugins/carousel-manager/templates/admin.html @@ -0,0 +1,19 @@ + +
diff --git a/plugins/carousel-manager/templates/admin.th.xml b/plugins/carousel-manager/templates/admin.th.xml new file mode 100644 index 0000000..585625c --- /dev/null +++ b/plugins/carousel-manager/templates/admin.th.xml @@ -0,0 +1,9 @@ + + + + + + + + diff --git a/plugins/carousel-manager/templates/dashboard.html b/plugins/carousel-manager/templates/dashboard.html new file mode 100644 index 0000000..d94c1b2 --- /dev/null +++ b/plugins/carousel-manager/templates/dashboard.html @@ -0,0 +1,15 @@ + +
+
+
+
+ +
+
Carousel
+
+ 0 slides +
+
+
+
+
diff --git a/plugins/carousel-manager/templates/dashboard.th.xml b/plugins/carousel-manager/templates/dashboard.th.xml new file mode 100644 index 0000000..744a4db --- /dev/null +++ b/plugins/carousel-manager/templates/dashboard.th.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/plugins/contact/CHANGELOG.md b/plugins/contact/CHANGELOG.md new file mode 100644 index 0000000..3c11246 --- /dev/null +++ b/plugins/contact/CHANGELOG.md @@ -0,0 +1,10 @@ +# Changelog + +All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/). + +## [2.1.0] — 2026-10-21 + +First public release of `contact`: an embeddable contact-form widget whose submissions are both emailed over the +site's own SMTP relay and stored as site data for the console, with CAPTCHA (when the site has one) and a +honeypot against spam. Requires SPI `1.0.0` (Runway `1.0.0` or later). Licensed under the GNU AGPL v3.0 with an additional permission for +plugins (`LICENSE`, `LICENSE-EXCEPTION`). diff --git a/plugins/contact/LICENSE b/plugins/contact/LICENSE new file mode 100644 index 0000000..dba13ed --- /dev/null +++ b/plugins/contact/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/plugins/contact/LICENSE-EXCEPTION b/plugins/contact/LICENSE-EXCEPTION new file mode 100644 index 0000000..b634521 --- /dev/null +++ b/plugins/contact/LICENSE-EXCEPTION @@ -0,0 +1,44 @@ +Runway — additional permission for plugins +(an additional permission under section 7 of the GNU Affero General Public License, version 3) + +Copyright (C) 2026 Quest ICT SAS de CV + +Runway is free software: you can redistribute it and/or modify it under the terms of the +GNU Affero General Public License as published by the Free Software Foundation, version 3 +(the file LICENSE), with the additional permission below. Runway is distributed in the hope +that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public +License for more details. + +1. Definitions + + "Runway" means the Runway kernel and every Runway plugin whose source carries this file. + + "Published SPI" means the public classes and interfaces of the runway-spi artifact + (the package mx.quest.runway.spi and its subpackages), together with the public classes + and interfaces of any package named "spi" that a part of Runway publishes for other + plugins to use (for example mx.quest.search.spi). + + "Plugin" means an independent module that Runway loads as a plugin, that interacts with + Runway only through the Published SPI, and that is not based on any part of Runway other + than the Published SPI. + +2. Permission + + As an additional permission, the copyright holder gives you permission to combine Runway + with Plugins, and to convey and run the resulting combination, without the terms of the + GNU Affero General Public License applying to those Plugins. You may license, convey and + run your Plugins under terms of your choice, provided that you continue to meet the terms + of the GNU Affero General Public License for Runway itself, including offering the + Corresponding Source of Runway, and of any modification you make to it, as that license + requires. + +3. Testing + + Compiling a Plugin's tests against the runway-spi-testkit artifact, and running them, does + not by itself make the Plugin subject to the GNU Affero General Public License. + +4. Modified versions + + If you modify Runway, you may extend this additional permission to your version, but you + are not obliged to do so. If you do not wish to, delete this file from your version. diff --git a/plugins/contact/README.md b/plugins/contact/README.md new file mode 100644 index 0000000..0caea10 --- /dev/null +++ b/plugins/contact/README.md @@ -0,0 +1,63 @@ +# Runway Contact plugin + +A **contact form** for [Runway](../README.md): an embeddable form content widget that **POSTs** to an anonymous +`/contact/submit` route, which **both emails** each submission over the site's own SMTP relay **and stores** it as +tenant-owned data (read in the console) — belt-and-suspenders, so a message is never lost even if SMTP is down. +CAPTCHA (when the site has one) and honeypot anti-spam. + +- **Plugin id:** `contact` — install folder `external/plugins/contact/` · **version 2.1.0** +- **Java package:** `mx.quest.contact` · **SPIs:** `ContentWidget` (`contact`) + `EndpointContributor` + (`POST /contact/submit` anonymous; `POST /contact/install-page` and `POST /contact/smtp-test`, CSRF-checked) +- **Links only the Runway SPI** (`requiresSpi: ">=1.0.0"`): `PluginSettings` (settings + the SMTP password secret), + `PluginSiteFiles` (submissions), `Messages`, `AccessCheck`, `SitePages` (the starter page), `CaptchaService`. + **Needs Runway 1.0.0 or later** (SPI `1.0.0`) — a kernel with an older SPI blocks this release at startup with + a reason. See [`CHANGELOG.md`](CHANGELOG.md). +- **No plugin dependency:** Jakarta Mail is part of the **core** Runway application (the kernel bundles it for + its own platform mailer), so `contact` compiles it as `provided` and resolves the kernel's copy at runtime. + +## Use it + +1. Install `contact`, then restart the host. +2. Enable the plugin, set your thank-you message, and fill in the **SMTP relay** (host, port, auth, + username/password, STARTTLS/SSL, from/to) on the Contact settings page — the password is stored encrypted. +3. Verify the relay with **Send a test email** on the settings page (operator-only). +4. Put a form on a page: install the ready-made **Contact page** from the settings (it follows the site's + publishing rules and says what happened), or add `
` to any + page. +5. Read submissions on the Contact settings page (newest first) — a copy is kept even when email delivery fails. + +> A site with a **blank** SMTP host/recipient simply stores messages (no email) — email is optional. A site sends +> with its **own** relay only (tenant isolation). + +> **Privacy.** The form POSTs, so a visitor's fields never appear in a URL, browser history or proxy log. The +> stored submissions are declared **personal data** (`siteData.personal: [submissions.tsv]`): a site's **transfer +> copy** leaves them out (and lists the omission in its manifest); a **full backup** keeps them. See +> [`docs/CONTACT-PLUGIN.md`](docs/CONTACT-PLUGIN.md). + +## Build and verify + +```bash +export JAVA_HOME=/path/to/jdk-25 +mvn verify # 75 tests (send seam mocked — no socket) +mvn -DskipTests package # jar + target/contact/ + the .zip +HOST_JAR=/path/to/runway-app--exec.jar VERIFY_TMPDIR=/somewhere scripts/verify-against-host.sh +``` + +The first build downloads its Maven dependencies, and needs the `runway-spi` jars installed in `~/.m2` as the +[authoring guide §2](../docs/PLUGIN-AUTHORING-GUIDE.md#2-prerequisites) describes. + +The verify boots the **packaged** host with this plugin (and, when built, the protection plugin from the host +checkout), on four sites (Advisory, Enforced, Reviewed, and one with a CAPTCHA), and checks 59 things (54 without +the protection plugin): zero +host-linkage and surface warnings; an anonymous POST with no session stored and answered `303` with only an +outcome flag; GET, honeypot, invalid, query-string and multipart submissions refused; the two operator actions +CSRF-checked (a GET changes nothing, a POST without the console token is `403`); the starter page installed +on every editorial level and never twice; the SMTP password stored `ENC(...)` and handed in clear to a local fake +relay; a full backup with the submissions and a transfer copy without them; a POST without the CAPTCHA token +refused. + +## License + +GNU Affero General Public License v3.0 with an additional permission for plugins (`LICENSE`, `LICENSE-EXCEPTION`), +copyright Quest ICT SAS de CV. The permission means that a plugin which uses only the published SPI may carry any +license. diff --git a/plugins/contact/docs/CONTACT-PLUGIN.md b/plugins/contact/docs/CONTACT-PLUGIN.md new file mode 100644 index 0000000..b001c2a --- /dev/null +++ b/plugins/contact/docs/CONTACT-PLUGIN.md @@ -0,0 +1,256 @@ +# Runway Contact plugin — design & reference + +> The reference for a plugin that **accepts input from anonymous visitors**, **stores per-tenant +> personal data**, and **sends email** within the kernel's constraints (CSRF, servlet-free endpoints, tenant +> isolation, encrypted secrets) — using **only the Runway SPI** (version 2.1.0, SPI 1.0.0). Grounded in the Runway +> kernel as built. + +## 1. What it does + +- **Form widget** — a `ContentWidget` (`key = "contact"`) that renders the shared `ContactForm` inline wherever a + page carries `
`. Honors the per-tenant `enabled` flag. The plugin owns + **no visible page**: the form lives on a normal, editable site page. The widget is **query-aware** — the submit + handler redirects back with `?contact=sent|invalid|captcha|queued`, and the widget re-renders that outcome + (thank-you, or the form with an error) from the flag, so the page it sits on stays an ordinary, cacheable page. +- **`POST /contact/submit`** — an `EndpointContributor` route declared **anonymous** (`Route.anonymousPost`, §2) + that reads the fields from the url-encoded **body only**, runs the honeypot + (when configured) the CAPTCHA + check, and for a valid message **stores it AND emails it** over the site's own SMTP relay, then answers + **`303 See Other` back to the page the form lives on** (the same-origin `return` field, else the `Referer`) with + only the outcome flag. It renders nothing itself. Any other method on this path is a 404. +- **`POST /contact/install-page`** — an ordinary (CSRF-checked, §2a) route, operator-gated (`contact|settings`, + checked with `AccessCheck`; fails **closed** with a 404 otherwise): installs a ready-made, editable tenant page carrying the form widget (slug + `contact`, path `/contact`) through **`SitePages.install`**. The kernel never overwrites and follows the site's + editorial level; the plain-text answer names the outcome (§1c). Once installed it is an ordinary site page + (listed under Pages; restyle / move / rename it), so the operator, not the plugin, owns the URL and chrome. +- **`POST /contact/smtp-test`** — an operator-only diagnostic (same CSRF check and gate) that sends a test message + over the site's relay to verify the SMTP configuration — to the configured recipient, or to an optional `to` field + of the form body (never the query string). +- **Console** — a dashboard card (submission count) and an admin fragment with a **"Contact page"** card (install + the ready-made page with a button, or see its live path when already installed — read fresh with + `SitePages.pathOf`, so it follows a move and counts a draft or a page in review), the **SMTP readiness** + ("Configured / Not configured" badge + a "Send a test email" button) and a list of + **recent submissions** (name, email, message excerpt, time), gated by the `settings` control point. + +## 1a. Belt-and-suspenders: store AND send + +A valid submission is **always stored first** (`ContactStore`, tenant TSV), **then** emailed (`ContactMailer`). +The store is unconditional, so a message is **never lost** even if SMTP is down: + +- **Send OK** → stored + emailed; the visitor sees the thank-you. +- **Send FAILED** (a configured relay rejected/unreachable) → stored; the failure is logged and the visitor is + redirected with `?contact=queued`, which the widget renders as the thank-you plus an unobtrusive "message + received; email delivery is delayed" note. The relay internals + are never exposed to the visitor. +- **NOT_CONFIGURED** (blank host/recipient) → stored silently, no note — a site may legitimately choose to only + store messages and read them in the console. +- **PROVIDER_MISSING** (Jakarta Mail off the classloader) → stored; reported. The kernel bundles Jakarta Mail as + a core capability, so this is effectively unreachable, but `ContactMailer` still guards the `LinkageError` at + the send seam so the request can never crash. + +## 1b. Email over the kernel's Jakarta Mail + +The plugin compiles `jakarta.mail-api` as **`provided`** — the **kernel** bundles the Jakarta Mail + Angus stack +as a core capability (for its own platform mailer), and the plugin classloader reaches it parent-first. This +plugin **never bundles Jakarta Mail itself** (that would be a second, shadowing copy on the classloader). It +therefore needs **no `requires:`** gate. + +- The send seam is the `MailTransport` interface (`JakartaMailTransport` delegates to `jakarta.mail.Transport` in + production; mocked in tests so no socket is opened). +- `ContactMailer.build(...)` constructs a `MimeMessage` from `SmtpSettings`: From = the site's `fromAddress` (or + the recipient when blank), To = the site's `toAddress`, Reply-To = the visitor's email (so a reply reaches + them), a site-prefixed Subject, and a plain-text body. The `Session` always uses the `smtp` protocol + (implicit TLS rides `mail.smtp.ssl.enable`, STARTTLS `mail.smtp.starttls.enable`) and a static `Authenticator` + when `smtpAuth` is on. + +### Per-site SMTP settings (tenant-owned, isolated) + +All relay config is per-tenant `siteSettings` over `sites//plugins/contact.yml`, so **a site sends with its +OWN relay only** — never another tenant's: + +| key | type | notes | +|---|---|---| +| `smtpHost` | string | blank ⇒ not configured ⇒ mail skipped (stored only) | +| `smtpPort` | int (1..65535, default 25) | | +| `smtpAuth` | boolean (default false) | when on, uses username/password | +| `smtpUsername` | string | | +| `smtpPassword` | **secret** | stored `ENC(...)`-encrypted; the config file is `chmod 600`; **bound** to `smtpHost`, `smtpPort`, `smtpUsername`, `smtpStarttls`, `smtpSsl` (below) | +| `smtpStarttls` | boolean (default false) | STARTTLS upgrade on a plain connection | +| `smtpSsl` | boolean (default false) | implicit-TLS (SMTPS) | +| `fromAddress` | string | envelope From; blank ⇒ falls back to the recipient | +| `toAddress` | string | recipient; blank ⇒ not configured ⇒ mail skipped | + +Every value is read from the `SettingsView` that `PluginSettings.site(siteId)` returns (the descriptor defaults +overlaid by what the operator saved). The **secret** password is stored `ENC(...)` by the platform; the plugin +reads it in clear with **`PluginSettings.secret(siteId, "smtpPassword")`** at send time — the kernel decrypts it +(a hand-written plaintext value is returned as is) and answers empty when it is unset or cannot be decrypted (the +relay then rejects the login and the submission is reported "delivery delayed", still stored). The password is +never taken from the settings view (the kernel leaves secret keys out of it, and a test holds the plugin to that). +The plaintext lives only in the transient `SmtpSettings` value handed to Jakarta Mail — never logged +(`SmtpSettings.toString()` masks it) and never stored by this plugin. + +**The password is bound to the relay login (`secretBoundTo`).** The descriptor declares +`secretBoundTo: [smtpHost, smtpPort, smtpUsername, smtpStarttls, smtpSsl]` on `smtpPassword` (the TLS switches +too: turning TLS off toward the same host would otherwise send the stored password in clear). A settings save that +changes any of those five **without retyping the password** makes the kernel drop the stored password (the field is left blank, so the +next send fails the login and the submission is stored as "delivery delayed" until the password is entered again). +Why: the settings form never shows the stored password, but whoever may edit the settings could otherwise point the +site's saved credentials at a server of their own — change the host, keep the password, press **Send a test +email** — and read the password off the wire. Binding it means a stored password is only ever offered to the relay +login it was typed for. Retyping the password in the same save keeps it (the new value is stored). Changing any +other setting (`enabled`, the thank-you message, sender, recipient, `smtpAuth`) leaves it alone. The binding is +enforced by the kernel, which also tells the operator on the settings page when a save dropped the password. + +## 1c. The starter page and the site's editorial level + +`SitePages.install` creates the page as a draft and then applies the site's level; the endpoint reports each +`InstallResult` outcome in the operator's console language (`Messages.console`): + +| Outcome | When | The answer (EN) | +|---|---|---| +| `PUBLISHED` | Advisory; Enforced or Reviewed with the checks passing (on Reviewed, for someone who may approve pages) | `Contact page installed at /contact` | +| `PENDING_REVIEW` | Reviewed, and the operator may not approve pages | `The contact page was created and is waiting in the review queue: /contact` | +| `DRAFT_BLOCKED` | the quality checks blocked publishing | `The contact page was created as a draft because the quality checks blocked publishing; fix it in the page editor: /contact` + one `- code: message` line per blocking finding | +| `ALREADY_EXISTS` | a page with the slug `contact` exists, in any state | `A contact page already exists at ` | +| a constant added in a later SPI | — | `The contact page install finished: ` | + +A refused install (another page serves `/contact`, a write failure) answers `500` "Could not install the contact +page." and leaves no draft behind (the kernel removes it). + +## 2. POST on an anonymous route (the CSRF constraint, solved) + +A public form on a cacheable page cannot carry the tenant chain's **session-based CSRF token**. The easy way +around that — a form that submits by **GET** — would put a visitor's name, email and message in their browser +history, in `Referer` headers and in proxy logs. The SPI has a contract for exactly this case, and the plugin uses +it: + +- The endpoint declares **`Route.anonymousPost("/contact/submit", posture)`**. The kernel exempts **exactly that + method and path** from CSRF, on a site's host only, and in exchange takes away what a forged cross-site + submission could use: the handler runs with **no principal** (`AccessCheck.may` is `false` even for a signed-in + administrator), it is handed only `application/x-www-form-urlencoded` bodies (anything else is answered `415`), + and every other route keeps its CSRF check. +- The form (`ContactForm`) is `method="post"` with that encoding. The handler reads the fields **from the body + only** (`RouteRequest.form()`), so a field put in a query string is ignored and personal data has no reason to + travel in a URL; the `303` back to the page carries only `?contact=`. +- **The abuse guards stay in front of the store:** a hidden **honeypot** field (`website`; a submission that fills + it is silently dropped — the bot sees a fake success, nothing is stored or sent), the site's **CAPTCHA** when one + is configured (`CaptchaService.verify(site, token, req.clientIp())` — the client IP after the kernel's + trusted-proxy gate; the token is read from the body too), and the platform's **per-address rate limit** (the + protection plugin's edge guard, which sees every request before any endpoint). + +## 2a. The operator actions are CSRF-checked POSTs + +Installing the starter page creates a page, and the SMTP test sends an email. Were they `GET` links, a signed-in +site manager who followed a link on another web site — or merely loaded a page with an +`` — would perform the action without meaning to (the browser +sends the session cookie with the request; the permission check passes because it *is* the manager). The SMTP test +would be worse: a `?to=` choosing the recipient would let such a link make the server email an arbitrary address. + +Both are therefore **ordinary `POST` routes** — deliberately **not** `Route.anonymousPost`, which would switch the +CSRF check off. The kernel's tenant chain demands the console session's CSRF token on them: + +- the admin fragment renders each action as a `
` with a hidden `_csrf` field bound to the + request's token (`th:attr="name=${_csrf.parameterName},value=${_csrf.token}"`, the same pattern as the search + plugin's "Clear list"); the answer opens in a new tab; +- a `POST` without a valid token is refused `403` by the kernel (the "session expired" page) before the plugin runs; +- a `GET` (a link, an ``) matches no route, so the kernel answers `404` and nothing changes; the handler also + refuses any non-`POST` method itself, as a second line; +- the `contact|settings` permission check still runs after the token check (an anonymous visitor who holds a valid + session token gets `404`). + +**The body reaches the plugin whole.** The SMTP test's optional `to` override is read from the form body only, +never the query string. The kernel keeps the url-encoded body for the route after its CSRF check, so `form()` +carries every field whether the token travels as the `_csrf` form field — as a browser form sends it — or in the +`X-CSRF-TOKEN` header. The console's SMTP-test button sends no `to`, so it always mails the configured recipient; +the override is for a scripted call. + +## 3. Storage (tenant-owned, backup-safe) + +Submissions go through the kernel's **`PluginSiteFiles`** (this plugin's per-site folder, bound to the plugin by +its jar; the kernel confines every path to `sites//plugins/contact/`, real path included) to +`sites//plugins/contact/submissions.tsv` (an existing file is read and appended in place, so stored +submissions survive an upgrade of the plugin): + +- **Outside** the served `static/` tree — never publicly downloadable (the verify asserts a traversal attempt on + it does not return 200). +- **Inside** the tenant folder — so a **full backup** carries it automatically; no `BackupParticipant` needed. +- **Declared personal data** in `plugin.yml` (`siteData: personal: [submissions.tsv]`): a **transfer copy** of the + site (the console's "Download a transfer copy") leaves it out and lists `plugins/contact/submissions.tsv` under + `omitted:` in the archive's `manifest.yml`. A restored transfer copy starts with no submissions, which the store + reads as empty. +- One **sanitized** TSV line per submission (`epochMillis \t name \t email \t message`; tabs/newlines stripped so + the format is unambiguous, fields length-capped at 4,000 characters), bounded to the most recent + `MAX_SUBMISSIONS` (500), which keeps the file far below the kernel's 16 MiB write cap. Each kernel write is + atomic; the append (a read-modify-write) is serialized per site by the store. An append that cannot read the + existing file fails rather than rewriting it from nothing; the console count and list then show nothing (logged). + +Everywhere the plugin echoes a value (form re-render, thank-you, admin listing) it HTML-escapes it (`Html.escape`). + +## 4. Inventory + +| Piece | Type | File | +|---|---|---| +| `mainClass` `@Configuration` | `ContactConfig` | wires widget + endpoint + store + mailer + admin model from SPI services; every bean name starts with `contact` | +| Form widget | `ContactWidget` (`ContentWidget` `contact`, query-aware) | inline form + outcome re-render | +| Endpoint | `ContactEndpoint` (`EndpointContributor`: anonymous `POST /contact/submit`; CSRF-checked `POST /contact/install-page` and `POST /contact/smtp-test`) | submit+store+send+303, starter page via `SitePages`, gated test | +| Shared form markup | `ContactForm` | the `` the widget renders | +| Storage | `ContactStore` + `ContactSubmission` | append/read tenant TSV | +| Mail send | `ContactMailer` + `MailTransport`/`JakartaMailTransport` + `SmtpSettings` + `MailSendResult` | build MIME + send over the site relay | +| Console model | `ContactAdminModel` (+ `SitePages.pathOf`) + `templates/` | contact-page install card + dashboard card + readiness + submissions table | +| Front-end | `static/contact.css`, `static/contact-help.html` | self-contained | +| i18n (EN/ES) | `i18n/` | form + console + SMTP labels/results | + +## 5. What it links (SPI 1.0.0) + +`pom.xml` depends on `runway-spi` only (`runway-spi-testkit` for tests); **`runway-app` is not a dependency in any +scope**, so a host import does not compile, and `ContactConfigTest` scans the compiled classes' constant pools for +any `mx.quest.runway` reference outside `mx.quest.runway.spi` — the kernel's own load-time scan finds nothing. + +| Need | SPI service | +|---|---| +| the site's settings | `PluginSettings.site(site)` → `SettingsView` | +| the SMTP password in clear, at send time | `PluginSettings.secret(site, "smtpPassword")` | +| the stored submissions | `PluginSiteFiles` (`submissions.tsv`) | +| visitor text / operator answers | `Messages.site` / `Messages.console` | +| the operator gate | `AccessCheck` (the `authz` bean) | +| the starter page | `SitePages.install` / `SitePages.pathOf` | +| the site's CAPTCHA | `CaptchaService.verify(site, token, req.clientIp())` | +| the submitted fields | `RouteRequest.form()` of an anonymous POST | + +`requiresSpi: ">=1.0.0"`: a kernel with an older SPI blocks the plugin before wiring, with a reason. + +## 6. Verify + +`scripts/verify-against-host.sh` (honours `JAVA_HOME` (required), `MVN`, `HOST_TARGET`, `HOST_JAR`, `VERIFY_TMPDIR`, +`VERIFY_LOG_DIR`, `PROTECTION_DIR`; never +runs `mvn install`) boots the **packaged** host in ACTIVE mode with four sites — the wizard's default (Advisory) +plus an Enforced, a Reviewed and a CAPTCHA site copied from it — and, when it is built, the protection plugin from +the host checkout. It checks: the plugin loads with zero host-linkage and bean-name/surface warnings; an anonymous +form POST with no session or token is stored and answered `303 ?contact=sent` with no submitted value in the +`Location`; a GET submission is a 404, a honeypot fakes success, an invalid email, fields only in the query string +and a multipart body are refused, and nothing of those is stored; the operator actions are CSRF-checked POSTs +(a `GET` of either is a `404` and changes nothing even for the signed-in owner, a `POST` without or with a forged +token is a `403` with no page created and no email sent, an anonymous `POST` holding a valid session token is a +`404`, and the settings page renders both as `POST` forms carrying a non-empty token and links to neither); the +starter page installs (`POST` with the settings page's token) on all three editorial levels and a second install +changes nothing; the settings page shows the page's path and the count; the SMTP +password saved through the settings form is stored `ENC(...)` and is offered in clear to a local fake relay (a +small Python SMTP listener) for a submission and for the SMTP test (the console form to the configured +recipient; a body `to` override with the token as a form field, as a browser form sends it, and again with it in +the `X-CSRF-TOKEN` header; a `to` in the query string is ignored); a full backup carries `submissions.tsv` and a +transfer copy does not, its manifest listing the omission; on the CAPTCHA site a POST without (or with a blank) +token is answered `?contact=captcha` and nothing is stored; the static assets serve and the submissions are never +served publicly. + +Unit tests (75) cover the store over the testkit's `TempDirSiteFiles` (`ContactStoreTest`, incl. an existing file +read in place and the unreadable-file rule), the widget rendering incl. the POST form, outcome flags + escaping +(`ContactWidgetTest`), the endpoint incl. POST-only and body-only acceptance, the CAPTCHA with the gated client +IP, store-then-send ordering, redirect outcomes, return-path safety, every install outcome, the gated SMTP test, POST-only operator actions (a GET installs and +sends nothing even for a permitted operator; the SMTP recipient is read from the body only) (`ContactEndpointTest`), +the admin fragment's POST forms carrying the CSRF token, no link to an action, unique ids +(`ContactAdminTemplateTest`), the send path incl. the MIME build against a mock transport and the password taken only +from the secret (`ContactMailerTest`), and the plugin's contract with the host (`ContactConfigTest`: wiring from +SPI services, bean-name prefix, template bean references, the floor, version, personal-data and secret +declarations, EN/ES key parity, the constant-pool scan). + +> **Send tests open no socket.** The send seam (`MailTransport`) is mocked, so `ContactMailerTest` exercises the +> full `MimeMessage` build and the store/send/report contract without touching the network. diff --git a/plugins/contact/i18n/messages.properties b/plugins/contact/i18n/messages.properties new file mode 100644 index 0000000..0f40ce2 --- /dev/null +++ b/plugins/contact/i18n/messages.properties @@ -0,0 +1,69 @@ +# Runway Contact plugin — English strings. Console labels resolve automatically; public-facing strings +# (contact.form.*, contact.success/error.*, contact.page.title) are looked up with Messages.site for the visitor's +# locale, and the plain-text answers of the operator actions (contact.page.*, contact.test.*) with +# Messages.console in the operator's console language. + +# Grantable permission (permissions matrix label) +contact.perm.settings=Configure contact form + +# Per-tenant settings form labels +contact.set.enabled=Enable contact form +contact.set.success=Thank-you message +contact.set.smtpHost=SMTP host +contact.set.smtpPort=SMTP port +contact.set.smtpAuth=SMTP authentication +contact.set.smtpUsername=SMTP username +contact.set.smtpPassword=SMTP password +contact.set.smtpStarttls=Use STARTTLS +contact.set.smtpSsl=Use SSL/TLS (SMTPS) +contact.set.fromAddress=From address +contact.set.toAddress=Send submissions to + +# Dashboard card +contact.card.title=Contact +contact.card.submissions=submissions + +# Admin status fragment +contact.admin.title=Contact submissions +contact.admin.empty=No submissions yet. +contact.admin.when=When +contact.admin.help=Contact help & reference +contact.admin.smtp=SMTP relay +contact.admin.smtp.ok=Configured +contact.admin.smtp.missing=Not configured +contact.admin.smtp.test=Send a test email +contact.admin.smtp.test.tip=Send a test message over this site's SMTP relay to verify the configuration + +# SMTP test result (public text response of /contact/smtp-test) +contact.test.ok=Test message sent. +contact.test.notConfigured=No SMTP relay is configured for this site. +contact.test.providerMissing=Mail libraries are not available on the server, so email cannot be sent. +contact.test.failed=Test message failed: + +# Ready-made "Contact page" install card (admin fragment) + install-action result text +contact.page.card.title=Contact page +contact.page.card.desc=Install a ready-made contact page carrying the form. It becomes a normal site page — edit, restyle, move or rename it from Pages. +contact.page.card.install=Install contact page +contact.page.card.install.tip=Seed a ready-made, editable contact page (idempotent — it never overwrites an existing page) +contact.page.card.badge=Installed +contact.page.card.at=Installed at +contact.page.card.edit=— edit it under Pages. +# install-page action result (plain text) +contact.page.title=Contact +contact.page.installed=Contact page installed at +contact.page.exists=A contact page already exists at +contact.page.failed=Could not install the contact page. +contact.page.pending=The contact page was created and is waiting in the review queue: +contact.page.blocked=The contact page was created as a draft because the quality checks blocked publishing; fix it in the page editor: +contact.page.other=The contact page install finished: + +# Public-facing form + result +contact.heading=Contact +contact.form.name=Name +contact.form.email=Email +contact.form.message=Message +contact.form.submit=Send +contact.success=Thanks — your message has been sent. +contact.note.stored=Your message was received; email delivery is delayed. +contact.error.invalid=Please enter your email and a message. +contact.error.captcha=Please complete the challenge and try again. diff --git a/plugins/contact/i18n/messages_es.properties b/plugins/contact/i18n/messages_es.properties new file mode 100644 index 0000000..16f1015 --- /dev/null +++ b/plugins/contact/i18n/messages_es.properties @@ -0,0 +1,66 @@ +# Runway Contact plugin — cadenas en español. + +# Permiso otorgable (etiqueta de la matriz de permisos) +contact.perm.settings=Configurar formulario de contacto + +# Etiquetas del formulario de configuración por sitio +contact.set.enabled=Activar formulario de contacto +contact.set.success=Mensaje de agradecimiento +contact.set.smtpHost=Servidor SMTP +contact.set.smtpPort=Puerto SMTP +contact.set.smtpAuth=Autenticación SMTP +contact.set.smtpUsername=Usuario SMTP +contact.set.smtpPassword=Contraseña SMTP +contact.set.smtpStarttls=Usar STARTTLS +contact.set.smtpSsl=Usar SSL/TLS (SMTPS) +contact.set.fromAddress=Dirección de remitente +contact.set.toAddress=Enviar los mensajes a + +# Tarjeta del panel +contact.card.title=Contacto +contact.card.submissions=mensajes + +# Fragmento de estado (admin) +contact.admin.title=Mensajes de contacto +contact.admin.empty=Aún no hay mensajes. +contact.admin.when=Fecha +contact.admin.help=Ayuda y referencia de contacto +contact.admin.smtp=Relé SMTP +contact.admin.smtp.ok=Configurado +contact.admin.smtp.missing=Sin configurar +contact.admin.smtp.test=Enviar un correo de prueba +contact.admin.smtp.test.tip=Envía un mensaje de prueba por el relé SMTP de este sitio para verificar la configuración + +# Resultado de la prueba SMTP (respuesta de texto de /contact/smtp-test) +contact.test.ok=Mensaje de prueba enviado. +contact.test.notConfigured=No hay ningún relé SMTP configurado para este sitio. +contact.test.providerMissing=Las bibliotecas de correo no están disponibles en el servidor, así que no se puede enviar correo. +contact.test.failed=La prueba de envío falló: + +# Tarjeta de instalación de la «Página de contacto» (fragmento admin) + texto del resultado de la acción +contact.page.card.title=Página de contacto +contact.page.card.desc=Instala una página de contacto lista para usar con el formulario. Se convierte en una página normal del sitio: edítala, cámbiale el estilo, muévela o renómbrala desde Páginas. +contact.page.card.install=Instalar página de contacto +contact.page.card.install.tip=Crea una página de contacto lista y editable (idempotente: nunca sobrescribe una página existente) +contact.page.card.badge=Instalada +contact.page.card.at=Instalada en +contact.page.card.edit=— edítala desde Páginas. +# Resultado de la acción de instalación (texto plano) +contact.page.title=Contacto +contact.page.installed=Página de contacto instalada en +contact.page.exists=Ya existe una página de contacto en +contact.page.failed=No se pudo instalar la página de contacto. +contact.page.pending=Se creó la página de contacto y está esperando en la cola de revisión: +contact.page.blocked=Se creó la página de contacto como borrador porque las comprobaciones de calidad bloquearon la publicación; corrígela en el editor de páginas: +contact.page.other=La instalación de la página de contacto terminó: + +# De cara al público (formulario + resultado) +contact.heading=Contacto +contact.form.name=Nombre +contact.form.email=Correo electrónico +contact.form.message=Mensaje +contact.form.submit=Enviar +contact.success=Gracias: tu mensaje ha sido enviado. +contact.note.stored=Hemos recibido tu mensaje; el envío por correo se ha retrasado. +contact.error.invalid=Introduce tu correo electrónico y un mensaje. +contact.error.captcha=Completa el desafío e inténtalo de nuevo. diff --git a/plugins/contact/plugin.yml b/plugins/contact/plugin.yml new file mode 100644 index 0000000..26290cb --- /dev/null +++ b/plugins/contact/plugin.yml @@ -0,0 +1,70 @@ +# ============================================================================= +# Runway Contact plugin — descriptor +# A contact form delivered as a CONTENT WIDGET on a normal, editable site page +# (no plugin-owned page): drop
on a page, +# or install a ready-made contact page in one click from the settings — it then +# behaves like any site page (listed under Pages; restyle/move/rename it). The +# endpoint owns only the ANONYMOUS POST /contact/submit handler (CSRF-exempt by +# the kernel for exactly that method and path; 303s back to the form's page with +# a ?contact= outcome), the operator-gated, CSRF-checked POSTs /contact/install-page +# and /contact/smtp-test. A submission is BOTH emailed to the site's recipient over +# the site's own SMTP relay AND kept as a stored record (belt-and-suspenders — +# never lost even if SMTP is down). CAPTCHA (when the site has one) + honeypot. +# Links ONLY the Runway SPI (SPI 1.0.0). +# The install folder name MUST equal this `id`: external/plugins/contact/. +# ============================================================================= +id: contact +name: Contact form +version: 2.1.0 + +# The @Configuration registered before refresh. Package mx.quest.contact lives OUTSIDE mx.quest.runway. +mainClass: mx.quest.contact.ContactConfig + +# Built against the frozen SPI 1.0.0 contract (the service tier: PluginSettings, PluginSiteFiles, Messages, +# AccessCheck, SitePages and anonymous POST routes). A kernel with an older SPI BLOCKS this plugin at startup +# with a reason. +requiresSpi: ">=1.0.0" + +# --- Personal data (siteData) ------------------------------------------------------------------------------ +# submissions.tsv holds what visitors typed (names, emails, messages). A TRANSFER copy of a site (the one +# meant for someone outside the organisation) leaves it out and lists it in the archive's manifest; a FULL +# backup keeps it. Path relative to sites//plugins/contact/. +siteData: + personal: + - submissions.tsv + +# --- Dependencies ---------------------------------------------------------------------------------------- +# No plugin dependency: the Jakarta Mail stack is part of the CORE application (the kernel bundles it for +# its own platform mailer). This plugin compiles Jakarta Mail as `provided` and resolves the kernel's copy at +# runtime via the plugin classloader's parent-first delegation, so no `requires:` gate is needed. + +# --- Grantable control-point permission (gates the settings editor, the submissions view + the SMTP test) -- +permissions: + - { id: settings, realm: tenant, label: contact.perm.settings, defaultRoles: [] } + +# --- Per-tenant settings (tenant-owned behaviour; over sites//plugins/contact.yml) ------------------- +# The SMTP relay is the TENANT's own mail transport — isolation: a site sends with its OWN settings only. +# The password is a `secret` → stored ENC(...)-encrypted and the config file is chmod 600; the plugin reads it +# in clear only through PluginSettings.secret(site, "smtpPassword"), at send time. A blank host +# (or a blank recipient) simply means "don't send" — the submission is still stored. +# secretBoundTo: the stored password belongs to ONE relay login. A save that changes the host, port, username or a TLS switch +# without retyping the password makes the kernel DROP the stored password, so whoever may edit the settings +# cannot point the site's saved credentials at a server of their choosing and read them off the wire. +siteSettings: + - { key: enabled, type: boolean, default: true, label: contact.set.enabled } + - { key: successMessage, type: text, label: contact.set.success } + # --- SMTP relay ------------------------------------------------------------------------------------- + - { key: smtpHost, type: string, label: contact.set.smtpHost } + - { key: smtpPort, type: int, default: 25, range: "1..65535", label: contact.set.smtpPort } + - { key: smtpAuth, type: boolean, default: false, label: contact.set.smtpAuth } + - { key: smtpUsername, type: string, label: contact.set.smtpUsername } + - { key: smtpPassword, type: secret, label: contact.set.smtpPassword, + secretBoundTo: [smtpHost, smtpPort, smtpUsername, smtpStarttls, smtpSsl] } + - { key: smtpStarttls, type: boolean, default: false, label: contact.set.smtpStarttls } + - { key: smtpSsl, type: boolean, default: false, label: contact.set.smtpSsl } + - { key: fromAddress, type: string, label: contact.set.fromAddress } + - { key: toAddress, type: string, label: contact.set.toAddress } + +# --- Tenant dashboard card (fragment resolves to __plugin__/contact/dashboard) --------------------------- +dashboardCards: + - { realm: tenant, order: 45, fragment: dashboard, permission: "contact|settings" } diff --git a/plugins/contact/pom.xml b/plugins/contact/pom.xml new file mode 100644 index 0000000..7500714 --- /dev/null +++ b/plugins/contact/pom.xml @@ -0,0 +1,144 @@ + + + 4.0.0 + + + + org.springframework.boot + spring-boot-starter-parent + 4.0.6 + + + + mx.quest + runway-plugin-contact + 2.1.0 + jar + Runway Contact Plugin + + + GNU Affero General Public License v3.0, with the Runway additional permission for plugins + https://www.gnu.org/licenses/agpl-3.0.txt + repo + See LICENSE and LICENSE-EXCEPTION. + + + + A contact form for Runway: an embeddable form content widget that POSTs to an anonymous /contact/submit + route. A submission is BOTH emailed over the site's own SMTP relay (via Jakarta Mail, a core capability the + kernel bundles) AND kept as a stored tenant-owned record (viewable in the console; declared personal data, + so transfer copies leave it out), with CAPTCHA and honeypot anti-spam. Links only the Runway SPI. + + + + 25 + 25 + UTF-8 + + 2026-10-21T18:56:00Z + 1.0.0 + + 2.1.5 + + + + + mx.quest + runway-spi + ${runway.version} + + + + mx.quest + runway-spi-testkit + ${runway.version} + test + + + org.springframework.boot + spring-boot-starter + provided + + + + + jakarta.mail + jakarta.mail-api + ${jakarta.mail-api.version} + provided + + + + + org.eclipse.angus + angus-mail + 2.0.5 + test + + + org.springframework.boot + spring-boot-starter-test + test + + + + + runway-plugin-contact + + + maven-antrun-plugin + + + assemble-plugin-folder + package + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/contact/scripts/verify-against-host.sh b/plugins/contact/scripts/verify-against-host.sh new file mode 100755 index 0000000..a4cd9da --- /dev/null +++ b/plugins/contact/scripts/verify-against-host.sh @@ -0,0 +1,383 @@ +#!/usr/bin/env bash +# Build this plugin, drop it into a throwaway Runway deployment, boot the PACKAGED host in ACTIVE mode, and prove +# the contact contract end to end (SPI 1.0.0): +# - it loads with ZERO host-linkage and bean-name/surface warnings; +# - an anonymous visitor's form POST (no session, no CSRF token) to the anonymous route is stored and 303s back +# with only an outcome flag; GET submission is gone; honeypot / invalid / non-form bodies are refused; +# - the two operator actions are CSRF-protected POSTs: a GET (a cross-site link or ) changes nothing even +# for a signed-in owner, a POST without the console's CSRF token is refused 403, and an anonymous caller holding +# a token is still refused by the permission check (404); +# - signed in as the site owner, the starter page installs (POST + the token from the settings page) through +# SitePages on an Advisory, an Enforced and a Reviewed site (each outcome reported), and a second install +# changes nothing; +# - the SMTP password saved through the settings form is stored ENC(...) and reaches a local fake relay in clear +# (PluginSettings.secret), both for a submission and for the operator's SMTP test, whose body `to` override +# arrives with the CSRF token as a form field or a header; +# - a FULL backup carries submissions.tsv and a TRANSFER copy leaves it out and lists it in its manifest; +# - with the protection plugin installed (from the host checkout, when built) and a CAPTCHA configured on one +# site, a POST without the CAPTCHA token is refused and nothing is stored. +# The deployment holds four sites copied from the wizard's default one before the ACTIVE boot: default (Advisory), +# enforced, reviewed, captcha — addressed by Host name through curl --resolve. Verify ONLY against the packaged jar +# — never spring-boot:run (its restart classloader loads ZERO plugins). +# +# Usage: scripts/verify-against-host.sh [--keep] [--port N] +# JAVA_HOME=/path/to/jdk-25 required: the JDK that builds the plugin and runs the host +# MVN=/path/to/mvn Maven (default: mvn on the PATH) +# HOST_TARGET=/path/to/runway/runway-app/target the host build (default: the kernel this plugin sits in, else ../runway) +# HOST_JAR=/path/to/runway-app--exec.jar the kernel to verify against (default: the host checkout's +# runway-app/target jar MATCHING its pom version) +# PROTECTION_DIR=/dir the protection plugin's source folder (plugin.yml, i18n/, templates/, +# target/runway-plugin-protection.jar); default: the host checkout's +# runway-plugin-protection/. +# Set it to "" to skip the CAPTCHA checks. +# VERIFY_TMPDIR=/dir where the throwaway deployment goes (default: $TMPDIR or /tmp) +# VERIFY_LOG_DIR=/dir keep copies of the host logs, the fake relay's log and the two +# backup manifests there (evidence) +# The script never runs `mvn install` (nothing is written to ~/.m2): it packages this plugin offline against +# whatever runway-spi is already in the local repository. +set -uo pipefail + +HERE="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)" +# JAVA_HOME must name a JDK 25. MVN (default: `mvn` on the PATH), HOST_TARGET and PROTECTION_DIR (defaults: see +# above) can be set in the environment. +if [ -z "${JAVA_HOME:-}" ] || [ ! -x "$JAVA_HOME/bin/java" ]; then echo "set JAVA_HOME to a JDK 25"; exit 2; fi +export JAVA_HOME +JAVA="$JAVA_HOME/bin/java" +MVN="${MVN:-mvn}" +# Default host: the kernel at the root of the repository this plugin sits in (plugins//), else a kernel +# checkout named `runway` beside the plugins checkout. +if [ -z "${HOST_TARGET:-}" ]; then + if [ -f "$HERE/../../runway-app/pom.xml" ]; then HOST_TARGET="$HERE/../../runway-app/target" + else HOST_TARGET="$HERE/../../runway/runway-app/target"; fi +fi +PROTECTION_DIR="${PROTECTION_DIR-$HOST_TARGET/../../runway-plugin-protection}" + +KEEP="no"; PORT="" +while [ $# -gt 0 ]; do case "$1" in + --keep) KEEP="yes"; shift ;; + --port) PORT="${2:?}"; shift 2 ;; + *) echo "unknown arg: $1"; exit 2 ;; +esac; done + +APP_USER=root; APP_PW=Contact-Admin-2026; SITE_USER=owner; SITE_PW=Contact-Site-2026 +SECRET_KEY=contact-verify-master-key-2026; RELAY_USER=relay-user; RELAY_PW='Relay-Secret-42' +free_port() { python3 -I -c 'import socket;s=socket.socket();s.bind(("127.0.0.1",0));print(s.getsockname()[1]);s.close()'; } +[ -n "$PORT" ] || PORT="$(free_port)" +SMTP_PORT="$(free_port)" +BASE="http://localhost:$PORT" + +echo "[verify] building the plugin ..." +( cd "$HERE" && "$MVN" -o -q -DskipTests package ) || { echo "plugin build failed"; exit 1; } + +# The host jar MATCHING the host pom's version — never "the newest file": every reproducible jar carries the same +# fixed timestamp, so `ls -t` cannot tell a leftover release jar from the SNAPSHOT under test. +if [ -n "${HOST_JAR:-}" ]; then + JAR="$HOST_JAR" +else + HOST_VERSION="$(sed -n 's:.*\(.*\).*:\1:p' "$HOST_TARGET/../pom.xml" | head -1)" + JAR="$HOST_TARGET/runway-app-$HOST_VERSION-exec.jar" +fi +[ -f "$JAR" ] || { echo "no host exec jar $JAR — build the host (mvn -pl runway-app package) or set HOST_JAR"; exit 1; } +echo "[verify] host jar: $JAR" + +SCRATCH="$(mktemp -d "${VERIFY_TMPDIR:-${TMPDIR:-/tmp}}/contact-verify.XXXXXX")" +cleanup() { + [ -z "${VERIFY_LOG_DIR:-}" ] || { mkdir -p "$VERIFY_LOG_DIR" \ + && cp "$SCRATCH"/*.log "$SCRATCH"/*-manifest.yml "$VERIFY_LOG_DIR"/ 2>/dev/null; } + kill "${SMTP_PID:-0}" 2>/dev/null + # Wait for the host to exit before deleting: a JVM still shutting down rewrites files under external/ and + # makes `rm -rf` leave the scratch folder behind. + [ "$KEEP" = "yes" ] || { kill "${PID:-0}" 2>/dev/null; wait "${PID:-0}" 2>/dev/null; rm -rf "$SCRATCH"; } +} +trap cleanup EXIT +EXT="$SCRATCH/external" +mkdir -p "$EXT/plugins" +cp -r "$HERE/target/contact" "$EXT/plugins/contact" + +wait_for() { for _ in $(seq 1 "$3"); do grep -q "$2" "$1" 2>/dev/null && return 0; sleep 1; done; return 1; } +PASS=0; FAIL=0; SKIP=0 +ck() { if eval "$2" >/dev/null 2>&1; then echo " PASS $1"; PASS=$((PASS+1)); else echo " FAIL $1"; FAIL=$((FAIL+1)); fi; } +skip() { echo " SKIP $1"; SKIP=$((SKIP+1)); } +boot() { ( cd "$SCRATCH" && exec "$JAVA" -jar "$JAR" --server.port="$PORT" --runway.storage.external="$EXT" \ + --runway.security.secret-key="$SECRET_KEY" ) >"$1" 2>&1 & PID=$!; } + +echo "[verify] booting host (wizard) on :$PORT ..." +boot "$SCRATCH/wizard.log" +wait_for "$SCRATCH/wizard.log" "Started RunwayApplication" 90 || { echo "wizard did not start"; tail -20 "$SCRATCH/wizard.log"; exit 1; } +curl -s -o /dev/null -X POST "$BASE/setup" --data-urlencode "username=$APP_USER" --data-urlencode "password=$APP_PW" \ + --data-urlencode "displayName=Root" --data-urlencode "siteAdminUsername=$SITE_USER" --data-urlencode "siteAdminPassword=$SITE_PW" +for _ in $(seq 1 30); do kill -0 "$PID" 2>/dev/null || break; sleep 1; done + +# --- Three more sites, copied from the seeded default one (same owner), before the ACTIVE boot reads them -------- +SITES="$EXT/sites" +[ -f "$SITES/default/site.yml" ] || { echo "the wizard did not seed $SITES/default"; exit 1; } +make_site() { # id editorial-level + cp -r "$SITES/default" "$SITES/$1" + sed -i -e "s/^id: .*/id: \"$1\"/" -e "s/^- \"localhost\"/- \"$1.test\"/" -e "s/^editorial: .*/editorial: \"$2\"/" \ + "$SITES/$1/site.yml" +} +make_site enforced enforced +make_site reviewed reviewed +make_site captcha advisory +sed -i 's/^ - "default"$/ - "default"\n - "enforced"\n - "reviewed"/' "$EXT/site-users.yml" +# A page carrying the widget anchor on the captcha site: its seeded About page, edited on disk. +sed -i 's|
|
|' \ + "$SITES/captcha/templates/about.html" +PROTECTION="no" +if [ -n "$PROTECTION_DIR" ] && [ -f "$PROTECTION_DIR/target/runway-plugin-protection.jar" ]; then + mkdir -p "$EXT/plugins/protection" + cp "$PROTECTION_DIR/plugin.yml" "$PROTECTION_DIR/target/runway-plugin-protection.jar" "$EXT/plugins/protection/" + cp -r "$PROTECTION_DIR/i18n" "$PROTECTION_DIR/templates" "$EXT/plugins/protection/" + mkdir -p "$SITES/captcha/plugins" + # A reCAPTCHA v2 configuration for the captcha site only (a hand-written plaintext secret is accepted). A POST + # without a token is refused before any call to the provider, so no network is needed. + cat > "$SITES/captcha/plugins/protection.yml" <<'YML' +honeypotEnabled: true +captcha: + enabled: true + provider: recaptcha-v2 + siteKey: verify-site-key + secretKey: verify-secret-key +YML + PROTECTION="yes" +fi + +echo "[verify] booting host (ACTIVE) ..." +boot "$SCRATCH/active.log" +wait_for "$SCRATCH/active.log" "Started RunwayApplication" 90 || { echo "ACTIVE did not start"; tail -20 "$SCRATCH/active.log"; exit 1; } +LOG="$SCRATCH/active.log" +TSV="$SITES/default/plugins/contact/submissions.tsv" +lines() { if [ -f "$1" ]; then grep -c . "$1"; else echo 0; fi; } + +echo "== plugin load (SPI 1.0.0 contract) ==" +EXPECTED=1; [ "$PROTECTION" = "yes" ] && EXPECTED=2 +ck "plugins registered ($EXPECTED), 0 blocked" "grep -qE 'plugins: $EXPECTED registered, 0 blocked' '$LOG'" +ck "not blocked / quarantined" "! grep -qE \"plugin 'contact' is blocked|plugin-quarantine\" '$LOG'" +# Host linkage and the surface rules, in both kernels' words: SPI 0.6.0 WARNed ("uses host internals", "… allowed until +# Runway 1.0"); from SPI 1.0.0 the kernel BLOCKS and logs "linkage scan: " / the surface reason — a grep for the +# 0.6.0 wording alone can never fail on a 1.0 kernel. +ck "ZERO host-linkage findings" "! grep -qE \"uses host internals|plugin 'contact' linkage scan\" '$LOG'" +ck "ZERO bean-name/surface findings" "! grep -qE \"plugin 'contact'.*(allowed until Runway 1.0|bean name|may not contribute)\" '$LOG'" +ck "no WARN/ERROR names the plugin" "! grep -E ' (WARN|ERROR) ' '$LOG' | grep -qi 'contact'" +ck "no key collision / degraded" "! grep -qiE 'collision|duplicate key|degraded' '$LOG'" + +echo "== static assets ==" +ck "contact.css served" "curl -s -o /dev/null -w '%{http_code}' '$BASE/__plugin/contact/static/contact.css' | grep -q 200" +ck "help page served" "curl -s -o /dev/null -w '%{http_code}' '$BASE/__plugin/contact/static/contact-help.html' | grep -q 200" + +echo "== anonymous POST /contact/submit (no session, no CSRF token) ==" +post() { curl -s -o /dev/null -w '%{http_code} %{redirect_url}' -X POST "$@"; } +R="$(post "$BASE/contact/submit" --data-urlencode 'return=/' --data-urlencode 'name=Ann Visitor' \ + --data-urlencode 'email=ann@example.com' --data-urlencode 'message=Hello from a POST' --data-urlencode 'website=')" +ck "valid POST -> 303 ?contact=sent" "[ \"\${R%% *}\" = 303 ] && echo '$R' | grep -q 'contact=sent'" +ck "the redirect carries no submitted value" "! echo '$R' | grep -qiE 'ann|example|hello'" +ck "the submission is stored (appended to submissions.tsv)" "grep -q $'\tAnn Visitor\tann@example.com\tHello from a POST' '$TSV'" +ck "a GET submission is gone (404) and stores nothing" \ + "[ \"\$(curl -s -o /dev/null -w '%{http_code}' '$BASE/contact/submit?return=/&name=Get&email=get%40example.com&message=via%20GET&website=')\" = 404 ] && ! grep -q 'get@example.com' '$TSV'" +ck "a filled honeypot fakes success and stores nothing" \ + "post '$BASE/contact/submit' -d 'return=/&name=Bot&email=bot%40example.com&message=spam&website=http://spam' | grep -q 'contact=sent' && ! grep -q 'bot@example.com' '$TSV'" +ck "an invalid email -> ?contact=invalid, not stored" \ + "post '$BASE/contact/submit' -d 'return=/&name=Bad&email=nope&message=hi&website=' | grep -q 'contact=invalid' && ! grep -q $'\tBad\t' '$TSV'" +ck "fields in the query string are ignored -> invalid" \ + "post '$BASE/contact/submit?name=Q&email=q%40example.com&message=query' -d 'return=/' | grep -q 'contact=invalid' && ! grep -q 'q@example.com' '$TSV'" +ck "a multipart body is refused 415 by the kernel" \ + "[ \"\$(curl -s -o /dev/null -w '%{http_code}' -X POST '$BASE/contact/submit' -F 'name=M' -F 'email=m@example.com' -F 'message=multi')\" = 415 ]" +ck "exactly one stored submission so far" "[ \"\$(lines '$TSV')\" = 1 ]" + +ck "submissions.tsv is never served publicly" \ + "( for u in '/static/../plugins/contact/submissions.tsv' '/plugins/contact/submissions.tsv' '/__plugin/contact/static/../../submissions.tsv'; do curl -s --path-as-is '$BASE'\$u | grep -q 'ann@example.com' && exit 1; done; exit 0 )" + +echo "== the starter page through SitePages (Advisory, Enforced, Reviewed) ==" +token() { grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//'; } +# One cookie jar per site host; curl --resolve maps .test to the local host so cookies scope correctly. +site_url() { [ "$1" = default ] && echo "$BASE" || echo "http://$1.test:$PORT"; } +sc() { # site curl-args... + local site="$1"; shift + curl -s -H 'Accept-Language: en' --resolve "$site.test:$PORT:127.0.0.1" \ + -c "$SCRATCH/cookies-$site.txt" -b "$SCRATCH/cookies-$site.txt" "$@" +} +login() { + local u; u="$(site_url "$1")" + sc "$1" -o /dev/null -X POST "$u/login" --data-urlencode "username=$SITE_USER" --data-urlencode "password=$SITE_PW" \ + --data-urlencode "_csrf=$(sc "$1" "$u/login" | token)" +} +code() { curl -s -o /dev/null -w '%{http_code}' "$@"; } +SETTINGS="$BASE/__admin/plugins/contact/settings" +no_page() { ! ls "$SITES/$1/templates"/contact.* >/dev/null 2>&1; } + +echo "== the operator actions are CSRF-protected POSTs (a link or an changes nothing) ==" +ck "anonymous GET of either action -> 404 (no GET route)" \ + "[ \"\$(code '$BASE/contact/install-page')\" = 404 ] && [ \"\$(code '$BASE/contact/smtp-test')\" = 404 ]" +ck "anonymous POST without a CSRF token -> 403 (the tenant chain's CSRF check)" \ + "[ \"\$(code -X POST '$BASE/contact/install-page' -d x=1)\" = 403 ] && [ \"\$(code -X POST '$BASE/contact/smtp-test' -d x=1)\" = 403 ]" +ANON_JAR="$SCRATCH/cookies-anon.txt" +ANON_TOKEN="$(curl -s -c "$ANON_JAR" -b "$ANON_JAR" "$BASE/login" | token)" +ck "anonymous POST WITH a valid session token -> 404 (the permission check still applies)" \ + "[ -n '$ANON_TOKEN' ] && [ \"\$(code -c '$ANON_JAR' -b '$ANON_JAR' -X POST '$BASE/contact/install-page' --data-urlencode '_csrf=$ANON_TOKEN')\" = 404 ]" +ck "…and nothing was installed by any of that" "no_page default" +for site in default enforced reviewed; do login "$site"; done +ck "signed-in owner: GET /contact/install-page -> 404 and no page (a cross-site link installs nothing)" \ + "[ \"\$(sc default -o /dev/null -w '%{http_code}' '$BASE/contact/install-page')\" = 404 ] && no_page default" +ck "signed-in owner: POST without the CSRF token -> 403 and no page" \ + "[ \"\$(sc default -o /dev/null -w '%{http_code}' -X POST '$BASE/contact/install-page' -d x=1)\" = 403 ] && no_page default" +ck "signed-in owner: POST with a forged CSRF token -> 403 and no page" \ + "[ \"\$(sc default -o /dev/null -w '%{http_code}' -X POST '$BASE/contact/install-page' -d _csrf=forged-token)\" = 403 ] && no_page default" +sc default "$SETTINGS" > "$SCRATCH/settings-0.html" +ck "the settings page offers the install as a POST form carrying a non-empty CSRF token" \ + "grep -q 'id=\"cp-install-form\" method=\"post\" action=\"/contact/install-page\"' '$SCRATCH/settings-0.html' && grep -qE 'id=\"cp-csrf\" type=\"hidden\" name=\"_csrf\" value=\"[^\"]+\"' '$SCRATCH/settings-0.html'" +ck "…and the SMTP test as a POST form carrying a non-empty CSRF token" \ + "grep -q 'id=\"cn-smtp-test-form\" method=\"post\" action=\"/contact/smtp-test\"' '$SCRATCH/settings-0.html' && grep -qE 'id=\"cn-csrf\" type=\"hidden\" name=\"_csrf\" value=\"[^\"]+\"' '$SCRATCH/settings-0.html'" +ck "…and no link points at either action" "! grep -qE 'href=\"/contact/(install-page|smtp-test)' '$SCRATCH/settings-0.html'" +install() { # site -> the install action's answer, POSTed with the token from that site's settings page + local u; u="$(site_url "$1")" + sc "$1" -X POST "$u/contact/install-page" --data-urlencode "_csrf=$(sc "$1" "$u/__admin/plugins/contact/settings" | token)" +} +install default > "$SCRATCH/install-default.txt" +ck "Advisory: POST with the token installs and publishes at /contact" "grep -qx 'Contact page installed at /contact' '$SCRATCH/install-default.txt'" +curl -s "$BASE/contact" > "$SCRATCH/contact-page.html" +ck "…the public page renders the form as a POST to the anonymous route" \ + "grep -q 'method=\"post\" action=\"/contact/submit\"' '$SCRATCH/contact-page.html' && ! grep -q 'name=\"_csrf\"' '$SCRATCH/contact-page.html'" +ck "…with the return path of the page" "grep -q 'name=\"return\" value=\"/contact\"' '$SCRATCH/contact-page.html'" +install default > "$SCRATCH/install-again.txt" +ck "a second install changes nothing and says where the page is" "grep -qx 'A contact page already exists at /contact' '$SCRATCH/install-again.txt'" +for site in enforced reviewed; do + install "$site" > "$SCRATCH/install-$site.txt" + echo " $site says: $(head -c 300 "$SCRATCH/install-$site.txt" | tr '\n' ' ')" +done +# Enforced: published when the quality checks pass, else a draft with the blocking findings listed. +ck "Enforced: a documented outcome, never an error" \ + "grep -qE '^(Contact page installed at /contact|The contact page was created as a draft because the quality checks blocked publishing; fix it in the page editor: /contact)' '$SCRATCH/install-enforced.txt'" +# Reviewed: the owner holds APPROVE_PAGES, so the gated publish runs; without it the page would wait for review. +ck "Reviewed (as the owner, who may approve): a documented outcome" \ + "grep -qE '^(Contact page installed at /contact|The contact page was created and is waiting in the review queue: /contact|The contact page was created as a draft)' '$SCRATCH/install-reviewed.txt'" +ck "the installed pages exist on every site" \ + "( for s in default enforced reviewed; do ls \"$SITES/\$s/templates\"/contact.* >/dev/null || exit 1; done )" +sc default "$SETTINGS" > "$SCRATCH/settings-1.html" +ck "the settings page shows the installed page's live path" "grep -q 'id=\"cp-path\"[^>]*>/contact<' '$SCRATCH/settings-1.html'" +ck "…and counts the stored submission" "grep -q 'id=\"cn-count\">1<' '$SCRATCH/settings-1.html'" + +echo "== the SMTP password: saved ENC(...), handed to the relay in clear (PluginSettings.secret) ==" +# A minimal local SMTP relay that accepts AUTH LOGIN/PLAIN and records the credentials and the message. +cat > "$SCRATCH/fake_smtp.py" <<'PY' +import base64, socket, sys, threading +port, log = int(sys.argv[1]), open(sys.argv[2], "a", buffering=1) +def b64(s): + return base64.b64decode(s.strip()).decode("utf-8", "replace") +def serve(c): + f = c.makefile("rwb", buffering=0) + def say(line): f.write((line + "\r\n").encode()) + say("220 fake ESMTP") + while True: + raw = f.readline() + if not raw: break + line = raw.decode("utf-8", "replace").rstrip("\r\n"); up = line.upper() + if up.startswith(("EHLO", "HELO")): say("250-fake"); say("250 AUTH LOGIN PLAIN") + elif up.startswith("AUTH PLAIN"): + arg = line[10:].strip() + if not arg: say("334 "); arg = f.readline().decode() + parts = b64(arg).split("\0"); log.write("AUTH user=%s pass=%s\n" % (parts[1], parts[2])); say("235 ok") + elif up.startswith("AUTH LOGIN"): + arg = line[10:].strip() + if not arg: say("334 VXNlcm5hbWU6"); arg = f.readline().decode() + user = b64(arg); say("334 UGFzc3dvcmQ6"); pw = b64(f.readline().decode()) + log.write("AUTH user=%s pass=%s\n" % (user, pw)); say("235 ok") + elif up.startswith(("MAIL", "RCPT", "RSET", "NOOP")): log.write(line + "\n"); say("250 ok") + elif up == "DATA": + say("354 go") + while True: + d = f.readline().decode("utf-8", "replace") + if d in (".\r\n", ".\n", ""): break + log.write("DATA " + d.rstrip("\r\n") + "\n") + say("250 queued") + elif up == "QUIT": say("221 bye"); break + else: say("250 ok") + c.close() +s = socket.socket(); s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1); s.bind(("127.0.0.1", port)); s.listen(5) +while True: + conn, _ = s.accept(); threading.Thread(target=serve, args=(conn,), daemon=True).start() +PY +python3 -I "$SCRATCH/fake_smtp.py" "$SMTP_PORT" "$SCRATCH/smtp.log" & SMTP_PID=$! +sc default -o /dev/null -X POST "$SETTINGS" --data-urlencode "enabled=true" \ + --data-urlencode "smtpHost=127.0.0.1" --data-urlencode "smtpPort=$SMTP_PORT" --data-urlencode "smtpAuth=true" \ + --data-urlencode "smtpUsername=$RELAY_USER" --data-urlencode "smtpPassword=$RELAY_PW" \ + --data-urlencode "fromAddress=site@example.test" --data-urlencode "toAddress=owner@example.test" \ + --data-urlencode "_csrf=$(token < "$SCRATCH/settings-1.html")" +CFG="$SITES/default/plugins/contact.yml" +ck "the password is stored ENC(...), never in clear" "grep -q 'smtpPassword: .*ENC(' '$CFG' && ! grep -q '$RELAY_PW' '$CFG'" +R="$(post "$BASE/contact/submit" --data-urlencode 'return=/contact' --data-urlencode 'name=Bea Mailer' \ + --data-urlencode 'email=bea@example.com' --data-urlencode 'message=Please call me back' --data-urlencode 'website=')" +ck "a submission over the configured relay -> ?contact=sent (not queued)" "echo '$R' | grep -q '/contact?contact=sent'" +ck "…the relay was offered the secret in clear" "grep -qx 'AUTH user=$RELAY_USER pass=$RELAY_PW' '$SCRATCH/smtp.log'" +ck "…and received the visitor's message" "grep -q 'DATA Please call me back' '$SCRATCH/smtp.log'" +ck "…which is stored as well" "grep -q 'bea@example.com' '$TSV'" +ck "signed-in owner: GET /contact/smtp-test?to=… -> 404 and no email (a cross-site link sends nothing)" \ + "[ \"\$(sc default -o /dev/null -w '%{http_code}' '$BASE/contact/smtp-test?to=link@example.test')\" = 404 ] && ! grep -q 'link@example.test' '$SCRATCH/smtp.log'" +ck "signed-in owner: POST /contact/smtp-test without the CSRF token -> 403 and no email" \ + "[ \"\$(sc default -o /dev/null -w '%{http_code}' -X POST '$BASE/contact/smtp-test' --data-urlencode 'to=forged@example.test')\" = 403 ] && ! grep -q 'forged@example.test' '$SCRATCH/smtp.log'" +# The console's button: a form POST carrying only the token -> the test goes to the configured recipient. +sc default -X POST "$BASE/contact/smtp-test" --data-urlencode "_csrf=$(sc default "$SETTINGS" | token)" \ + > "$SCRATCH/smtp-test.txt" +ck "the operator's SMTP test (the console form: POST + token) sends over the same relay to the configured recipient" \ + "grep -qx 'Test message sent.' '$SCRATCH/smtp-test.txt' && [ \"\$(grep -c 'RCPT TO:' '$SCRATCH/smtp.log')\" = 2 ]" +# The optional `to` override is read from the form BODY, never the query string. A browser form sends the CSRF +# token as the `_csrf` FIELD next to it, so that is the case that must work: the kernel keeps the url-encoded body +# for the route after its CSRF check, so form() carries the field whether the token came as the field or in the +# X-CSRF-TOKEN header. Both ways are checked. +sc default -X POST "$BASE/contact/smtp-test" --data-urlencode "_csrf=$(sc default "$SETTINGS" | token)" \ + --data-urlencode "to=field@example.test" > "$SCRATCH/smtp-test-to-field.txt" +ck "…and honours a 'to' override in the body with the token as a form field (as a browser form sends it)" \ + "grep -qx 'Test message sent.' '$SCRATCH/smtp-test-to-field.txt' && grep -q 'RCPT TO:' '$SCRATCH/smtp.log'" +sc default -X POST "$BASE/contact/smtp-test" -H "X-CSRF-TOKEN: $(sc default "$SETTINGS" | token)" \ + --data-urlencode "to=header@example.test" > "$SCRATCH/smtp-test-to-header.txt" +ck "…and with the token in the X-CSRF-TOKEN header" \ + "grep -qx 'Test message sent.' '$SCRATCH/smtp-test-to-header.txt' && grep -q 'RCPT TO:' '$SCRATCH/smtp.log'" +sc default -X POST "$BASE/contact/smtp-test?to=query@example.test" \ + --data-urlencode "_csrf=$(sc default "$SETTINGS" | token)" > "$SCRATCH/smtp-test-to-query.txt" +ck "…but ignores a 'to' in the query string (the test goes to the configured recipient)" \ + "grep -qx 'Test message sent.' '$SCRATCH/smtp-test-to-query.txt' && ! grep -q 'query@example.test' '$SCRATCH/smtp.log' && [ \"\$(grep -c 'RCPT TO:' '$SCRATCH/smtp.log')\" = 3 ]" + +echo "== backups: a full backup keeps submissions.tsv, a transfer copy leaves it out ==" +sc default -o "$SCRATCH/full.zip" "$BASE/__admin/backups/download" +sc default -o "$SCRATCH/transfer.zip" "$BASE/__admin/backups/download-transfer" +zipq() { # zip mode -> prints what was asked + python3 -I - "$@" <<'PY' +import sys, zipfile +z = zipfile.ZipFile(sys.argv[1]); mode = sys.argv[2] +names = z.namelist() +if mode == "has": + sys.exit(0 if any(n.endswith(sys.argv[3]) for n in names) else 1) +if mode == "read": + n = next(n for n in names if n.endswith(sys.argv[3])); sys.stdout.write(z.read(n).decode("utf-8")) +PY +} +zipq "$SCRATCH/full.zip" read manifest.yml > "$SCRATCH/full-manifest.yml" 2>/dev/null +zipq "$SCRATCH/transfer.zip" read manifest.yml > "$SCRATCH/transfer-manifest.yml" 2>/dev/null +ck "the full backup carries plugins/contact/submissions.tsv" "zipq '$SCRATCH/full.zip' has plugins/contact/submissions.tsv" +ck "…with the submissions in it" "zipq '$SCRATCH/full.zip' read plugins/contact/submissions.tsv | grep -q 'ann@example.com'" +ck "the transfer copy has NO plugins/contact/submissions.tsv" "! zipq '$SCRATCH/transfer.zip' has plugins/contact/submissions.tsv" +ck "…and its manifest lists the omission" "grep -q 'plugins/contact/submissions.tsv' '$SCRATCH/transfer-manifest.yml'" +ck "…while the settings file travels (secret blanked)" \ + "zipq '$SCRATCH/transfer.zip' has plugins/contact.yml && ! zipq '$SCRATCH/transfer.zip' read plugins/contact.yml | grep -q 'ENC('" +ck "the full backup's manifest omits nothing of contact" "! grep -q 'plugins/contact/submissions.tsv' '$SCRATCH/full-manifest.yml'" + +echo "== CAPTCHA still enforced on the anonymous POST (protection plugin, one site) ==" +if [ "$PROTECTION" = "yes" ]; then + CTSV="$SITES/captcha/plugins/contact/submissions.tsv" + CURL_C="http://captcha.test:$PORT" + curl -s --resolve "captcha.test:$PORT:127.0.0.1" "$CURL_C/about" > "$SCRATCH/captcha-about.html" + ck "the form carries the site's CAPTCHA challenge" \ + "grep -q 'data-sitekey=\"verify-site-key\"' '$SCRATCH/captcha-about.html' && grep -q 'method=\"post\" action=\"/contact/submit\"' '$SCRATCH/captcha-about.html'" + ck "a POST without the CAPTCHA token -> ?contact=captcha" \ + "post --resolve 'captcha.test:$PORT:127.0.0.1' '$CURL_C/contact/submit' -d 'return=/about&name=Cy&email=cy%40example.com&message=no%20token&website=' | grep -q '/about?contact=captcha'" + ck "a POST with a blank CAPTCHA token -> ?contact=captcha" \ + "post --resolve 'captcha.test:$PORT:127.0.0.1' '$CURL_C/contact/submit' -d 'return=/about&name=Cy&email=cy%40example.com&message=blank&website=&g-recaptcha-response=' | grep -q 'contact=captcha'" + ck "a filled honeypot on that site still fakes success" \ + "post --resolve 'captcha.test:$PORT:127.0.0.1' '$CURL_C/contact/submit' -d 'return=/about&name=Bot&email=b%40example.com&message=x&website=http://spam' | grep -q 'contact=sent'" + ck "nothing was stored for the CAPTCHA site" "[ \"\$(lines '$CTSV')\" = 0 ]" +else + skip "CAPTCHA checks (no built protection plugin at '$PROTECTION_DIR')" +fi + +echo; echo "RESULT: $PASS passed, $FAIL failed, $SKIP skipped" +if [ "$KEEP" = "yes" ]; then echo "[verify] kept at $BASE (scratch $SCRATCH; kill $PID to stop)"; wait "$PID"; fi +exit "$FAIL" diff --git a/plugins/contact/src/main/java/mx/quest/contact/ContactAdminModel.java b/plugins/contact/src/main/java/mx/quest/contact/ContactAdminModel.java new file mode 100644 index 0000000..c9c0f39 --- /dev/null +++ b/plugins/contact/src/main/java/mx/quest/contact/ContactAdminModel.java @@ -0,0 +1,69 @@ +package mx.quest.contact; + +import java.util.List; +import mx.quest.runway.spi.service.SitePages; + +/** + * Read-only status model for the console surfaces (dashboard card + admin fragment), read by template bean name, + * e.g. {@code ${@contactAdminModel.count(tenantSiteId)}} and iterated for the recent-submissions table. Also + * exposes the SMTP readiness ({@link #smtpConfigured(String)}) and the test-action URL so the admin + * fragment can show "Configured / Not configured" and offer the operator-only SMTP self-test, plus the + * ready-made-page install status ({@link #pageInstalled(String)} / {@link #pagePath(String)}) — read + * fresh from the kernel's {@link SitePages#pathOf} so a moved/renamed page reports its current path. Gated in the console + * by the plugin's {@code settings} control point. + */ +public class ContactAdminModel { + + private static final int RECENT = 20; + + private final ContactStore store; + private final ContactMailer mailer; + private final SitePages pages; + + public ContactAdminModel(ContactStore store, ContactMailer mailer, SitePages pages) { + this.store = store; + this.mailer = mailer; + this.pages = pages; + } + + /** Total stored submissions for the site. */ + public int count(String siteId) { + return store.count(siteId); + } + + /** The most recent submissions (newest first) for the admin listing. */ + public List recent(String siteId) { + return store.recent(siteId, RECENT); + } + + /** + * Whether this site has a usable SMTP relay (a non-blank host AND recipient). When false, submissions are + * stored only — the readiness badge shows "Not configured" and no email is sent. + */ + public boolean smtpConfigured(String siteId) { + return mailer.settingsFor(siteId).isConfigured(); + } + + /** The recipient address configured for this site (for display), or an empty string when none is set. */ + public String recipient(String siteId) { + return mailer.settingsFor(siteId).to(); + } + + /** + * Whether this site already has the ready-made contact page (the one {@code /contact/install-page} seeds). + * Read fresh through {@link SitePages#pathOf} by the installer's stable slug, in any state (a draft or a page + * waiting for review counts), so it stays true even after the operator moves or renames the page (the slug is + * the page's identity; only its path changes). + */ + public boolean pageInstalled(String siteId) { + return pages.pathOf(siteId, ContactEndpoint.INSTALLED_PAGE_SLUG).isPresent(); + } + + /** + * The current URL path of the installed contact page (e.g. {@code /contact}, or wherever the operator moved + * it), or an empty string when it is not installed. Read live so the console always shows the real location. + */ + public String pagePath(String siteId) { + return pages.pathOf(siteId, ContactEndpoint.INSTALLED_PAGE_SLUG).orElse(""); + } +} diff --git a/plugins/contact/src/main/java/mx/quest/contact/ContactConfig.java b/plugins/contact/src/main/java/mx/quest/contact/ContactConfig.java new file mode 100644 index 0000000..a45f468 --- /dev/null +++ b/plugins/contact/src/main/java/mx/quest/contact/ContactConfig.java @@ -0,0 +1,66 @@ +package mx.quest.contact; + +import mx.quest.runway.spi.CaptchaService; +import mx.quest.runway.spi.ContentWidget; +import mx.quest.runway.spi.EndpointContributor; +import mx.quest.runway.spi.service.AccessCheck; +import mx.quest.runway.spi.service.Messages; +import mx.quest.runway.spi.service.PluginSettings; +import mx.quest.runway.spi.service.PluginSiteFiles; +import mx.quest.runway.spi.service.SitePages; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * The plugin's {@code mainClass} — the single {@code @Configuration} registered into the host context before + * refresh. Beans are wired EXPLICITLY (no {@code @ComponentScan}). The package {@code mx.quest.contact} lives + * OUTSIDE {@code mx.quest.runway} so the host never double-scans it. + * + *

SPI only. Everything this plugin needs from the kernel arrives as an SPI service (SPI 1.0.0): + * {@link PluginSettings} (this plugin's per-site settings, and the SMTP password secret in clear) and + * {@link PluginSiteFiles} (this plugin's per-site folder, where submissions are kept) are bound to this plugin by + * the jar this class was loaded from; {@link Messages}, {@link AccessCheck}, {@link SitePages} and the + * {@link CaptchaService} are kernel singletons. Nothing outside {@code mx.quest.runway.spi} is linked. + * + *

The {@link ContactWidget} ({@code ContentWidget}) and {@link ContactEndpoint} ({@code EndpointContributor}) + * are list-collected SPIs — plain {@code @Bean}s, NEVER {@code @Primary}. Every bean name starts with the plugin + * id ({@code contact…}), the kernel's rule for a bean namespace plugins share. The email seam is + * {@link MailTransport} ({@link JakartaMailTransport} in production, using the Jakarta Mail stack the KERNEL + * bundles as a core capability). + */ +@Configuration(proxyBeanMethods = false) +public class ContactConfig { + + @Bean + public ContactStore contactStore(PluginSiteFiles files) { + return new ContactStore(files); + } + + /** The production send seam — delegates to {@code jakarta.mail.Transport} (the kernel bundles Jakarta Mail). */ + @Bean + public MailTransport contactMailTransport() { + return new JakartaMailTransport(); + } + + @Bean + public ContactMailer contactMailer(PluginSettings settings, MailTransport transport) { + return new ContactMailer(settings, transport); + } + + @Bean + public ContentWidget contactWidget(PluginSettings settings, Messages messages, CaptchaService captcha) { + return new ContactWidget(settings, messages, captcha); + } + + @Bean + public EndpointContributor contactEndpoint(ContactStore store, ContactMailer mailer, PluginSettings settings, + Messages messages, AccessCheck access, CaptchaService captcha, + SitePages pages) { + return new ContactEndpoint(store, mailer, settings, messages, access, captcha, pages); + } + + @Bean + public ContactAdminModel contactAdminModel(ContactStore store, ContactMailer mailer, SitePages pages) { + return new ContactAdminModel(store, mailer, pages); + } +} diff --git a/plugins/contact/src/main/java/mx/quest/contact/ContactEndpoint.java b/plugins/contact/src/main/java/mx/quest/contact/ContactEndpoint.java new file mode 100644 index 0000000..a5d46f9 --- /dev/null +++ b/plugins/contact/src/main/java/mx/quest/contact/ContactEndpoint.java @@ -0,0 +1,310 @@ +package mx.quest.contact; + +import java.util.List; +import java.util.Locale; +import java.util.Map; +import mx.quest.runway.spi.CaptchaService; +import mx.quest.runway.spi.EndpointContributor; +import mx.quest.runway.spi.model.Capabilities; +import mx.quest.runway.spi.model.CaptchaWidget; +import mx.quest.runway.spi.model.Finding; +import mx.quest.runway.spi.model.InstallResult; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.spi.model.Route; +import mx.quest.runway.spi.model.RouteRequest; +import mx.quest.runway.spi.model.RouteResponse; +import mx.quest.runway.spi.model.StarterPage; +import mx.quest.runway.spi.model.SurfacePosture; +import mx.quest.runway.spi.service.AccessCheck; +import mx.quest.runway.spi.service.Messages; +import mx.quest.runway.spi.service.PluginSettings; +import mx.quest.runway.spi.service.SitePages; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The contact plugin's tiny request-handling surface — it owns no visible page. The contact form lives on a + * normal, editable site page (via the {@link ContactWidget} anchor; the operator installs the ready-made one from + * the plugin settings). This endpoint only: + *

    + *
  • {@code POST /contact/submit} — an anonymous route ({@code Route.anonymousPost}): the kernel + * exempts exactly this method and path from CSRF (a public form on a cacheable page has no session token), + * hands it only {@code application/x-www-form-urlencoded} bodies and runs it with no principal. The fields + * are read from the form body only — a field put in the query string is ignored, so a visitor's + * personal data never has to travel in a URL. It stores + emails the submission, then answers {@code 303} + * back to the page the form lives on (the {@code return} field, or the {@code Referer}) with a + * {@code ?contact=sent|invalid|captcha|queued} flag the widget re-renders the outcome from. The abuse guards + * stay in front of the store: a filled honeypot fakes success (stores/sends nothing), an invalid submission + * or an unsolved CAPTCHA (verified with the kernel-gated {@code clientIp}) redirects with an error flag, and + * the platform's per-address rate limit (the protection plugin's edge guard) applies to this path like any + * other. A valid submission is stored first ({@link ContactStore}) and then emailed over the + * site's own relay, so a send failure never loses the message. Any other method on this path is a 404.
  • + *
  • {@code POST /contact/install-page} — operator-gated ({@code contact|settings}): installs a real, + * editable page carrying the contact-form widget through {@link SitePages#install}, which respects the + * site's editorial level and never overwrites; the operator is told which of the outcomes happened.
  • + *
  • {@code POST /contact/smtp-test} — operator-gated SMTP self-test; an optional {@code to} field of the + * form body overrides the recipient.
  • + *
+ * The two operator actions change something (a page is created, an email is sent), so they are ordinary, + * non-anonymous {@code POST} routes: the kernel's tenant chain demands the console session's CSRF token on them + * (the admin fragment's forms carry it), which is what stops another web site from triggering them through a + * signed-in operator's browser with a link or an {@code }. A {@code GET} on either path matches no route and + * changes nothing (the kernel answers 404); {@link #handle} refuses any other method too, as a second line. + * Neither action reads the query string. + * Honors the per-site {@code enabled} setting (disabled ⇒ a submission is a no-op 404). All redirect targets are + * validated as same-origin local paths. + */ +public class ContactEndpoint implements EndpointContributor { + + /** The anonymous form-submission route; the {@link ContactForm} posts here. */ + static final String SUBMIT_PATH = "/contact/submit"; + static final String INSTALL_PATH = "/contact/install-page"; + static final String SMTP_TEST_PATH = "/contact/smtp-test"; + /** The slug/path the ready-made contact page is installed at (then owned + movable by the operator). */ + static final String INSTALLED_PAGE_SLUG = "contact"; + static final String SETTINGS_PERMISSION = "contact|settings"; + + private static final Logger log = LoggerFactory.getLogger(ContactEndpoint.class); + + private final ContactStore store; + private final ContactMailer mailer; + private final PluginSettings settings; + private final Messages messages; + private final AccessCheck access; + private final CaptchaService captcha; + private final SitePages pages; + + public ContactEndpoint(ContactStore store, ContactMailer mailer, PluginSettings settings, Messages messages, + AccessCheck access, CaptchaService captcha, SitePages pages) { + this.store = store; + this.mailer = mailer; + this.settings = settings; + this.messages = messages; + this.access = access; + this.captcha = captcha; + this.pages = pages; + } + + @Override + public String key() { + return "contact/form"; + } + + @Override + public List routes() { + // No public /contact PAGE — the form lives on a normal editable page. These are the submit handler + the + // two operator actions; all safeDefault (noindex/no-store), never advertised or crawled. The operator + // actions are POST and NOT anonymous: they change state, so the kernel's CSRF check must apply to them. + return List.of( + Route.anonymousPost(SUBMIT_PATH, SurfacePosture.safeDefault()), + new Route("POST", INSTALL_PATH, Realm.TENANT, SurfacePosture.safeDefault()), + new Route("POST", SMTP_TEST_PATH, Realm.TENANT, SurfacePosture.safeDefault())); + } + + @Override + public RouteResponse handle(RouteRequest req) { + // Every route here is POST-only; the kernel dispatches by method + path, and this check is the second line. + if (!"POST".equalsIgnoreCase(req.method())) { + return RouteResponse.notFound(); + } + return switch (req.path()) { + case SUBMIT_PATH -> handleSubmit(req); + case INSTALL_PATH -> handleInstallPage(req); + case SMTP_TEST_PATH -> handleSmtpTest(req); + default -> RouteResponse.notFound(); + }; + } + + /** Stores + emails a submission, then redirects back to the form's page with an outcome flag. */ + private RouteResponse handleSubmit(RouteRequest req) { + String siteId = req.site().id(); + if (!settings.site(siteId).bool("enabled", true)) { + return RouteResponse.notFound(); + } + String back = resolveReturn(req); + String name = formField(req, "name"); + String email = formField(req, "email"); + String message = formField(req, "message"); + String honeypot = formField(req, "website"); + + if (!honeypot.isBlank()) { + return redirect(back, "sent"); // a bot filled the trap — fake success, store/send nothing + } + if (message.isBlank() || !isEmail(email)) { + return redirect(back, "invalid"); + } + CaptchaWidget widget = captcha.widgetForSite(siteId); + if (widget.active() && !captcha.verify(siteId, formField(req, widget.tokenField()), req.clientIp())) { + return redirect(back, "captcha"); + } + // Belt-and-suspenders: STORE first (never lose a message), THEN email over the site's relay. + store.add(siteId, name, email, message, System.currentTimeMillis()); + MailSendResult sent = mailer.send(siteId, req.site().displayName(), name, email, message); + // "queued" ⇒ stored but the configured relay failed (an unobtrusive "delivery delayed" note); NOT_CONFIGURED + // is silent (the site simply stores messages) — so only a real relay failure downgrades to "queued". + boolean delayed = sent != null && !sent.wasSent() + && sent.status() != MailSendResult.Status.NOT_CONFIGURED; + return redirect(back, delayed ? "queued" : "sent"); + } + + /** + * Installs the ready-made, editable contact page (idempotent). {@code POST} only, CSRF-checked by the kernel; + * operator-gated, failing closed with a 404. + */ + private RouteResponse handleInstallPage(RouteRequest req) { + if (!access.may(SETTINGS_PERMISSION)) { + return RouteResponse.notFound(); + } + String siteId = req.site().id(); + Locale siteDefault = req.site().defaultLocale(); + String title = messages.site(siteId, siteDefault, "contact.page.title", "Contact"); + StarterPage page = new StarterPage(INSTALLED_PAGE_SLUG, "/" + INSTALLED_PAGE_SLUG, + Map.of(siteDefault.getLanguage(), title), installedPageHtml(title), installedPageLogic(), false); + InstallResult result; + try { + result = pages.install(siteId, page); + } catch (RuntimeException e) { + // IllegalStateException: a path another page serves, an unknown site, a failed write (no stray draft + // is left behind). Anything else is equally "not installed" to the operator. + log.warn("contact page install failed for site {}: {}", siteId, e.toString()); + return RouteResponse.text(500, console("contact.page.failed", "Could not install the contact page.")); + } + return RouteResponse.text(200, describe(result)); + } + + /** The operator's words for each install outcome; an outcome added in a later SPI MINOR gets a neutral line. */ + private String describe(InstallResult result) { + String path = result.path(); + return switch (result.outcome()) { + case PUBLISHED -> console("contact.page.installed", "Contact page installed at") + " " + path; + case PENDING_REVIEW -> console("contact.page.pending", + "The contact page was created and is waiting in the review queue:") + " " + path; + case DRAFT_BLOCKED -> { + StringBuilder text = new StringBuilder(console("contact.page.blocked", + "The contact page was created as a draft because the quality checks blocked publishing; " + + "fix it in the page editor:")).append(' ').append(path); + for (Finding finding : result.blocking()) { + text.append("\n- ").append(finding.code()).append(": ").append(finding.message()); + } + yield text.toString(); + } + case ALREADY_EXISTS -> console("contact.page.exists", "A contact page already exists at") + " " + path; + default -> console("contact.page.other", "The contact page install finished:") + " " + + result.outcome() + " " + path; + }; + } + + /** + * The operator-only SMTP self-test ({@code POST}, CSRF-checked by the kernel) — fails closed unless the caller + * holds {@code contact|settings}. + */ + private RouteResponse handleSmtpTest(RouteRequest req) { + if (!access.may(SETTINGS_PERMISSION)) { + return RouteResponse.notFound(); + } + // The override recipient comes from the form body only — never the query string. + MailSendResult result = mailer.sendTest(req.site().id(), req.site().displayName(), formField(req, "to")); + String text = switch (result.status()) { + case SENT -> console("contact.test.ok", "Test message sent."); + case NOT_CONFIGURED -> console("contact.test.notConfigured", "No SMTP relay is configured for this site."); + case PROVIDER_MISSING -> console("contact.test.providerMissing", + "Mail libraries are not available on the server."); + case FAILED -> console("contact.test.failed", "Test message failed:") + " " + result.detail(); + }; + return RouteResponse.text(result.wasSent() ? 200 : 502, text); + } + + /** The page the form lives on: the same-origin {@code return} field, else the {@code Referer} path, else "/". */ + private static String resolveReturn(RouteRequest req) { + String fromField = safeLocalPath(formField(req, "return")); + if (fromField != null) { + return fromField; + } + String fromReferer = safeLocalPath(refererPath(req.headers().get("referer"))); + return fromReferer != null ? fromReferer : "/"; + } + + /** The path (with query stripped) of a Referer, or {@code null} when absent. */ + private static String refererPath(String referer) { + if (referer == null || referer.isBlank()) { + return null; + } + int scheme = referer.indexOf("://"); + String path = referer; + if (scheme >= 0) { + int slash = referer.indexOf('/', scheme + 3); + path = slash < 0 ? "/" : referer.substring(slash); + } + int q = path.indexOf('?'); + return q < 0 ? path : path.substring(0, q); + } + + /** + * A {@code 303 See Other} back to {@code path} carrying only the outcome flag (never a submitted value); the + * browser follows it with a GET and the widget on that page re-renders from the flag (post/redirect/get, so a + * reload never resubmits). + */ + private static RouteResponse redirect(String path, String outcome) { + String location = path + (path.contains("?") ? "&" : "?") + "contact=" + outcome; + return new RouteResponse(303, Map.of("Location", location), new byte[0]); + } + + /** Reduces a candidate to a safe same-origin path (a single leading "/", no scheme/backslash/space/control). */ + private static String safeLocalPath(String p) { + if (p == null || p.isBlank() || !p.startsWith("/") || p.startsWith("//") || p.contains("://")) { + return null; + } + for (int i = 0; i < p.length(); i++) { + char c = p.charAt(i); + if (c < 0x20 || c == '\\' || c == ' ') { + return null; + } + } + return p; + } + + /** + * The body of the installed page: chrome seams ({@code head}/{@code #site-header}/{@code #site-footer}, filled + * from the master by {@link #installedPageLogic()}) and a {@code #content} carrying the contact-form widget + * anchor. The anchor bears both an {@code id} and {@code data-widget="contact/form"} on one element (the + * widget-binding contract), so the host renders the form in place. + */ + private static String installedPageHtml(String title) { + String t = Html.escape(title); + return "\n\n" + t + "\n\n" + + "
\n
\n" + + "

" + t + "

\n" + + "
\n" + + "
\n
\n\n\n"; + } + + /** The decoupled logic of the installed page: pulls the master chrome via {@code ${master}} (never a literal). */ + private static String installedPageLogic() { + return "\n\n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + } + + private static boolean isEmail(String value) { + int at = value.indexOf('@'); + return at > 0 && at < value.length() - 1 && value.indexOf('.', at) > at; + } + + /** A field of the form BODY (never the query string), stripped; "" when absent. */ + private static String formField(RouteRequest req, String name) { + List values = req.form().get(name); + return (values == null || values.isEmpty()) ? "" : values.get(0).strip(); + } + + private String console(String code, String fallback) { + return messages.console(code, fallback); + } + + @Override + public Capabilities capabilities() { + return Capabilities.of("endpoint.tenant", "contact.form"); + } +} diff --git a/plugins/contact/src/main/java/mx/quest/contact/ContactForm.java b/plugins/contact/src/main/java/mx/quest/contact/ContactForm.java new file mode 100644 index 0000000..862ad3b --- /dev/null +++ b/plugins/contact/src/main/java/mx/quest/contact/ContactForm.java @@ -0,0 +1,63 @@ +package mx.quest.contact; + +import java.util.Locale; +import mx.quest.runway.spi.service.Messages; + +/** + * Builds the contact-form markup the {@link ContactWidget} renders inline on a page. The form POSTs an + * {@code application/x-www-form-urlencoded} body to {@value ContactEndpoint#SUBMIT_PATH}, a route the + * {@link ContactEndpoint} declares anonymous ({@code Route.anonymousPost}): the kernel exempts exactly that + * method and path from CSRF, because a public form on a cacheable page cannot carry a per-session token. So the + * visitor's name, email and message travel in the request body — never in a URL, browser history, a + * {@code Referer} or a proxy log. A hidden honeypot field ({@code website}) catches naive bots; {@code captchaHtml} + * (when non-empty) adds the site's CAPTCHA challenge from the platform's {@code CaptchaService} — trusted, + * pre-rendered markup. Every label is looked up with {@link Messages#site} for the visitor's locale; every value + * that came from a request or a setting is HTML-escaped. + */ +final class ContactForm { + + private ContactForm() { + } + + /** + * Renders the contact form. It submits to the anonymous {@code POST} handler, which stores + emails the message + * and answers {@code 303} back to {@code returnPath} with a {@code ?contact=sent|invalid|captcha|queued} flag — + * so the visible page stays a normal, editable site page (the widget re-renders the outcome from that flag). + */ + static String render(Messages messages, String siteId, Locale locale, String error, String captchaHtml, + String returnPath) { + String nameLbl = messages.site(siteId, locale, "contact.form.name", "Name"); + String emailLbl = messages.site(siteId, locale, "contact.form.email", "Email"); + String messageLbl = messages.site(siteId, locale, "contact.form.message", "Message"); + String submitLbl = messages.site(siteId, locale, "contact.form.submit", "Send"); + + StringBuilder b = new StringBuilder(768); + b.append("") + .append("") + // Where the submit handler redirects back to (this page); validated server-side as a local path. + .append(""); + if (error != null && !error.isBlank()) { + b.append("

").append(Html.escape(error)).append("

"); + } + b.append(field("text", "name", nameLbl)) + .append(field("email", "email", emailLbl)) + .append("") + // Honeypot: hidden from humans, left blank; a bot that fills it is dropped as spam. + .append("
") + .append("
"); + // Real CAPTCHA challenge (only when the site configured one — trusted markup from the platform seam). + if (captchaHtml != null && !captchaHtml.isBlank()) { + b.append("
").append(captchaHtml).append("
"); + } + b.append(""); + return b.toString(); + } + + private static String field(String type, String fieldName, String label) { + return ""; + } +} diff --git a/plugins/contact/src/main/java/mx/quest/contact/ContactMailer.java b/plugins/contact/src/main/java/mx/quest/contact/ContactMailer.java new file mode 100644 index 0000000..516a6a3 --- /dev/null +++ b/plugins/contact/src/main/java/mx/quest/contact/ContactMailer.java @@ -0,0 +1,195 @@ +package mx.quest.contact; + +import jakarta.mail.Authenticator; +import jakarta.mail.Message; +import jakarta.mail.MessagingException; +import jakarta.mail.PasswordAuthentication; +import jakarta.mail.Session; +import jakarta.mail.internet.InternetAddress; +import jakarta.mail.internet.MimeMessage; +import java.nio.charset.StandardCharsets; +import java.util.Properties; +import mx.quest.runway.spi.service.PluginSettings; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Builds and sends the notification email for a contact submission over the site's own SMTP relay, then + * reports the outcome as a {@link MailSendResult}. It NEVER stores anything and NEVER throws for an operational + * failure — the {@link ContactEndpoint} always stores the submission first, so a relay problem degrades to a + * reported (not lost) message. + * + *

Isolation. The relay coordinates come only from {@link SmtpSettings#from} over this site's settings + * ({@link PluginSettings}, bound by the kernel to this plugin), so a site sends exclusively through the relay it + * configured (a tenant can never send through another's). The password is the site's {@code smtpPassword} secret, + * read in clear with {@link PluginSettings#secret} at send time and never kept. + * + *

Degrade-don't-crash. Three non-fatal outcomes are reported rather than thrown: + *

    + *
  • {@link MailSendResult#notConfigured()} — no host/recipient set (nothing to send to);
  • + *
  • {@link MailSendResult#providerMissing()} — the Jakarta Mail classes are not on the classloader (a + * {@link NoClassDefFoundError}/{@link LinkageError} at the seam). The kernel now bundles Jakarta Mail as a + * core capability, so this is effectively unreachable; the guard is kept purely so a broken deployment can + * never crash the request;
  • + *
  • {@link MailSendResult#failed(String)} — a configured relay rejected the message or was unreachable.
  • + *
+ * The build/send seam is {@link MailTransport}, injected so tests exercise the full MIME build against a mock + * with no socket opened. + */ +public class ContactMailer { + + private static final Logger log = LoggerFactory.getLogger(ContactMailer.class); + private static final int MAX_SUBJECT_SOURCE = 120; + /** The declared {@code type: secret} key of the SMTP password (plugin.yml). */ + static final String PASSWORD_KEY = "smtpPassword"; + + private final PluginSettings settings; + private final MailTransport transport; + + public ContactMailer(PluginSettings settings, MailTransport transport) { + this.settings = settings; + this.transport = transport; + } + + /** This site's current SMTP settings (the secret password in clear). Used by the send and the readiness badge. */ + public SmtpSettings settingsFor(String siteId) { + return SmtpSettings.from(settings.site(siteId), settings.secret(siteId, PASSWORD_KEY)); + } + + /** + * Emails a stored submission's contents to the site's recipient. Never throws for an operational failure — + * the outcome is always a {@link MailSendResult}. + * + * @param siteId the bound site (its own relay is used) + * @param displayName the site's display name (for the subject / body context) + * @param name the submitter's name + * @param email the submitter's email (used as Reply-To so a reply reaches the visitor) + * @param message the message body + */ + public MailSendResult send(String siteId, String displayName, String name, String email, String message) { + SmtpSettings smtp = settingsFor(siteId); + if (!smtp.isConfigured()) { + return MailSendResult.notConfigured(); + } + String subject = "[" + displayName + "] " + subjectExcerpt(name, message); + String body = "New contact submission on " + displayName + "\n\n" + + "Name: " + orDash(name) + "\n" + + "Email: " + orDash(email) + "\n\n" + + message; + return dispatch(smtp, smtp.effectiveFrom(), smtp.to(), subject, body, blankToNull(email)); + } + + /** + * Sends a diagnostic test message to {@code testTo} over the site's relay, to verify the SMTP configuration + * from the console. Same degrade contract as {@link #send} — the outcome is reported, never thrown. + */ + public MailSendResult sendTest(String siteId, String displayName, String testTo) { + SmtpSettings smtp = settingsFor(siteId); + // A test still needs a usable relay (host + a configured recipient) even though we override the To. + if (!smtp.isConfigured()) { + return MailSendResult.notConfigured(); + } + String to = (testTo == null || testTo.isBlank()) ? smtp.to() : testTo.strip(); + String body = "This is a test message from the Runway contact plugin for site '" + displayName + "'.\n" + + "If you received it, the site's SMTP relay is configured correctly."; + return dispatch(smtp, smtp.effectiveFrom(), to, "[" + displayName + "] SMTP test", body, null); + } + + private MailSendResult dispatch(SmtpSettings smtp, String from, String to, String subject, String body, + String replyTo) { + try { + MimeMessage msg = build(smtp, from, to, subject, body, replyTo); + transport.send(msg); + return MailSendResult.sent(); + } catch (MessagingException e) { + log.warn("contact mail send failed for relay {}: {}", smtp, e.toString()); + return MailSendResult.failed(rootMessage(e)); + } catch (LinkageError e) { + // Jakarta Mail not on the classpath. The kernel bundles it as a core capability, so this is + // effectively unreachable; guard it anyway so a broken deployment never crashes the request. + log.warn("contact mail send skipped: Jakarta Mail unavailable on the classloader: {}", e.toString()); + return MailSendResult.providerMissing(); + } + } + + /** Builds the MIME message from the site's relay settings. Package-visible for direct MIME-shape testing. */ + MimeMessage build(SmtpSettings smtp, String from, String to, String subject, String body, String replyTo) + throws MessagingException { + Session session = session(smtp); + MimeMessage msg = new MimeMessage(session); + msg.setFrom(new InternetAddress(from)); + msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); + if (replyTo != null) { + try { + msg.setReplyTo(InternetAddress.parse(replyTo, false)); + } catch (MessagingException badReplyTo) { + // A visitor-supplied email that isn't a valid address must not block the notification. + log.debug("ignoring invalid Reply-To '{}': {}", replyTo, badReplyTo.toString()); + } + } + msg.setSubject(subject, StandardCharsets.UTF_8.name()); + msg.setText(body, StandardCharsets.UTF_8.name()); + return msg; + } + + /** + * A Jakarta Mail {@link Session} from the relay settings (host/port, TLS mode + auth). + * + *

The protocol is always {@code smtp}, even for implicit TLS. We send with the static + * {@link jakarta.mail.Transport#send(jakarta.mail.Message)}, which resolves an {@code rfc822} recipient to + * the {@code smtp} transport via Jakarta Mail's address map — that lookup ignores + * {@code mail.transport.protocol}. Selecting {@code smtps} therefore leaves {@code mail.smtp.host} unset, so + * the send silently dials {@code localhost:25} and fails with "Connection refused". Implicit TLS (SMTPS, e.g. + * port 465) must instead ride {@code mail.smtp.ssl.enable}; explicit TLS (e.g. 587) rides + * {@code mail.smtp.starttls.enable}. Package-visible so a test can assert the resolved properties. + */ + static Session session(SmtpSettings smtp) { + boolean ssl = smtp.ssl(); + Properties props = new Properties(); + props.put("mail.transport.protocol", "smtp"); + props.put("mail.smtp.host", smtp.host()); + props.put("mail.smtp.port", String.valueOf(smtp.port())); + props.put("mail.smtp.auth", String.valueOf(smtp.auth())); + if (ssl) { + props.put("mail.smtp.ssl.enable", "true"); // implicit TLS on connect (SMTPS, e.g. 465) + } else { + props.put("mail.smtp.starttls.enable", String.valueOf(smtp.starttls())); // opportunistic STARTTLS (e.g. 587) + } + if (smtp.auth()) { + Authenticator auth = new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(smtp.username(), smtp.password()); + } + }; + return Session.getInstance(props, auth); + } + return Session.getInstance(props); + } + + private static String subjectExcerpt(String name, String message) { + String source = (name != null && !name.isBlank()) ? name : message; + String s = source == null ? "message" : source.strip().replaceAll("\\s+", " "); + if (s.isEmpty()) { + s = "message"; + } + return s.length() <= MAX_SUBJECT_SOURCE ? s : s.substring(0, MAX_SUBJECT_SOURCE).stripTrailing() + "…"; + } + + private static String rootMessage(Throwable t) { + Throwable cur = t; + while (cur.getCause() != null && cur.getCause() != cur) { + cur = cur.getCause(); + } + String m = cur.getMessage(); + return (m == null || m.isBlank()) ? cur.getClass().getSimpleName() : m; + } + + private static String orDash(String value) { + return (value == null || value.isBlank()) ? "—" : value.strip(); + } + + private static String blankToNull(String value) { + return (value == null || value.isBlank()) ? null : value.strip(); + } +} diff --git a/plugins/contact/src/main/java/mx/quest/contact/ContactStore.java b/plugins/contact/src/main/java/mx/quest/contact/ContactStore.java new file mode 100644 index 0000000..8c7ddda --- /dev/null +++ b/plugins/contact/src/main/java/mx/quest/contact/ContactStore.java @@ -0,0 +1,124 @@ +package mx.quest.contact; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import mx.quest.runway.spi.service.PluginSiteFiles; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Persists contact-form submissions as tenant-owned data in this plugin's per-site folder, through the kernel's + * {@link PluginSiteFiles}: {@value #FILE} under {@code sites//plugins/contact/}; an existing file is read and + * appended in place. The folder is outside the served {@code static/} tree (never publicly downloadable) and + * inside the site folder, so full backups carry it. The file holds what visitors typed, so {@code plugin.yml} + * declares it personal data ({@code siteData.personal}) and a transfer copy of the site leaves it out. + * + *

One tab-separated line per submission ({@code epochMillis \t name \t email \t message}); fields are + * sanitized to strip tabs/newlines so the format stays unambiguous, and each field is capped at + * {@value #MAX_FIELD} characters. The file is bounded to the most recent {@link #MAX_SUBMISSIONS}, so it stays + * a few MiB — well under the kernel's per-write cap. + * + *

Concurrency. Each kernel write is atomic, but appending is a read-modify-write, which the service + * leaves to the plugin: it is serialized here per site (contact volume is low). Failure. A read failure + * during {@link #add} aborts the append rather than rewriting the file from nothing (which would lose every + * stored submission); the console reads ({@link #count}, {@link #recent}) degrade to empty with a warning so an + * unreadable file never takes the settings screen down. + */ +public class ContactStore { + + static final int MAX_SUBMISSIONS = 500; + static final String FILE = "submissions.tsv"; + static final int MAX_FIELD = 4000; + private static final Logger log = LoggerFactory.getLogger(ContactStore.class); + + private final PluginSiteFiles files; + private final ConcurrentMap locks = new ConcurrentHashMap<>(); + + public ContactStore(PluginSiteFiles files) { + this.files = files; + } + + /** + * Appends a submission (stamped {@code epochMillis}), keeping only the most recent {@link #MAX_SUBMISSIONS}. + * + * @throws UncheckedIOException when the file cannot be read or written (nothing is lost: an unreadable file is + * left untouched) + */ + public void add(String siteId, String name, String email, String message, long epochMillis) { + String line = epochMillis + "\t" + sanitize(name) + "\t" + sanitize(email) + "\t" + sanitize(message); + synchronized (locks.computeIfAbsent(siteId, k -> new Object())) { + try { + List lines = new ArrayList<>(rawLines(siteId)); + lines.add(line); + if (lines.size() > MAX_SUBMISSIONS) { + lines = lines.subList(lines.size() - MAX_SUBMISSIONS, lines.size()); + } + files.writeText(siteId, FILE, String.join("\n", lines) + "\n"); + } catch (IOException e) { + throw new UncheckedIOException("storing a contact submission for site " + siteId, e); + } + } + } + + /** The most recent submissions, newest first, at most {@code limit}; empty when the file cannot be read. */ + public List recent(String siteId, int limit) { + List lines = new ArrayList<>(readableLines(siteId)); + Collections.reverse(lines); + List out = new ArrayList<>(); + for (String line : lines) { + if (out.size() >= limit) { + break; + } + ContactSubmission s = parse(line); + if (s != null) { + out.add(s); + } + } + return List.copyOf(out); + } + + /** The total number of stored submissions; 0 when the file cannot be read. */ + public int count(String siteId) { + return readableLines(siteId).size(); + } + + private List readableLines(String siteId) { + try { + return rawLines(siteId); + } catch (IOException e) { + log.warn("contact submissions of site {} could not be read: {}", siteId, e.toString()); + return List.of(); + } + } + + private List rawLines(String siteId) throws IOException { + return files.readText(siteId, FILE) + .map(text -> List.of(text.split("\n")).stream().filter(l -> !l.isBlank()).toList()) + .orElse(List.of()); + } + + private static ContactSubmission parse(String line) { + String[] p = line.split("\t", 4); + if (p.length < 4) { + return null; + } + try { + return new ContactSubmission(Long.parseLong(p[0].trim()), p[1], p[2], p[3]); + } catch (NumberFormatException e) { + return null; + } + } + + private static String sanitize(String value) { + if (value == null) { + return ""; + } + String s = value.replace('\t', ' ').replace('\r', ' ').replace('\n', ' ').strip(); + return s.length() > MAX_FIELD ? s.substring(0, MAX_FIELD) : s; + } +} diff --git a/plugins/contact/src/main/java/mx/quest/contact/ContactSubmission.java b/plugins/contact/src/main/java/mx/quest/contact/ContactSubmission.java new file mode 100644 index 0000000..b35aaf0 --- /dev/null +++ b/plugins/contact/src/main/java/mx/quest/contact/ContactSubmission.java @@ -0,0 +1,31 @@ +package mx.quest.contact; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; + +/** + * One stored contact-form submission. Immutable; fields are already sanitized (no tabs/newlines) by + * {@link ContactStore} so the on-disk TSV format stays unambiguous. + * + * @param epochMillis when it was received + * @param name the submitter's name + * @param email the submitter's email + * @param message the message (newlines collapsed to spaces on storage) + */ +public record ContactSubmission(long epochMillis, String name, String email, String message) { + + private static final DateTimeFormatter WHEN = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(ZoneId.systemDefault()); + + /** A {@code yyyy-MM-dd HH:mm} timestamp for display. */ + public String time() { + return WHEN.format(Instant.ofEpochMilli(epochMillis)); + } + + /** A short excerpt of the message for a listing cell. */ + public String excerpt() { + String m = message == null ? "" : message.strip(); + return m.length() <= 80 ? m : m.substring(0, 80).stripTrailing() + "…"; + } +} diff --git a/plugins/contact/src/main/java/mx/quest/contact/ContactWidget.java b/plugins/contact/src/main/java/mx/quest/contact/ContactWidget.java new file mode 100644 index 0000000..63c6ba1 --- /dev/null +++ b/plugins/contact/src/main/java/mx/quest/contact/ContactWidget.java @@ -0,0 +1,79 @@ +package mx.quest.contact; + +import java.util.Locale; +import mx.quest.runway.spi.CaptchaService; +import mx.quest.runway.spi.ContentWidget; +import mx.quest.runway.spi.model.Capabilities; +import mx.quest.runway.spi.model.RenderFragment; +import mx.quest.runway.spi.model.SettingsView; +import mx.quest.runway.spi.model.WidgetView; +import mx.quest.runway.spi.service.Messages; +import mx.quest.runway.spi.service.PluginSettings; + +/** + * The {@code contact} content widget: a site manager drops + * {@code

} on a page and the host renders the contact form + * inline (it POSTs to the {@link ContactEndpoint}). Honors the per-site {@code enabled} setting (disabled ⇒ + * {@link RenderFragment#empty()}). The markup is the shared {@link ContactForm}; public text comes from + * {@link Messages#site} in the visitor's locale. + */ +public class ContactWidget implements ContentWidget { + + private final PluginSettings settings; + private final Messages messages; + private final CaptchaService captcha; + + public ContactWidget(PluginSettings settings, Messages messages, CaptchaService captcha) { + this.settings = settings; + this.messages = messages; + this.captcha = captcha; + } + + @Override + public String key() { + return "contact"; + } + + @Override + public RenderFragment render(WidgetView view) { + String siteId = view.site().id(); + SettingsView config = settings.site(siteId); + if (!config.bool("enabled", true)) { + return RenderFragment.empty(); + } + Locale locale = view.locale(); + // The submit handler redirects back here with ?contact=sent|invalid|captcha; the widget re-renders the + // outcome from that flag. A pure read of the request — the store/send side effects live in the endpoint. + String outcome = view.query().get("contact"); + if ("sent".equals(outcome) || "queued".equals(outcome)) { + String success = config.string("successMessage", + messages.site(siteId, locale, "contact.success", "Thanks — your message has been sent.")); + String html = "

" + Html.escape(success.strip()) + "

"; + if ("queued".equals(outcome)) { + // Stored, but the site's relay failed: say so quietly, so the visitor does not send it again. + html += "

" + Html.escape(messages.site(siteId, locale, + "contact.note.stored", "Your message was received; email delivery is delayed.")) + "

"; + } + return RenderFragment.of(html); + } + String error = null; + if ("invalid".equals(outcome)) { + error = messages.site(siteId, locale, "contact.error.invalid", "Please enter your email and a message."); + } else if ("captcha".equals(outcome)) { + error = messages.site(siteId, locale, "contact.error.captcha", + "Please complete the challenge and try again."); + } + String captchaHtml = captcha.widgetForSite(siteId).html(); + // Land the visitor back on THIS page after submit: the request path as served (locale prefix and all), + // from the view — NEVER built from the slug, which for a content source's page (a blog entry rendering + // this widget in the master chrome) is a composite identity like "blog:my-post", not a path. The slug + // form remains only as the legacy fallback for a host that predates WidgetView.path. + String returnPath = view.path().isEmpty() ? "/" + view.page().slug() : view.path(); + return RenderFragment.of(ContactForm.render(messages, siteId, locale, error, captchaHtml, returnPath)); + } + + @Override + public Capabilities capabilities() { + return Capabilities.of("widget.contact"); + } +} diff --git a/plugins/contact/src/main/java/mx/quest/contact/Html.java b/plugins/contact/src/main/java/mx/quest/contact/Html.java new file mode 100644 index 0000000..7c1863f --- /dev/null +++ b/plugins/contact/src/main/java/mx/quest/contact/Html.java @@ -0,0 +1,20 @@ +package mx.quest.contact; + +/** + * Minimal HTML escaping for the values the contact plugin interpolates into its form and its stored/echoed + * submissions. The plugin owns escaping of its own output so a crafted name/email/message can never inject + * markup into the form page, the thank-you page, or the admin listing. + */ +final class Html { + + private Html() { + } + + static String escape(String value) { + if (value == null || value.isEmpty()) { + return ""; + } + return value.replace("&", "&").replace("<", "<").replace(">", ">") + .replace("\"", """).replace("'", "'"); + } +} diff --git a/plugins/contact/src/main/java/mx/quest/contact/JakartaMailTransport.java b/plugins/contact/src/main/java/mx/quest/contact/JakartaMailTransport.java new file mode 100644 index 0000000..940cd9d --- /dev/null +++ b/plugins/contact/src/main/java/mx/quest/contact/JakartaMailTransport.java @@ -0,0 +1,24 @@ +package mx.quest.contact; + +import jakarta.mail.MessagingException; +import jakarta.mail.Transport; +import jakarta.mail.internet.MimeMessage; + +/** + * The production {@link MailTransport}: hands the message to {@code jakarta.mail.Transport}, which resolves the + * {@code smtp}/{@code smtps} provider from the message's {@link jakarta.mail.Session} (the Angus reference + * implementation, discovered at runtime via {@code META-INF/services/jakarta.mail.Provider} — now supplied by + * the KERNEL, which bundles the Jakarta Mail stack as a core capability and is reached parent-first from the + * plugin classloader). + * + *

Authentication is carried on the {@code Session} the {@link ContactMailer} built (with {@code mail.smtp.auth} + * and a static {@link jakarta.mail.Authenticator} when the relay requires it), so {@link Transport#send(jakarta.mail.Message)} + * with the message alone is sufficient — no separate connect/credentials call. Stateless and thread-safe. + */ +public class JakartaMailTransport implements MailTransport { + + @Override + public void send(MimeMessage message) throws MessagingException { + Transport.send(message); + } +} diff --git a/plugins/contact/src/main/java/mx/quest/contact/MailSendResult.java b/plugins/contact/src/main/java/mx/quest/contact/MailSendResult.java new file mode 100644 index 0000000..aaf3372 --- /dev/null +++ b/plugins/contact/src/main/java/mx/quest/contact/MailSendResult.java @@ -0,0 +1,47 @@ +package mx.quest.contact; + +/** + * The reported outcome of trying to email a contact submission. A submission is always stored first + * (belt-and-suspenders), so this result is advisory — it never means the message was lost, only whether + * the email went out. The {@link ContactEndpoint} uses it to decide what the visitor sees; the plugin logs a + * failure but keeps the stored copy. + */ +public record MailSendResult(Status status, String detail) { + + /** Which way the send went. */ + public enum Status { + /** The message was handed to the site's SMTP relay successfully. */ + SENT, + /** No relay is configured for this site (blank host or recipient) — nothing was sent, only stored. */ + NOT_CONFIGURED, + /** Jakarta Mail is not on the classpath (a broken deployment; the kernel bundles it) — stored only. */ + PROVIDER_MISSING, + /** A relay is configured but the send failed (rejected / unreachable / auth) — {@link #detail} says why. */ + FAILED + } + + /** The email was sent. */ + public static MailSendResult sent() { + return new MailSendResult(Status.SENT, null); + } + + /** No SMTP relay configured for this site (stored only). */ + public static MailSendResult notConfigured() { + return new MailSendResult(Status.NOT_CONFIGURED, null); + } + + /** Jakarta Mail is unavailable on the classloader (a broken deployment; stored only). */ + public static MailSendResult providerMissing() { + return new MailSendResult(Status.PROVIDER_MISSING, null); + } + + /** The send failed for the given reason (stored only). */ + public static MailSendResult failed(String detail) { + return new MailSendResult(Status.FAILED, detail); + } + + /** Whether the email actually went out (as opposed to being stored only). */ + public boolean wasSent() { + return status == Status.SENT; + } +} diff --git a/plugins/contact/src/main/java/mx/quest/contact/MailTransport.java b/plugins/contact/src/main/java/mx/quest/contact/MailTransport.java new file mode 100644 index 0000000..950b4d8 --- /dev/null +++ b/plugins/contact/src/main/java/mx/quest/contact/MailTransport.java @@ -0,0 +1,25 @@ +package mx.quest.contact; + +import jakarta.mail.MessagingException; +import jakarta.mail.internet.MimeMessage; + +/** + * The send seam: the single point where a built {@link MimeMessage} actually leaves the JVM over SMTP. Factored + * out as an interface so the {@link ContactMailer}'s build-and-send logic can be unit-tested against a mock + * transport with no socket opened (the production {@link JakartaMailTransport} delegates to + * {@code jakarta.mail.Transport}). + * + *

Implementations MUST NOT swallow a failure — a broken relay has to be reported so the {@link ContactMailer} + * can surface it (the stored copy of the submission still lands regardless). A {@link MessagingException} means + * the send failed; returning normally means it was handed to the relay. + */ +public interface MailTransport { + + /** + * Sends an already-built, already-addressed message. + * + * @param message the MIME message to transmit (From/To/Subject/body all set by the caller) + * @throws MessagingException if the relay rejected the message or could not be reached + */ + void send(MimeMessage message) throws MessagingException; +} diff --git a/plugins/contact/src/main/java/mx/quest/contact/SmtpSettings.java b/plugins/contact/src/main/java/mx/quest/contact/SmtpSettings.java new file mode 100644 index 0000000..aabebcc --- /dev/null +++ b/plugins/contact/src/main/java/mx/quest/contact/SmtpSettings.java @@ -0,0 +1,80 @@ +package mx.quest.contact; + +import java.util.Objects; +import java.util.Optional; +import mx.quest.runway.spi.model.SettingsView; + +/** + * The per-site SMTP relay configuration, materialized from a site's {@code contact} plugin settings (the + * {@code smtp*} + {@code fromAddress}/{@code toAddress} {@code siteSettings}). Immutable; a pure value. + * + *

Isolation. Every field comes from this site's own {@code sites//plugins/contact.yml}; + * a site can therefore only ever send through the relay it configured — never another tenant's. + * + *

Secret handling. The password is a {@code secret} setting, stored {@code ENC(...)}-encrypted by the + * platform. It never appears in the {@link SettingsView} (the kernel leaves secret keys out of it); the caller + * hands it over separately, already in clear, from {@code PluginSettings.secret(siteId, "smtpPassword")}. The + * plaintext lives only in this transient value and is handed straight to Jakarta Mail, never logged (see + * {@link #toString()}) and never stored by this plugin. + * + * @param host the SMTP server host; blank ⇒ {@link #isConfigured()} is false (mail is skipped) + * @param port the SMTP server port (1..65535; default 25) + * @param auth whether to authenticate (SMTP AUTH) with {@code username}/{@code password} + * @param username the SMTP username (used only when {@code auth}) + * @param password the SMTP password in PLAINTEXT (already decrypted; used only when {@code auth}) + * @param starttls whether to upgrade a plain connection with STARTTLS + * @param ssl whether to open an implicit-TLS (SMTPS) connection + * @param from the envelope/From address; blank ⇒ falls back to {@code to} + * @param to the recipient address; blank ⇒ {@link #isConfigured()} is false (mail is skipped) + */ +public record SmtpSettings(String host, int port, boolean auth, String username, String password, + boolean starttls, boolean ssl, String from, String to) { + + /** + * Reads the SMTP relay from a site's contact settings. + * + * @param view the site's effective contact settings ({@code PluginSettings.site}) — declared defaults + * overlaid by what the operator saved; secret keys are absent from it by contract + * @param password the {@code smtpPassword} secret in clear ({@code PluginSettings.secret}); empty when unset + * or undecryptable — the relay then authenticates with a blank password and reports the failure + * @return the materialized, immutable settings (never {@code null}); {@link #isConfigured()} reports usability + */ + public static SmtpSettings from(SettingsView view, Optional password) { + Objects.requireNonNull(view, "view"); + String host = text(view, "smtpHost"); + int port = (int) view.integer("smtpPort", 25L, 1, 65535); + boolean auth = view.bool("smtpAuth", false); + String username = text(view, "smtpUsername"); + String clear = password == null ? "" : password.orElse(""); + boolean starttls = view.bool("smtpStarttls", false); + boolean ssl = view.bool("smtpSsl", false); + String from = text(view, "fromAddress"); + String to = text(view, "toAddress"); + return new SmtpSettings(host, port, auth, username, clear, starttls, ssl, from, to); + } + + /** + * Whether enough is set to attempt a send: a non-blank host AND a non-blank recipient. When false the + * {@link ContactMailer} reports {@code NOT_CONFIGURED} and the submission is stored only (never lost). + */ + public boolean isConfigured() { + return host != null && !host.isBlank() && to != null && !to.isBlank(); + } + + /** The effective From address: the configured one, or the recipient when From is blank (a sane default). */ + public String effectiveFrom() { + return (from == null || from.isBlank()) ? to : from; + } + + private static String text(SettingsView view, String key) { + return view.string(key, "").strip(); + } + + /** Never leak the password in logs / diagnostics. */ + @Override + public String toString() { + return "SmtpSettings[host=" + host + ", port=" + port + ", auth=" + auth + ", username=" + username + + ", starttls=" + starttls + ", ssl=" + ssl + ", from=" + from + ", to=" + to + + ", password=" + (password == null || password.isBlank() ? "" : "") + "]"; + } +} diff --git a/plugins/contact/src/test/java/mx/quest/contact/ContactAdminTemplateTest.java b/plugins/contact/src/test/java/mx/quest/contact/ContactAdminTemplateTest.java new file mode 100644 index 0000000..ffaf5e1 --- /dev/null +++ b/plugins/contact/src/test/java/mx/quest/contact/ContactAdminTemplateTest.java @@ -0,0 +1,98 @@ +package mx.quest.contact; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import mx.quest.runway.spi.model.Route; +import mx.quest.runway.spi.testkit.FakePluginSettings; +import mx.quest.runway.spi.testkit.FakeSiteServices; +import org.junit.jupiter.api.Test; + +/** + * The console side of the CSRF fix: every operator action the endpoint declares (a non-anonymous {@code POST}) is + * reached from the admin fragment by a {@code

} that carries the console session's CSRF token, + * and no link points at it any more (a link is a {@code GET}, and a {@code GET} on those paths changes nothing). + * The markup is read from {@code templates/} as shipped; the token binding from the sibling {@code .th.xml}. + */ +class ContactAdminTemplateTest { + + private static final Pattern FORM = Pattern.compile("(?s)]*)>(.*?)"); + private static final Pattern CSRF_INPUT = + Pattern.compile("]*\\bid=\"([^\"]+)\"[^>]*\\bname=\"_csrf\"[^>]*>"); + private static final String TOKEN_BINDING = + "th:attr=\"name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}\""; + + private static String read(String file) throws IOException { + return Files.readString(Path.of("templates", file), StandardCharsets.UTF_8).replaceAll("(?s)", ""); + } + + private static List operatorActions() { + ContactEndpoint endpoint = new ContactEndpoint(null, null, new FakePluginSettings(), new FakeSiteServices(), + new FakeSiteServices(), null, new FakeSiteServices()); + List paths = new ArrayList<>(); + for (Route r : endpoint.routes()) { + if (!r.anonymous()) { + paths.add(r.pathPattern()); + } + } + return paths; + } + + @Test + void theOperatorActionsAreTheInstallAndTheSmtpTest() { + assertEquals(List.of("/contact/install-page", "/contact/smtp-test"), operatorActions()); + } + + @Test + void everyOperatorActionIsAPostFormCarryingTheCsrfToken() throws IOException { + String html = read("admin.html"); + String logic = read("admin.th.xml"); + for (String action : operatorActions()) { + Matcher form = FORM.matcher(html); + boolean found = false; + while (form.find()) { + String attrs = form.group(1); + if (!attrs.contains("action=\"" + action + "\"")) { + continue; + } + found = true; + assertTrue(attrs.contains("method=\"post\""), action + " must be submitted by POST: " + attrs); + Matcher csrf = CSRF_INPUT.matcher(form.group(2)); + assertTrue(csrf.find(), action + "'s form carries a hidden _csrf field"); + String id = csrf.group(1); + assertTrue(logic.contains(""), + "#" + id + " is bound to the console session's CSRF token in admin.th.xml"); + } + assertTrue(found, "the admin fragment has a form for " + action); + } + } + + @Test + void noLinkPointsAtAnOperatorAction() throws IOException { + String html = read("admin.html"); + for (String action : operatorActions()) { + assertFalse(html.contains("href=\"" + action), "a link is a GET and would not carry the token: " + action); + } + } + + @Test + void theAdminFragmentsIdsAreUnique() throws IOException { + // A duplicate id in a decoupled template is a hard Thymeleaf error that would 500 the settings page. + Matcher ids = Pattern.compile("\\bid=\"([^\"]+)\"").matcher(read("admin.html")); + Set seen = new HashSet<>(); + while (ids.find()) { + assertTrue(seen.add(ids.group(1)), "duplicate id " + ids.group(1)); + } + } +} diff --git a/plugins/contact/src/test/java/mx/quest/contact/ContactConfigTest.java b/plugins/contact/src/test/java/mx/quest/contact/ContactConfigTest.java new file mode 100644 index 0000000..0bd3776 --- /dev/null +++ b/plugins/contact/src/test/java/mx/quest/contact/ContactConfigTest.java @@ -0,0 +1,226 @@ +package mx.quest.contact; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.Reader; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import mx.quest.runway.spi.CaptchaService; +import mx.quest.runway.spi.ContentWidget; +import mx.quest.runway.spi.EndpointContributor; +import mx.quest.runway.spi.model.CaptchaWidget; +import mx.quest.runway.spi.model.SiteView; +import mx.quest.runway.spi.service.PluginSettings; +import mx.quest.runway.spi.service.PluginSiteFiles; +import mx.quest.runway.spi.testkit.FakePluginSettings; +import mx.quest.runway.spi.testkit.FakeSiteServices; +import mx.quest.runway.spi.testkit.TempDirSiteFiles; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.yaml.snakeyaml.Yaml; + +/** + * The plugin's contract with the host, checked at build time: the wiring over SPI services only, the bean-name + * rule, the bean names the templates reference, the descriptor (SPI floor, release version, the personal-data + * declaration matching the file the store writes), the i18n bundles, and that the compiled classes link nothing of + * the host but the SPI — the same things the kernel's load-time checks warn about (and refuse from Runway 1.0). + */ +class ContactConfigTest { + + private static final String PREFIX = "contact"; + + private static Set beanMethodNames() { + return Arrays.stream(ContactConfig.class.getDeclaredMethods()) + .filter(m -> m.isAnnotationPresent(Bean.class)) + .map(Method::getName) + .collect(Collectors.toCollection(TreeSet::new)); + } + + @SuppressWarnings("unchecked") + private static Map descriptor() throws IOException { + try (Reader in = Files.newBufferedReader(Path.of("plugin.yml"), StandardCharsets.UTF_8)) { + return (Map) new Yaml().load(in); + } + } + + @Test + void wiresEverythingFromSpiServicesUnderPrefixedNames(@TempDir Path sites) throws IOException { + Files.createDirectories(sites.resolve("acme")); + FakeSiteServices kernel = new FakeSiteServices() + .site(new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null)) + .page("acme", "contact", "/kontakt"); + try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) { + ctx.registerBean(PluginSettings.class, () -> new FakePluginSettings() + .site("acme", Map.of("smtpHost", "mail.example.com", "toAddress", "owner@example.com"))); + ctx.registerBean(PluginSiteFiles.class, () -> new TempDirSiteFiles(sites, "contact")); + ctx.registerBean(FakeSiteServices.class, () -> kernel); + ctx.registerBean(CaptchaService.class, () -> new CaptchaService() { + @Override + public CaptchaWidget widgetForSite(String siteId) { + return CaptchaWidget.inactive(); + } + + @Override + public boolean verify(String siteId, String token, String clientIp) { + return true; + } + }); + ctx.register(ContactConfig.class); + ctx.refresh(); + + assertInstanceOf(ContactWidget.class, ctx.getBean("contactWidget", ContentWidget.class)); + assertInstanceOf(ContactEndpoint.class, ctx.getBean("contactEndpoint", EndpointContributor.class)); + ctx.getBean("contactStore", ContactStore.class).add("acme", "Ann", "a@example.com", "hi", 1L); + ContactAdminModel model = ctx.getBean("contactAdminModel", ContactAdminModel.class); + assertEquals(1, model.count("acme"), "the admin model reads the store over the injected site files"); + assertTrue(model.smtpConfigured("acme"), "…and the relay over the injected settings"); + assertEquals("/kontakt", model.pagePath("acme"), "…and the page through SitePages"); + assertTrue(model.pageInstalled("acme")); + assertFalse(model.pageInstalled("other")); + } + } + + @Test + void everyBeanNameStartsWithThePluginIdInLowerCamelCase() { + Set names = beanMethodNames(); + assertEquals(Set.of("contactStore", "contactMailTransport", "contactMailer", "contactWidget", + "contactEndpoint", "contactAdminModel"), names); + for (Method m : ContactConfig.class.getDeclaredMethods()) { + Bean bean = m.getAnnotation(Bean.class); + if (bean != null) { + for (String alias : bean.name()) { + assertTrue(alias.startsWith(PREFIX), "an explicit bean name must start with " + PREFIX + ": " + alias); + } + } + } + } + + @Test + void everyBeanTheTemplatesReferenceIsOneOfOurs() throws IOException { + Set referenced = new TreeSet<>(); + try (Stream files = Files.list(Path.of("templates"))) { + for (Path file : files.filter(p -> p.toString().endsWith(".th.xml")).toList()) { + // XML comments explain the ${@bean} rules in prose; only the live attributes count. + String live = Files.readString(file, StandardCharsets.UTF_8).replaceAll("(?s)", ""); + Matcher m = Pattern.compile("\\$\\{\\s*!?\\s*@(\\w+)").matcher(live); + while (m.find()) { + referenced.add(m.group(1)); + } + } + } + assertEquals(Set.of("contactAdminModel"), referenced, "the console templates read the admin model only"); + assertTrue(beanMethodNames().containsAll(referenced), "templates reference unknown beans: " + referenced); + } + + @Test + void theDescriptorDeclaresTheSpiFloorAndTheReleaseVersion() throws IOException { + Map 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("runway-plugin-contact\\s*([^<]+)") + .matcher(pom); + assertTrue(version.find()); + assertEquals(version.group(1), String.valueOf(yml.get("version")), "plugin.yml and pom.xml agree on the version"); + assertFalse(pom.contains("runway-app"), "no runway-app dependency in any scope"); + } + + @Test + @SuppressWarnings("unchecked") + void theSubmissionsFileIsDeclaredPersonalDataSoTransferCopiesLeaveItOut() throws IOException { + Map siteData = (Map) descriptor().get("siteData"); + assertTrue(siteData != null, "plugin.yml declares siteData"); + List personal = (List) siteData.get("personal"); + assertEquals(List.of(ContactStore.FILE), personal, + "exactly the file the store writes (visitor names, emails, messages) is personal data"); + } + + @Test + void theSmtpPasswordIsDeclaredASecret() throws IOException { + @SuppressWarnings("unchecked") + List> schema = (List>) descriptor().get("siteSettings"); + Map password = schema.stream() + .filter(s -> ContactMailer.PASSWORD_KEY.equals(s.get("key"))).findFirst().orElseThrow(); + assertEquals("secret", password.get("type"), + "PluginSettings.secret hands out only keys declared type: secret (and site() leaves them out)"); + } + + @Test + void theSmtpPasswordIsBoundToTheRelayLogin() throws IOException { + // secretBoundTo: a save that changes the relay's host, port or username without retyping the password makes + // the kernel drop the stored password, so a settings editor cannot repoint the saved credentials at a server + // of their choosing. Every bound key must be a declared setting, or the binding silently binds nothing. + @SuppressWarnings("unchecked") + List> schema = (List>) descriptor().get("siteSettings"); + Map password = schema.stream() + .filter(s -> ContactMailer.PASSWORD_KEY.equals(s.get("key"))).findFirst().orElseThrow(); + assertEquals(List.of("smtpHost", "smtpPort", "smtpUsername", "smtpStarttls", "smtpSsl"), password.get("secretBoundTo"), + "the stored SMTP password is bound to the host, port and username it was typed for"); + List declared = schema.stream().map(s -> s.get("key")).toList(); + for (Object bound : (List) password.get("secretBoundTo")) { + assertTrue(declared.contains(bound), "secretBoundTo names a declared setting: " + bound); + } + } + + @Test + void theEnglishAndSpanishBundlesDefineTheSameKeys() throws IOException { + assertEquals(keys("i18n/messages.properties"), keys("i18n/messages_es.properties")); + Set en = keys("i18n/messages.properties"); + for (String key : List.of("contact.page.installed", "contact.page.pending", "contact.page.blocked", + "contact.page.exists", "contact.page.failed", "contact.page.other")) { + assertTrue(en.contains(key), "every install outcome has words: " + key); + } + } + + private static Set 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 problems = new ArrayList<>(); + int scanned = 0; + try (Stream files = Files.walk(classes)) { + for (Path file : files.filter(p -> p.toString().endsWith(".class")).toList()) { + scanned++; + String rel = classes.relativize(file).toString().replace('\\', '/'); + if (rel.startsWith("mx/quest/runway/")) { + problems.add(rel + " lives under mx.quest.runway"); + } + // The constant pool holds class names and descriptors as (modified) UTF-8; Latin-1 keeps every + // byte as one char, so an ASCII pattern finds them without parsing the class file. + Matcher m = host.matcher(new String(Files.readAllBytes(file), StandardCharsets.ISO_8859_1)); + while (m.find()) { + problems.add(rel + " → " + m.group()); + } + } + } + assertTrue(scanned >= 12, "the compiled classes were found (" + scanned + ")"); + assertTrue(problems.isEmpty(), "host linkage: " + problems); + } +} diff --git a/plugins/contact/src/test/java/mx/quest/contact/ContactEndpointTest.java b/plugins/contact/src/test/java/mx/quest/contact/ContactEndpointTest.java new file mode 100644 index 0000000..954f106 --- /dev/null +++ b/plugins/contact/src/test/java/mx/quest/contact/ContactEndpointTest.java @@ -0,0 +1,418 @@ +package mx.quest.contact; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import mx.quest.runway.spi.CaptchaService; +import mx.quest.runway.spi.model.CaptchaWidget; +import mx.quest.runway.spi.model.Finding; +import mx.quest.runway.spi.model.InstallResult; +import mx.quest.runway.spi.model.Route; +import mx.quest.runway.spi.model.RouteRequest; +import mx.quest.runway.spi.model.RouteResponse; +import mx.quest.runway.spi.model.Severity; +import mx.quest.runway.spi.model.SiteView; +import mx.quest.runway.spi.model.StarterPage; +import mx.quest.runway.spi.service.SitePages; +import mx.quest.runway.spi.testkit.FakePluginSettings; +import mx.quest.runway.spi.testkit.FakeSiteServices; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * The contact plugin's request surface — it owns no visible page. Covered here: the anonymous + * {@code POST /contact/submit} handler (303 back to the form's page with a {@code ?contact=…} outcome; POST only, + * fields from the body only; store-then-send ordering; honeypot, invalid and CAPTCHA gating with the gated client + * IP; return-path safety), the operator-gated {@code POST /contact/install-page} with each {@code SitePages} + * outcome, and the operator-gated {@code POST /contact/smtp-test}. Both operator actions change state, so they are + * non-anonymous POST routes (the kernel's CSRF check applies) and a GET changes nothing. The form's HTML is covered + * in {@link ContactWidgetTest}; the console forms that carry the CSRF token in {@link ContactAdminTemplateTest}. + */ +class ContactEndpointTest { + + private static final SiteView ACME = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null); + private static final String CLIENT_IP = "203.0.113.7"; + + private ContactStore store; + private ContactMailer mailer; + private FakePluginSettings settings; + private FakeSiteServices kernel; + private CaptchaService captcha; + private ContactEndpoint endpoint; + + @BeforeEach + void setUp() { + store = mock(ContactStore.class); + mailer = mock(ContactMailer.class); + when(mailer.send(anyString(), anyString(), anyString(), anyString(), anyString())) + .thenReturn(MailSendResult.sent()); + settings = new FakePluginSettings().defaults(Map.of("enabled", true)); + kernel = new FakeSiteServices().site(ACME).current("acme"); + captcha = mock(CaptchaService.class); + // Default: no challenge configured (submissions flow through the non-CAPTCHA path). + when(captcha.widgetForSite(any())).thenReturn(CaptchaWidget.inactive()); + endpoint = new ContactEndpoint(store, mailer, settings, kernel, kernel, captcha, kernel); + } + + private static RouteRequest request(String method, String path, Map> query, + Map> form, Map headers) { + return new RouteRequest(ACME, Locale.ENGLISH, method, path, query, headers, new byte[0], form, CLIENT_IP, + "https://acme.test"); + } + + /** A POST /contact/submit with the given BODY fields; carries a {@code return} of /home. */ + private RouteResponse submit(Map> fields) { + Map> form = new HashMap<>(fields); + form.putIfAbsent("return", List.of("/home")); + return endpoint.handle(request("POST", "/contact/submit", Map.of(), form, Map.of())); + } + + private static Map> valid() { + return Map.of("name", List.of("Ann"), "email", List.of("ann@example.com"), + "message", List.of("Hello there"), "website", List.of("")); + } + + private static Map> with(Map> base, String key, String value) { + Map> copy = new HashMap<>(base); + copy.put(key, List.of(value)); + return copy; + } + + private static String location(RouteResponse res) { + return res.headers().get("Location"); + } + + private static String text(RouteResponse res) { + return new String(res.body(), StandardCharsets.UTF_8); + } + + private void verifyNothingStoredOrSent() { + verify(store, never()).add(anyString(), anyString(), anyString(), anyString(), anyLong()); + verify(mailer, never()).send(anyString(), anyString(), anyString(), anyString(), anyString()); + } + + // ---- routes ---------------------------------------------------------------------------------------------- + + @Test + void theSubmitRouteIsAnAnonymousPostAndTheOperatorActionsAreNot() { + List routes = endpoint.routes(); + Route submit = routes.stream().filter(r -> r.pathPattern().equals("/contact/submit")).findFirst().orElseThrow(); + assertEquals("POST", submit.method()); + assertTrue(submit.anonymous(), "declared anonymous: the kernel exempts exactly this POST from CSRF"); + assertEquals(1, routes.stream().filter(r -> r.pathPattern().equals("/contact/submit")).count(), + "no GET submit route remains"); + for (Route r : routes) { + if (!r.pathPattern().equals("/contact/submit")) { + assertFalse(r.anonymous(), "the operator actions keep the principal (and the CSRF rule): " + r); + } + } + } + + @Test + void everyRouteIsAPostSoNoLinkOrImageCanChangeState() { + List routes = endpoint.routes(); + assertEquals(List.of("/contact/submit", "/contact/install-page", "/contact/smtp-test"), + routes.stream().map(Route::pathPattern).toList()); + for (Route r : routes) { + assertEquals("POST", r.method(), "a GET route would let a cross-site link trigger it: " + r); + } + } + + // ---- POST /contact/submit -------------------------------------------------------------------------------- + + @Test + void aValidPostRedirects303SentAndStoresAndEmails() { + RouteResponse res = submit(valid()); + assertEquals(303, res.status(), "post/redirect/get"); + assertEquals("/home?contact=sent", location(res), "it lands back on the form's page with a success flag"); + verify(store).add(eq("acme"), eq("Ann"), eq("ann@example.com"), eq("Hello there"), anyLong()); + verify(mailer).send(eq("acme"), eq("Acme"), eq("Ann"), eq("ann@example.com"), eq("Hello there")); + } + + @Test + void theRedirectCarriesTheOutcomeOnlyNeverASubmittedValue() { + String where = location(submit(valid())); + for (String personal : List.of("Ann", "ann", "example.com", "Hello")) { + assertFalse(where.contains(personal), "no personal data in the Location: " + where); + } + } + + @Test + void aGetSubmissionIsNotAcceptedAndStoresNothing() { + Map> query = with(valid(), "return", "/home"); + RouteResponse res = endpoint.handle(request("GET", "/contact/submit", query, Map.of(), Map.of())); + assertEquals(404, res.status(), "1.x's GET submission is gone: only the anonymous POST is handled"); + verifyNothingStoredOrSent(); + } + + @Test + void fieldsInTheQueryStringAreIgnoredOnAPost() { + Map> query = valid(); + RouteResponse res = endpoint.handle(request("POST", "/contact/submit", query, + Map.of("return", List.of("/home")), Map.of())); + assertEquals("/home?contact=invalid", location(res), "personal data is read from the body only"); + verifyNothingStoredOrSent(); + } + + @Test + void aFilledHoneypotFakesSuccessWithoutStoringOrEmailing() { + RouteResponse res = submit(with(valid(), "website", "http://spam.example")); + assertEquals("/home?contact=sent", location(res), "the bot sees a fake success"); + verifyNothingStoredOrSent(); + } + + @Test + void anInvalidEmailRedirectsWithTheInvalidFlag() { + assertEquals("/home?contact=invalid", location(submit(with(valid(), "email", "not-an-email")))); + verifyNothingStoredOrSent(); + } + + @Test + void aBlankMessageRedirectsWithTheInvalidFlag() { + assertEquals("/home?contact=invalid", location(submit(with(valid(), "message", " ")))); + verifyNothingStoredOrSent(); + } + + @Test + void anActiveCaptchaWithoutATokenRefusesThePost() { + when(captcha.widgetForSite(any())).thenReturn(new CaptchaWidget( + true, "g-recaptcha-response", "
")); + when(captcha.verify(any(), any(), any())).thenReturn(false); + RouteResponse res = submit(valid()); + assertEquals("/home?contact=captcha", location(res)); + verify(captcha).verify("acme", "", CLIENT_IP); + verifyNothingStoredOrSent(); + } + + @Test + void anActiveCaptchaIsVerifiedWithTheBodyTokenAndTheGatedClientIp() { + when(captcha.widgetForSite(any())).thenReturn(new CaptchaWidget( + true, "g-recaptcha-response", "
")); + when(captcha.verify(eq("acme"), eq("good-token"), eq(CLIENT_IP))).thenReturn(true); + RouteResponse res = submit(with(valid(), "g-recaptcha-response", "good-token")); + assertEquals("/home?contact=sent", location(res)); + verify(store).add(eq("acme"), eq("Ann"), eq("ann@example.com"), eq("Hello there"), anyLong()); + } + + @Test + void aCaptchaTokenOnlyInTheQueryStringDoesNotCount() { + when(captcha.widgetForSite(any())).thenReturn(new CaptchaWidget( + true, "g-recaptcha-response", "
")); + when(captcha.verify(eq("acme"), eq("good-token"), any())).thenReturn(true); + Map> form = with(valid(), "return", "/home"); + RouteResponse res = endpoint.handle(request("POST", "/contact/submit", + Map.of("g-recaptcha-response", List.of("good-token")), form, Map.of())); + assertEquals("/home?contact=captcha", location(res)); + verifyNothingStoredOrSent(); + } + + @Test + void anActiveCaptchaThatFailsRedirectsWithTheCaptchaFlag() { + when(captcha.widgetForSite(any())).thenReturn(new CaptchaWidget( + true, "g-recaptcha-response", "
")); + when(captcha.verify(any(), any(), any())).thenReturn(false); + assertEquals("/home?contact=captcha", location(submit(with(valid(), "g-recaptcha-response", "bad")))); + verifyNothingStoredOrSent(); + } + + @Test + void disabledContactReturns404() { + settings.site("acme", Map.of("enabled", false)); + assertEquals(404, submit(valid()).status()); + verifyNothingStoredOrSent(); + } + + @Test + void aFailedSendRedirectsQueuedButStillStores() { + when(mailer.send(anyString(), anyString(), anyString(), anyString(), anyString())) + .thenReturn(MailSendResult.failed("relay refused")); + assertEquals("/home?contact=queued", location(submit(valid())), "a real relay failure is a delayed note"); + verify(store).add(eq("acme"), eq("Ann"), eq("ann@example.com"), eq("Hello there"), anyLong()); + } + + @Test + void anUnconfiguredRelayRedirectsSentSilentlyAndStores() { + when(mailer.send(anyString(), anyString(), anyString(), anyString(), anyString())) + .thenReturn(MailSendResult.notConfigured()); + assertEquals("/home?contact=sent", location(submit(valid())), "a store-only site never shows a delivery note"); + verify(store).add(eq("acme"), eq("Ann"), eq("ann@example.com"), eq("Hello there"), anyLong()); + } + + @Test + void theRefererIsUsedWhenNoReturnFieldIsGiven() { + RouteResponse res = endpoint.handle(request("POST", "/contact/submit", Map.of(), valid(), + Map.of("Referer", "https://acme.test/contact-us?x=1"))); + assertEquals("/contact-us?contact=sent", location(res), "it lands back on the Referer page (query stripped)"); + } + + @Test + void aForeignReturnFieldIsRejectedAndFallsBackToRoot() { + RouteResponse res = submit(with(valid(), "return", "https://evil.example/steal")); + assertEquals("/?contact=sent", location(res), "an off-origin return target is ignored (no open redirect)"); + assertEquals("/?contact=sent", location(submit(with(valid(), "return", "//evil.example/x")))); + } + + // ---- /contact/install-page (operator-gated) --------------------------------------------------------------- + + private RouteResponse install() { + return endpoint.handle(request("POST", "/contact/install-page", Map.of(), Map.of(), Map.of())); + } + + @Test + void theInstallPageIsHiddenFromCallersWithoutThePermission() { + RouteResponse res = install(); + assertEquals(404, res.status(), "fail closed: the action is not revealed to the unauthorized"); + assertTrue(kernel.installs().isEmpty(), "nothing was installed"); + } + + @Test + void aGetOnTheInstallPathInstallsNothingEvenForAnAuthorizedOperator() { + kernel.grant("contact|settings"); + for (String method : List.of("GET", "HEAD", "PUT", "DELETE")) { + RouteResponse res = endpoint.handle(request(method, "/contact/install-page", Map.of(), Map.of(), Map.of())); + assertEquals(404, res.status(), method + " is not the install action"); + } + assertTrue(kernel.installs().isEmpty(), "following a link (or loading an ) must not install the page"); + } + + @Test + void theInstallMethodIsMatchedCaseInsensitively() { + kernel.grant("contact|settings"); + RouteResponse res = endpoint.handle(request("post", "/contact/install-page", Map.of(), Map.of(), Map.of())); + assertEquals(200, res.status()); + assertEquals(1, kernel.installs().size()); + } + + @Test + void anInstallThatPublishesSaysWhereThePageIs() { + kernel.grant("contact|settings").message("acme", "contact.page.title", "Contact us"); + RouteResponse res = install(); + assertEquals(200, res.status()); + assertEquals("Contact page installed at /contact", text(res)); + StarterPage page = kernel.installs().get(0); + assertEquals("contact", page.slug(), "installed at the stable slug"); + assertEquals("/contact", page.path()); + assertEquals(Map.of("en", "Contact us"), page.titles(), "titled in the site's default language"); + assertFalse(page.noindex(), "a contact page is meant to be found"); + assertTrue(page.html().contains("data-widget=\"contact/form\""), "the page carries the widget anchor"); + assertTrue(page.html().contains("Contact us")); + assertTrue(page.logic().contains("${master}"), "the chrome comes from the master"); + } + + @Test + void anInstallOnAReviewedSiteSaysItIsWaitingForReview() { + kernel.grant("contact|settings").nextInstall(InstallResult.Outcome.PENDING_REVIEW); + RouteResponse res = install(); + assertEquals(200, res.status()); + assertTrue(text(res).contains("waiting in the review queue"), text(res)); + assertTrue(text(res).endsWith("/contact")); + } + + @Test + void anInstallBlockedByTheQualityChecksSaysItIsADraftAndWhy() { + kernel.grant("contact|settings").nextInstall(InstallResult.Outcome.DRAFT_BLOCKED, + new Finding(Severity.ERROR, "content.thin", "The page has almost no text.")); + RouteResponse res = install(); + assertEquals(200, res.status()); + assertTrue(text(res).contains("as a draft"), text(res)); + assertTrue(text(res).contains("- content.thin: The page has almost no text."), "the blocking finding: " + text(res)); + } + + @Test + void aSecondInstallChangesNothingAndSaysWhereTheExistingPageIs() { + kernel.grant("contact|settings").page("acme", "contact", "/hola"); + RouteResponse res = install(); + assertEquals(200, res.status(), "an existing page is not an error — the action is idempotent"); + assertEquals("A contact page already exists at /hola", text(res), "the page's current path, wherever it moved"); + } + + @Test + void aFailedInstallIsA500WithTheOperatorsMessage() { + SitePages failing = mock(SitePages.class); + when(failing.install(any(), any())).thenThrow(new IllegalStateException("/contact is served by another page")); + kernel.grant("contact|settings"); + ContactEndpoint withFailingPages = new ContactEndpoint(store, mailer, settings, kernel, kernel, captcha, failing); + RouteResponse res = withFailingPages.handle(request("POST", "/contact/install-page", Map.of(), Map.of(), Map.of())); + assertEquals(500, res.status()); + assertEquals("Could not install the contact page.", text(res)); + } + + @Test + void theOperatorAnswersAreConsoleMessages() { + kernel.grant("contact|settings").message(null, "contact.page.installed", "Página de contacto instalada en"); + assertEquals("Página de contacto instalada en /contact", text(install()), + "in the operator's console language (Messages.console), not the visitor's"); + } + + // ---- /contact/smtp-test (operator-gated) ------------------------------------------------------------------ + + private RouteResponse smtpTest(Map> form) { + return endpoint.handle(request("POST", "/contact/smtp-test", Map.of(), form, Map.of())); + } + + @Test + void theSmtpTestIsHiddenFromCallersWithoutThePermission() { + assertEquals(404, smtpTest(Map.of()).status(), "fail closed: the surface is not revealed to the unauthorized"); + verifyNoInteractions(mailer); + } + + @Test + void theSmtpTestSendsForAnAuthorizedCaller() { + kernel.grant("contact|settings"); + when(mailer.sendTest(eq("acme"), eq("Acme"), eq("me@example.com"))).thenReturn(MailSendResult.sent()); + RouteResponse res = smtpTest(Map.of("to", List.of(" me@example.com "))); + assertEquals(200, res.status()); + assertEquals("Test message sent.", text(res)); + } + + @Test + void theSmtpTestWithoutARecipientUsesTheConfiguredOne() { + kernel.grant("contact|settings"); + when(mailer.sendTest(eq("acme"), eq("Acme"), eq(""))).thenReturn(MailSendResult.sent()); + assertEquals(200, smtpTest(Map.of()).status()); + verify(mailer).sendTest("acme", "Acme", ""); + } + + @Test + void aGetOnTheSmtpTestPathSendsNothingEvenForAnAuthorizedOperator() { + kernel.grant("contact|settings"); + RouteResponse res = endpoint.handle(request("GET", "/contact/smtp-test", + Map.of("to", List.of("victim@example.com")), Map.of(), Map.of())); + assertEquals(404, res.status(), "a cross-site link must not make the server send an email"); + verifyNoInteractions(mailer); + } + + @Test + void theSmtpTestRecipientIsReadFromTheBodyNeverTheQueryString() { + kernel.grant("contact|settings"); + when(mailer.sendTest(anyString(), anyString(), any())).thenReturn(MailSendResult.sent()); + endpoint.handle(request("POST", "/contact/smtp-test", Map.of("to", List.of("victim@example.com")), + Map.of(), Map.of())); + verify(mailer).sendTest("acme", "Acme", ""); + verify(mailer, never()).sendTest(anyString(), anyString(), eq("victim@example.com")); + } + + @Test + void aFailedSmtpTestReportsA502() { + kernel.grant("contact|settings"); + when(mailer.sendTest(anyString(), anyString(), any())).thenReturn(MailSendResult.failed("timeout")); + RouteResponse res = smtpTest(Map.of()); + assertEquals(502, res.status(), "a failed test reports a bad-gateway status"); + assertTrue(text(res).contains("timeout")); + } +} diff --git a/plugins/contact/src/test/java/mx/quest/contact/ContactMailerTest.java b/plugins/contact/src/test/java/mx/quest/contact/ContactMailerTest.java new file mode 100644 index 0000000..e63f077 --- /dev/null +++ b/plugins/contact/src/test/java/mx/quest/contact/ContactMailerTest.java @@ -0,0 +1,201 @@ +package mx.quest.contact; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import jakarta.mail.Message; +import jakarta.mail.MessagingException; +import jakarta.mail.internet.MimeMessage; +import jakarta.mail.PasswordAuthentication; +import jakarta.mail.Session; +import java.util.HashMap; +import java.util.Map; +import mx.quest.runway.spi.testkit.FakePluginSettings; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +/** + * The send path: {@link ContactMailer} builds the expected MIME message and hands it to a MOCK + * {@link MailTransport} (no socket), reports a send failure without throwing, reports "not configured" when no + * relay is set, and takes the SMTP password ONLY from {@code PluginSettings.secret(site, "smtpPassword")} — the + * kernel decrypts the {@code ENC(...)} value; the plugin never sees ciphertext, never reads a password out of the + * settings view, and never prints it. + */ +class ContactMailerTest { + + private static final Map RELAY = Map.of( + "smtpHost", "mail.example.com", + "smtpPort", 587L, + "smtpAuth", true, + "smtpUsername", "postmaster", + "smtpStarttls", true, + "fromAddress", "site@example.com", + "toAddress", "owner@example.com"); + + /** The plugin's per-site settings as the kernel hands them over: RELAY for acme, the password a secret. */ + private static FakePluginSettings settings(Map acme) { + return new FakePluginSettings().site("acme", acme).secret("acme", "smtpPassword", "s3cret"); + } + + /** The password the built session's authenticator would answer the relay with. */ + private static PasswordAuthentication credentials(Session session) { + return session.requestPasswordAuthentication(null, 587, "smtp", null, null); + } + + @Test + void aSubmissionBuildsTheExpectedMimeMessageAndCallsTheTransport() throws Exception { + MailTransport transport = mock(MailTransport.class); + ContactMailer mailer = new ContactMailer(settings(RELAY), transport); + + MailSendResult result = mailer.send("acme", "Acme", "Ann", "ann@example.com", "Hello there"); + + assertEquals(MailSendResult.Status.SENT, result.status()); + ArgumentCaptor captor = ArgumentCaptor.forClass(MimeMessage.class); + verify(transport).send(captor.capture()); + MimeMessage msg = captor.getValue(); + assertEquals("site@example.com", ((jakarta.mail.internet.InternetAddress) msg.getFrom()[0]).getAddress()); + assertEquals("owner@example.com", + ((jakarta.mail.internet.InternetAddress) msg.getRecipients(Message.RecipientType.TO)[0]).getAddress()); + // Reply-To is the visitor so the site can reply straight to them. + assertEquals("ann@example.com", + ((jakarta.mail.internet.InternetAddress) msg.getReplyTo()[0]).getAddress()); + assertTrue(msg.getSubject().startsWith("[Acme] "), "subject is site-prefixed: " + msg.getSubject()); + String body = (String) msg.getContent(); + assertTrue(body.contains("ann@example.com"), "the body carries the submitter email"); + assertTrue(body.contains("Hello there"), "the body carries the message"); + } + + @Test + void aTransportFailureIsReportedNotThrown() throws Exception { + MailTransport transport = mock(MailTransport.class); + doThrow(new MessagingException("relay refused")).when(transport).send(any()); + ContactMailer mailer = new ContactMailer(settings(RELAY), transport); + + MailSendResult result = mailer.send("acme", "Acme", "Ann", "ann@example.com", "Hi"); + + assertEquals(MailSendResult.Status.FAILED, result.status()); + assertNotNull(result.detail()); + assertTrue(result.detail().contains("relay refused"), "the reason is surfaced: " + result.detail()); + } + + @Test + void anUnconfiguredRelayReportsNotConfiguredAndNeverTouchesTheTransport() throws Exception { + MailTransport transport = mock(MailTransport.class); + // Blank host + recipient ⇒ not configured. + ContactMailer mailer = new ContactMailer(settings(Map.of()), transport); + + MailSendResult result = mailer.send("acme", "Acme", "Ann", "ann@example.com", "Hi"); + + assertEquals(MailSendResult.Status.NOT_CONFIGURED, result.status()); + verify(transport, never()).send(any()); + } + + @Test + void aSmtpTestSendsToTheGivenAddress() throws Exception { + MailTransport transport = mock(MailTransport.class); + ContactMailer mailer = new ContactMailer(settings(RELAY), transport); + + MailSendResult result = mailer.sendTest("acme", "Acme", "check@example.com"); + + assertEquals(MailSendResult.Status.SENT, result.status()); + ArgumentCaptor captor = ArgumentCaptor.forClass(MimeMessage.class); + verify(transport).send(captor.capture()); + assertEquals("check@example.com", ((jakarta.mail.internet.InternetAddress) + captor.getValue().getRecipients(Message.RecipientType.TO)[0]).getAddress()); + } + + @Test + void thePasswordIsTheSitesSecretInClearAndReachesTheRelayCredentials() throws Exception { + MailTransport transport = mock(MailTransport.class); + ContactMailer mailer = new ContactMailer(settings(RELAY), transport); + + SmtpSettings smtp = mailer.settingsFor("acme"); + assertEquals("s3cret", smtp.password(), "PluginSettings.secret supplies the password, already in clear"); + mailer.send("acme", "Acme", "Ann", "ann@example.com", "Hi"); + ArgumentCaptor captor = ArgumentCaptor.forClass(MimeMessage.class); + verify(transport).send(captor.capture()); + PasswordAuthentication auth = credentials(captor.getValue().getSession()); + assertEquals("postmaster", auth.getUserName()); + assertEquals("s3cret", auth.getPassword(), "the relay is offered the secret's clear value"); + } + + @Test + void aPasswordFoundInTheSettingsViewIsNeverUsed() { + // The kernel leaves secret keys out of the view; a value there anyway (a hand-built view, a future change) + // must not become the password: only the declared secret, read through secret(), is trusted. + Map withLeak = new HashMap<>(RELAY); + withLeak.put("smtpPassword", "ENC(ciphertext-not-a-password)"); + ContactMailer viewOnly = new ContactMailer(new FakePluginSettings().site("acme", withLeak), + mock(MailTransport.class)); + assertEquals("", viewOnly.settingsFor("acme").password(), "no secret ⇒ no password, whatever the view holds"); + + ContactMailer both = new ContactMailer(settings(withLeak), mock(MailTransport.class)); + assertEquals("s3cret", both.settingsFor("acme").password(), "the secret wins over anything in the view"); + } + + @Test + void theSecretIsReadForTheSendingSiteOnly() { + FakePluginSettings settings = settings(RELAY).site("other", RELAY).secret("other", "smtpPassword", "other-pw"); + ContactMailer mailer = new ContactMailer(settings, mock(MailTransport.class)); + assertEquals("s3cret", mailer.settingsFor("acme").password()); + assertEquals("other-pw", mailer.settingsFor("other").password(), "each site authenticates with its own secret"); + assertEquals("", mailer.settingsFor("nobody").password(), "a site with no secret has no password"); + } + + @Test + void thePasswordNeverAppearsInTheSettingsText() { + String text = new ContactMailer(settings(RELAY), mock(MailTransport.class)).settingsFor("acme").toString(); + assertFalse(text.contains("s3cret"), "masked in logs: " + text); + assertTrue(text.contains("password=")); + } + + @Test + void settingsAreReadTypedWithTheDescriptorDefaultsAndAClampedPort() { + Map odd = new HashMap<>(RELAY); + odd.put("smtpPort", 99999L); + odd.put("smtpHost", " mail.example.com "); + SmtpSettings smtp = new ContactMailer(settings(odd), mock(MailTransport.class)).settingsFor("acme"); + assertEquals(65535, smtp.port(), "the port is clamped to 1..65535"); + assertEquals("mail.example.com", smtp.host(), "values are stripped"); + SmtpSettings bare = new ContactMailer(new FakePluginSettings(), mock(MailTransport.class)).settingsFor("acme"); + assertEquals(25, bare.port(), "port 25 when unset"); + assertFalse(bare.auth()); + assertFalse(bare.isConfigured(), "no host and no recipient"); + } + + @Test + void implicitTlsRidesSslEnableOnTheSmtpProtocol() { + // Regression: implicit TLS (SMTPS, e.g. 465) must ride mail.smtp.ssl.enable on the smtp protocol. Switching + // to "smtps" left mail.smtp.host unset, so the static Transport.send() (which maps rfc822 -> smtp, ignoring + // mail.transport.protocol) dialed localhost:25 and failed with "Connection refused". + jakarta.mail.Session s = ContactMailer.session(new SmtpSettings( + "mail.example.com", 465, true, "postmaster", "pw", false, true, "site@example.com", "owner@example.com")); + + assertEquals("smtp", s.getProperty("mail.transport.protocol"), "protocol stays smtp (address map ignores smtps)"); + assertEquals("mail.example.com", s.getProperty("mail.smtp.host"), "host on mail.smtp.* (what the send reads)"); + assertEquals("465", s.getProperty("mail.smtp.port")); + assertEquals("true", s.getProperty("mail.smtp.ssl.enable"), "implicit TLS on connect"); + assertNull(s.getProperty("mail.smtps.host"), "no smtps-scoped host the static send would silently ignore"); + assertNull(s.getProperty("mail.smtp.starttls.enable"), "implicit TLS and STARTTLS are mutually exclusive"); + } + + @Test + void starttlsRidesStarttlsEnableOnTheSmtpProtocol() { + jakarta.mail.Session s = ContactMailer.session(new SmtpSettings( + "mail.example.com", 587, false, null, null, true, false, "site@example.com", "owner@example.com")); + + assertEquals("smtp", s.getProperty("mail.transport.protocol")); + assertEquals("587", s.getProperty("mail.smtp.port")); + assertEquals("true", s.getProperty("mail.smtp.starttls.enable"), "opportunistic STARTTLS"); + assertNull(s.getProperty("mail.smtp.ssl.enable"), "STARTTLS mode must not also enable implicit TLS"); + } +} diff --git a/plugins/contact/src/test/java/mx/quest/contact/ContactStoreTest.java b/plugins/contact/src/test/java/mx/quest/contact/ContactStoreTest.java new file mode 100644 index 0000000..5f155e2 --- /dev/null +++ b/plugins/contact/src/test/java/mx/quest/contact/ContactStoreTest.java @@ -0,0 +1,115 @@ +package mx.quest.contact; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import mx.quest.runway.spi.testkit.TempDirSiteFiles; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * The submission store over {@code PluginSiteFiles} (the testkit's {@link TempDirSiteFiles}, which applies the + * kernel's confinement rules): append + newest-first read, field sanitization, the bound, per-site isolation, the + * on-disk location shared with 1.x, and that an unreadable file is never overwritten. + */ +class ContactStoreTest { + + @TempDir + Path sites; + private TempDirSiteFiles files; + private ContactStore store; + + @BeforeEach + void setUp() throws IOException { + Files.createDirectories(sites.resolve("acme")); + Files.createDirectories(sites.resolve("other")); + files = new TempDirSiteFiles(sites, "contact"); + store = new ContactStore(files); + } + + @Test + void appendsAndReadsNewestFirst() { + store.add("acme", "Ann", "ann@example.com", "First message", 1000L); + store.add("acme", "Bob", "bob@example.com", "Second message", 2000L); + + assertEquals(2, store.count("acme")); + List recent = store.recent("acme", 10); + assertEquals("Bob", recent.get(0).name(), "newest first"); + assertEquals("Ann", recent.get(1).name()); + assertEquals("ann@example.com", recent.get(1).email()); + assertEquals(1, store.recent("acme", 1).size(), "the limit is honoured"); + } + + @Test + void writesTheSameFileAs1xSoExistingSubmissionsCarryOver() throws IOException { + Path file = sites.resolve("acme/plugins/contact/submissions.tsv"); + Files.createDirectories(file.getParent()); + Files.writeString(file, "500\tOld\told@example.com\tfrom contact 1.1.2\n", StandardCharsets.UTF_8); + + store.add("acme", "New", "new@example.com", "after the upgrade", 900L); + + assertEquals(2, store.count("acme"), "the 1.x submission is read from the same file"); + List lines = Files.readAllLines(file, StandardCharsets.UTF_8); + assertEquals(List.of("500\tOld\told@example.com\tfrom contact 1.1.2", "900\tNew\tnew@example.com\tafter the upgrade"), + lines, "appended in place, one TSV line each"); + } + + @Test + void tabsAndNewlinesAreSanitizedSoTheTsvFormatHolds() { + store.add("acme", "Eve\tEvil", "e@example.com", "line one\nline two\tindented", 1000L); + ContactSubmission s = store.recent("acme", 10).get(0); + assertEquals("Eve Evil", s.name(), "tabs stripped from the field"); + assertEquals("line one line two indented", s.message(), "newlines/tabs collapsed to spaces"); + } + + @Test + void aFieldIsCappedAndTheFileKeepsOnlyTheMostRecentSubmissions() { + store.add("acme", "Long", "l@example.com", "x".repeat(ContactStore.MAX_FIELD + 50), 1L); + assertEquals(ContactStore.MAX_FIELD, store.recent("acme", 1).get(0).message().length()); + for (int i = 2; i <= ContactStore.MAX_SUBMISSIONS + 1; i++) { + store.add("acme", "N" + i, "n@example.com", "m", i); + } + assertEquals(ContactStore.MAX_SUBMISSIONS, store.count("acme"), "bounded to the most recent"); + assertEquals("N" + (ContactStore.MAX_SUBMISSIONS + 1), store.recent("acme", 1).get(0).name()); + assertTrue(store.recent("acme", ContactStore.MAX_SUBMISSIONS).stream().noneMatch(s -> s.name().equals("Long")), + "the oldest one was dropped"); + } + + @Test + void submissionsAreIsolatedPerSite() { + store.add("acme", "Ann", "a@example.com", "for acme", 1000L); + assertEquals(1, store.count("acme")); + assertEquals(0, store.count("other"), "another site sees none of acme's submissions"); + assertTrue(store.recent("other", 10).isEmpty()); + } + + @Test + void anUnreadableFileIsNeverOverwrittenAndTheConsoleReadsDegradeToEmpty() throws IOException { + // A file over the read cap cannot be read: an append must fail rather than rewrite it from nothing. + ContactStore small = new ContactStore(new TempDirSiteFiles(sites, "contact", 64)); + Path file = sites.resolve("acme/plugins/contact/submissions.tsv"); + Files.createDirectories(file.getParent()); + String big = "1\tA\ta@example.com\t" + "y".repeat(200) + "\n"; + Files.writeString(file, big, StandardCharsets.UTF_8); + + assertThrows(UncheckedIOException.class, () -> small.add("acme", "B", "b@example.com", "hi", 2L)); + assertEquals(big, Files.readString(file, StandardCharsets.UTF_8), "the stored submissions are untouched"); + assertEquals(0, small.count("acme"), "the console count degrades to 0 instead of failing the screen"); + assertTrue(small.recent("acme", 10).isEmpty()); + } + + @Test + void aSiteWithoutAFolderIsAnErrorNotASilentCreate() { + assertThrows(UncheckedIOException.class, () -> store.add("ghost", "A", "a@example.com", "hi", 1L), + "the kernel refuses to create a deleted site's folder; the store reports it"); + assertTrue(Files.notExists(sites.resolve("ghost"))); + } +} diff --git a/plugins/contact/src/test/java/mx/quest/contact/ContactWidgetTest.java b/plugins/contact/src/test/java/mx/quest/contact/ContactWidgetTest.java new file mode 100644 index 0000000..7869421 --- /dev/null +++ b/plugins/contact/src/test/java/mx/quest/contact/ContactWidgetTest.java @@ -0,0 +1,150 @@ +package mx.quest.contact; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import mx.quest.runway.spi.CaptchaService; +import mx.quest.runway.spi.model.CaptchaWidget; +import mx.quest.runway.spi.model.PageMeta; +import mx.quest.runway.spi.model.SiteView; +import mx.quest.runway.spi.model.WidgetView; +import mx.quest.runway.spi.testkit.FakePluginSettings; +import mx.quest.runway.spi.testkit.FakeSiteServices; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * The {@code contact} content widget renders the form inline on a normal page and re-renders the submit outcome + * from the {@code ?contact=…} query the endpoint redirects back with. All rendering (form, thank-you, error + * re-render, CAPTCHA, escaping) lives here — the endpoint only stores/sends/redirects. Settings and messages come + * from the SPI services (testkit fakes). + */ +class ContactWidgetTest { + + private static final SiteView ACME = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null); + + private FakePluginSettings settings; + private FakeSiteServices kernel; + private final AtomicReference challenge = new AtomicReference<>(CaptchaWidget.inactive()); + private ContactWidget widget; + + @BeforeEach + void setUp() { + settings = new FakePluginSettings().defaults(Map.of("enabled", true)); + kernel = new FakeSiteServices().site(ACME); + CaptchaService captcha = new CaptchaService() { + @Override + public CaptchaWidget widgetForSite(String siteId) { + return challenge.get(); + } + + @Override + public boolean verify(String siteId, String token, String clientIp) { + return false; + } + }; + widget = new ContactWidget(settings, kernel, captcha); + } + + private String render(Map query) { + PageMeta page = new PageMeta("home", "Home", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false); + return widget.render(new WidgetView(ACME, page, Locale.ENGLISH, "contact", false, Map.of(), query)).html(); + } + + @Test + void theFormPostsAUrlEncodedBodyToTheAnonymousSubmitRoute() { + String html = render(Map.of()); + assertTrue(html.contains("method=\"post\""), "the form POSTs — its fields never ride a URL: " + html); + assertFalse(html.contains("method=\"get\"")); + assertTrue(html.contains("action=\"/contact/submit\""), "to the anonymous submit route"); + assertTrue(html.contains("enctype=\"application/x-www-form-urlencoded\""), + "the only body an anonymous route accepts"); + assertFalse(html.contains("_csrf"), "no session token: the route is CSRF-exempt by declaration"); + } + + @Test + void aBareRenderShowsTheFormWithTheHoneypotAndTheReturnPath() { + String html = render(Map.of()); + assertTrue(html.contains("name=\"message\""), "the message field is present"); + assertTrue(html.contains("name=\"website\""), "the honeypot field is present"); + // Lands the visitor back on this page (its slug path) after submit; a moved page is caught server-side by Referer. + assertTrue(html.contains("name=\"return\" value=\"/home\""), "the return path is the page the widget lives on"); + } + + @Test + void theReturnPathIsTheRequestPathWhenTheHostProvidesIt() { + // A blog entry (a content source's page) renders this widget from the master chrome: its PageMeta slug + // is a composite identity ("blog:my-post"), NOT a path — the request path from the view must win. + PageMeta entry = new PageMeta("blog:my-post", "My post", "", List.of(Locale.ENGLISH), Locale.ENGLISH, + true, false, "blog"); + String html = widget.render(new WidgetView(ACME, entry, Locale.ENGLISH, "contact", true, Map.of(), + Map.of(), "/es/blog/mi-entrada")).html(); + assertTrue(html.contains("name=\"return\" value=\"/es/blog/mi-entrada\""), + "the return path is the URL as served — never built from the composite slug"); + assertFalse(html.contains("/blog:my-post"), "the composite identity never leaks into a path"); + } + + @Test + void labelsComeFromTheSitesMessagesAndAreEscaped() { + kernel.message("acme", "contact.form.submit", "Envoyer "); + String html = render(Map.of()); + assertTrue(html.contains(">Envoyer <maintenant>"), "Messages.site for the label: " + html); + } + + @Test + void theSentOutcomeShowsAThankYouNotTheForm() { + String html = render(Map.of("contact", "sent")); + assertTrue(html.contains("rw-contact-success"), "a thank-you is shown"); + assertTrue(html.contains("Thanks — your message has been sent."), "the default thank-you text"); + assertFalse(html.contains("name=\"message\""), "the form is replaced by the confirmation"); + } + + @Test + void theQueuedOutcomeThanksAndNotesTheDelayedDeliveryInsteadOfShowingTheFormAgain() { + String html = render(Map.of("contact", "queued")); + assertTrue(html.contains("rw-contact-success"), "the message was stored: thank the visitor"); + assertTrue(html.contains("email delivery is delayed"), "and say the email is late: " + html); + assertFalse(html.contains("name=\"message\""), "no empty form inviting a duplicate submission"); + assertFalse(render(Map.of("contact", "sent")).contains("delayed"), "a plain success carries no note"); + } + + @Test + void theConfiguredThankYouWinsAndIsEscaped() { + settings.site("acme", Map.of("successMessage", "x")); + String html = render(Map.of("contact", "sent")); + assertFalse(html.contains("x"), "the configured thank-you is HTML-escaped"); + assertTrue(html.contains("<b>x</b>")); + } + + @Test + void anInvalidOutcomeReRendersTheFormWithAnError() { + String html = render(Map.of("contact", "invalid")); + assertTrue(html.contains("rw-contact-error"), "the validation error is surfaced"); + assertTrue(html.contains("name=\"message\""), "the form re-renders so the visitor can retry"); + } + + @Test + void aCaptchaOutcomeReRendersTheFormWithAnError() { + String html = render(Map.of("contact", "captcha")); + assertTrue(html.contains("Please complete the challenge"), "the challenge error is surfaced"); + assertTrue(html.contains("name=\"message\""), "the form re-renders so the visitor can retry"); + } + + @Test + void aConfiguredChallengeRendersOnTheForm() { + challenge.set(new CaptchaWidget(true, "g-recaptcha-response", "
")); + String html = render(Map.of()); + assertTrue(html.contains("data-sitekey=\"KEY\""), "the site's CAPTCHA renders inline"); + assertTrue(html.indexOf("data-sitekey") < html.indexOf(""), "inside the form, so its token is posted"); + } + + @Test + void aDisabledContactRendersNothing() { + settings.site("acme", Map.of("enabled", false)); + assertTrue(render(Map.of()).isEmpty(), "a disabled contact widget renders an empty fragment"); + } +} diff --git a/plugins/contact/static/contact-help.html b/plugins/contact/static/contact-help.html new file mode 100644 index 0000000..bc6a83a --- /dev/null +++ b/plugins/contact/static/contact-help.html @@ -0,0 +1,62 @@ + + + + + + + Contact plugin — help & reference + + + +

Contact — help & reference

+

The Contact plugin adds a contact form to your site and stores each submission (and can email it), which you + read here in the console. The form is a content widget: it lives on a normal, editable site + page. You can add it to any page yourself, or install a ready-made contact page in one click from the settings.

+ +

Install a ready-made contact page

+

On the Contact settings page, the Contact page card installs a ready-made page carrying the + form (at /contact). It then becomes an ordinary site page — it appears under + Pages, and you can edit its template, restyle it, move it or give it a different URL. Installing is + idempotent: it never overwrites an existing page. It also follows your site's publishing rules: on a site that + requires review it waits in the review queue (unless you may approve pages), and when the site's quality checks + block publishing it is kept as a draft and the answer lists what to fix. The answer always says which happened.

+ +

Or put the form on any page

+
<div id="contact" data-widget="contact/form"></div>
+

The id and data-widget must be on the same element. On submit the form posts to + /contact/submit, which stores (and emails) the message and sends the visitor back to the page the + form lives on, where they see your thank-you message. If the message was stored but your mail server could not + be reached, the thank-you adds a short note that email delivery is delayed.

+ +

Read submissions

+

Every submission is stored inside your site's own folder and listed on the Contact settings page — newest + first, with the name, email, message and time — and, when an SMTP relay is set, also emailed to you. A + full backup of the site keeps the submissions. A transfer copy (the download + meant for someone outside your organisation) leaves them out, because they are your visitors' personal data; + its manifest lists what was left out.

+ +

Settings

+
    +
  • Enable contact form — turn the form (and its submit handler) on or off.
  • +
  • Thank-you message — what the visitor sees after sending.
  • +
  • SMTP relay (host, port, authentication, username, password, STARTTLS, SSL/TLS, from + address, "Send submissions to") — optional: with a blank host or recipient, submissions are only stored. + The password is saved encrypted and never shown again. It belongs to the relay login it was typed for: a + save that changes the host, port, username or a TLS switch without retyping the password clears it, and + the settings page says so — enter it again. Send a test email checks the relay.
  • +
+ +

Anti-spam & privacy notes

+

The form is sent as a POST, so a visitor's name, email and message travel in the request body + and never appear in a web address, their browser history or a proxy log. The platform lets this one form address + accept a post from a visitor without a session (it takes nothing else and acts for nobody), and the form keeps + its guards: a hidden honeypot field (a bot that fills it is silently ignored), your site's CAPTCHA when + you configured one, and the platform's per-address rate limit.

+ + diff --git a/plugins/contact/static/contact.css b/plugins/contact/static/contact.css new file mode 100644 index 0000000..ab68774 --- /dev/null +++ b/plugins/contact/static/contact.css @@ -0,0 +1,80 @@ +/* Runway Contact plugin — form styles. Served at /__plugin/contact/static/contact.css. + Neutral defaults; override any .rw-contact* rule from your own CSS to match your theme. */ + +.rw-contact { + display: flex; + flex-direction: column; + gap: .75rem; + max-width: 32rem; +} + +.rw-contact-label { + display: flex; + flex-direction: column; + gap: .25rem; + font: 500 .95rem/1.3 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; +} + +.rw-contact-input { + padding: .5rem .75rem; + border: 1px solid #ccc; + border-radius: .375rem; + font-size: 1rem; + font-family: inherit; +} + +textarea.rw-contact-input { + resize: vertical; +} + +.rw-contact-submit { + align-self: flex-start; + padding: .5rem 1.25rem; + border: 1px solid transparent; + border-radius: .375rem; + background: #0d6efd; + color: #fff; + font-size: 1rem; + cursor: pointer; +} + +.rw-contact-submit:hover { + filter: brightness(.95); +} + +.rw-contact-error { + color: #b02a37; + background: #f8d7da; + border-radius: .375rem; + padding: .5rem .75rem; + margin: 0; +} + +.rw-contact-success { + color: #0f5132; + background: #d1e7dd; + border-radius: .375rem; + padding: .75rem 1rem; +} + +/* Honeypot: visually and semantically hidden, but present for naive bots to fill. */ +.rw-contact-hp { + position: absolute; + left: -9999px; + width: 1px; + height: 1px; + overflow: hidden; +} + +.rw-contact-main { + max-width: 40rem; + margin: 2rem auto; + padding: 0 1rem; + font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + color: #1a1a1a; +} + +.rw-contact-title { + font-size: 1.5rem; + margin: 0 0 1.25rem; +} diff --git a/plugins/contact/templates/admin.html b/plugins/contact/templates/admin.html new file mode 100644 index 0000000..c6a9664 --- /dev/null +++ b/plugins/contact/templates/admin.html @@ -0,0 +1,75 @@ + +
+

Contact page

+
+ +
+

Install a ready-made contact page carrying the form. It becomes + a normal site page — edit, restyle, move or rename it from Pages.

+
+ + +
+
+ +
+ Installed + Installed at /contact + — edit it under Pages. +
+
+
+ +
+
+

Contact submissions

+ 0 +
+
+ +
+ SMTP relay + Configured + Not configured +
+ + +
+
+

No submissions yet.

+
+ + + + + + + + + + + + + + + + + +
WhenNameEmailMessage
timenameemailexcerpt
+
+
+ +
diff --git a/plugins/contact/templates/admin.th.xml b/plugins/contact/templates/admin.th.xml new file mode 100644 index 0000000..478000e --- /dev/null +++ b/plugins/contact/templates/admin.th.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/contact/templates/dashboard.html b/plugins/contact/templates/dashboard.html new file mode 100644 index 0000000..0fcbc2c --- /dev/null +++ b/plugins/contact/templates/dashboard.html @@ -0,0 +1,15 @@ + +
+
+
+
+ +
+
Contact
+
+ 0 submissions +
+
+
+
+
diff --git a/plugins/contact/templates/dashboard.th.xml b/plugins/contact/templates/dashboard.th.xml new file mode 100644 index 0000000..c3e647e --- /dev/null +++ b/plugins/contact/templates/dashboard.th.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/plugins/demo/scripts/verify-against-host.sh b/plugins/demo/scripts/verify-against-host.sh index 81033d5..6fd234e 100755 --- a/plugins/demo/scripts/verify-against-host.sh +++ b/plugins/demo/scripts/verify-against-host.sh @@ -41,7 +41,7 @@ MVN="${MVN:-mvn}" # Default host: the kernel at the root of the repository this plugin sits in (plugins//), 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" + if [ -f "$HERE/../../runway-app/pom.xml" ]; then HOST_TARGET="$HERE/../../runway-app/target" else HOST_TARGET="$HERE/../../runway/runway-app/target"; fi fi diff --git a/plugins/discoverability/CHANGELOG.md b/plugins/discoverability/CHANGELOG.md new file mode 100644 index 0000000..81a3c6b --- /dev/null +++ b/plugins/discoverability/CHANGELOG.md @@ -0,0 +1,10 @@ +# Changelog + +All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/). + +## [2.3.0] — 2026-10-21 + +First public release of `discoverability`: SEO and GEO for Runway sites — `/sitemap.xml`, `/robots.txt` +(including groups for AI crawlers), `/llms.txt` and schema.org JSON-LD from one shared core, adding only what the +kernel's own SEO leaves out. Requires SPI `1.0.0` (Runway `1.0.0` or later). Licensed under the GNU AGPL v3.0 with an additional permission for +plugins (`LICENSE`, `LICENSE-EXCEPTION`). diff --git a/plugins/discoverability/LICENSE b/plugins/discoverability/LICENSE new file mode 100644 index 0000000..dba13ed --- /dev/null +++ b/plugins/discoverability/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/plugins/discoverability/LICENSE-EXCEPTION b/plugins/discoverability/LICENSE-EXCEPTION new file mode 100644 index 0000000..b634521 --- /dev/null +++ b/plugins/discoverability/LICENSE-EXCEPTION @@ -0,0 +1,44 @@ +Runway — additional permission for plugins +(an additional permission under section 7 of the GNU Affero General Public License, version 3) + +Copyright (C) 2026 Quest ICT SAS de CV + +Runway is free software: you can redistribute it and/or modify it under the terms of the +GNU Affero General Public License as published by the Free Software Foundation, version 3 +(the file LICENSE), with the additional permission below. Runway is distributed in the hope +that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public +License for more details. + +1. Definitions + + "Runway" means the Runway kernel and every Runway plugin whose source carries this file. + + "Published SPI" means the public classes and interfaces of the runway-spi artifact + (the package mx.quest.runway.spi and its subpackages), together with the public classes + and interfaces of any package named "spi" that a part of Runway publishes for other + plugins to use (for example mx.quest.search.spi). + + "Plugin" means an independent module that Runway loads as a plugin, that interacts with + Runway only through the Published SPI, and that is not based on any part of Runway other + than the Published SPI. + +2. Permission + + As an additional permission, the copyright holder gives you permission to combine Runway + with Plugins, and to convey and run the resulting combination, without the terms of the + GNU Affero General Public License applying to those Plugins. You may license, convey and + run your Plugins under terms of your choice, provided that you continue to meet the terms + of the GNU Affero General Public License for Runway itself, including offering the + Corresponding Source of Runway, and of any modification you make to it, as that license + requires. + +3. Testing + + Compiling a Plugin's tests against the runway-spi-testkit artifact, and running them, does + not by itself make the Plugin subject to the GNU Affero General Public License. + +4. Modified versions + + If you modify Runway, you may extend this additional permission to your version, but you + are not obliged to do so. If you do not wish to, delete this file from your version. diff --git a/plugins/discoverability/README.md b/plugins/discoverability/README.md new file mode 100644 index 0000000..03ddc98 --- /dev/null +++ b/plugins/discoverability/README.md @@ -0,0 +1,170 @@ +# discoverability — SEO+ & GEO for Runway + +One Runway plugin that makes a site legible to **search engines** and **AI answer engines**, sharing a single +schema.org **JSON-LD** core. It adds the layer the platform's lean SEO deliberately leaves out — it **never +duplicates** a tag the kernel already emits (canonical, `hreflang`, `robots`, Open Graph, Twitter cards are +free). + +- **SEO+** — JSON-LD structured data (`WebSite` / `WebPage`|`Article` / `Organization` / `BreadcrumbList`) in + every indexable page's ``; a per-site **`/sitemap.xml`** with `hreflang` alternates. + +**Since 1.1.0** the sitemap and `llms.txt` enumerate the host's whole **content catalog** — kernel pages AND +every content source's items (blog entries, any plugin content) — fail-closed re-filtered by the kernel, with the +URLs the kernel computes for the page head too, so head and sitemap provably agree (since 2.0.0 through the +SPI's `ContentCatalogView`). Every item now carries a `` (from its `updatedAt`; pages gain this for the first time). +Content whose URL collides with the reserved surface (e.g. a page at `/login`) is no longer listed. +- **GEO** (opt-in) — **`/llms.txt`** (a compact, machine-friendly page index for LLM/answer engines); a + `SearchAction` + `Speakable` **answer schema** that enriches the SEO JSON-LD by `@id`. + +Everything is per-site: SEO+ on by default, GEO opt-in — no restart to change (per-tenant config applies live). + +- **What it does & how it maps to seams:** [`docs/DISCOVERABILITY-PLUGIN.md`](docs/DISCOVERABILITY-PLUGIN.md) +- **How to build any Runway plugin:** [`../docs/PLUGIN-AUTHORING-GUIDE.md`](../docs/PLUGIN-AUTHORING-GUIDE.md) + +## Links only the Runway SPI (2.0.0+) + +2.0.0 compiles against `runway-spi` alone: settings through `PluginSettings`, the content listing and its URLs +through `ContentCatalogView`, sites through `Sites`, and IndexNow as a `SiteEventListener` that receives each +change with the item's URLs before and after it — so **unpublished, deleted and moved pages are now submitted**, +and only by the node where the change happened. Everything it serves for an unchanged site is byte-for-byte what +1.6.0 served, except three fixes (an item missing from the default locale is linked at its real URL in +`llms.txt`; a root-relative self canonical no longer drops a page from the sitemap; a host-less site's fallback +base is the request's trusted origin). The console bean is now `discoverabilityAdminModel`. + +**Upgrade:** no data or setting changes. Details: [`CHANGELOG.md`](CHANGELOG.md), +[`docs/DISCOVERABILITY-PLUGIN.md`](docs/DISCOVERABILITY-PLUGIN.md) §2. + +## Absolute JSON-LD on a host-less site; llms.txt revalidates honestly (2.1.0, needs SPI 1.0.0) + +A site with neither a base URL nor a host name (the platform's catch-all default) now gets absolute `@id`s and +URLs in its JSON-LD — built on `HeadContext.origin()`, the trusted origin the page is served under — and with them +the GEO `SearchAction` and the breadcrumb trail it never had. `llms.txt`'s `Last-Modified` now advances when only +the site name, `geo.summary` or the base URL changes. **Needs Runway 1.0.0 or later** (SPI `1.0.0`; an older +kernel blocks it with a reason). Details: [`CHANGELOG.md`](CHANGELOG.md). + +## A settings page in sections, every field explained (1.6.0+) + +The per-site settings page is laid out in six sections — structured data, sitemap & robots.txt, AI crawlers, +GEO, product on the homepage, IndexNow — with a help line under every field (English and Spanish), a +**Learn more** link into the matching section of the help page, rarely needed fields under **Advanced**, and +fields hidden while the switch they depend on is off. A site that turns IndexNow on while the platform has it +off is told so on the form, and the operator gets one WARN per site in the log. No setting changed name, type, +default or meaning. Details: +[`docs/DISCOVERABILITY-PLUGIN.md`](docs/DISCOVERABILITY-PLUGIN.md) §4. + +## IndexNow, AI crawlers by class, and a sitemap index (1.5.0+) + +**IndexNow (opt-in twice).** Tells Bing, Yandex, Seznam, Naver and Yep when a site's content changes. +**Google does not participate** — this is a freshness signal for those engines, not a ranking one anywhere. + +It is the only feature here that makes an outbound request, so it takes two switches, both off by default: the +platform operator permits it (`runway.plugin.discoverability.indexnow.enabled`) and the tenant enables it plus +sets a key. The key is served at `/indexnow-key.txt` and named in every submission via the spec's +`keyLocation`. Submissions are batched, capped, and dropped rather than retried on failure. + + +**Decline training while staying citable.** The three AI-agent classes — *training*, *live retrieval*, +*user-triggered fetch* — carry opposite consequences, and each now has its own per-site setting +(`robots.ai-training`, `robots.ai-retrieval`, `robots.ai-user`; `inherit` by default, meaning "whatever +`robots.ai-policy` says"). Declining training costs a site nothing it can see; declining retrieval removes it +from generated answers; declining user-triggered fetch breaks a visit somebody initiated. One switch could not +express that. + +A site that sets none of them gets a **byte-identical** `robots.txt` to before. + +**`/sitemap.xml` becomes an index only when it has to.** Under 10,000 URLs it stays exactly the single +`` it always was. Past that it is a `` over `/sitemap-1.xml` … `/sitemap-N.xml`, up to 20 +shards (200,000 URLs). Shard membership comes from the **sorted** URL list, not source-registration order, so +two nodes behind a load balancer cannot serve different content for the same shard number. + +## Per-site settings reach the page ETag (1.4.2+) + +`StructuredDataHead` declares its per-site settings file (`plugins/discoverability.yml`) through +`HeadContributor#headInputs`, so the kernel folds it into every page's `ETag`. + +Before that, it did not. Head markup is spliced in at the **response edge**, after the page validator has been +computed and possibly answered `304` with no body — so changing the organisation name, the GEO block or the +search URL changed the delivered page and **not** its validator. Every client and CDN holding the old one kept +the previous markup indefinitely, until some unrelated file happened to move; the operator, checking with a +fresh fetch, saw the new value and reasonably concluded it was live. + +**If you add a head contributor that reads a file, declare it.** An undeclared input is invisible to the +validator and fails silently, in the direction that looks correct. + +## Reproducible structured data (1.4.1+) + +The emitted JSON-LD is **byte-reproducible**: the same inputs always render the same bytes, across restarts +and across machines. + +That was not true before 1.4.1. `SearchAction.target` was built with `Map.of(...)`, and `java.util.Map.of` +randomizes iteration order **per JVM instance**, so the key order flipped on roughly every other restart — +stable within one run, different after the next. Semantically harmless (the graphs are equal key-sorted), but +it made rendered pages non-reproducible and quietly broke the promise of a page's strong `ETag`, which folds +metadata and templates rather than the body and therefore did *not* change when the bytes did. + +**If you extend the schema types: never build a serialized node with a multi-entry `Map.of(...)`.** Use +`Ld.node(...)` or a `LinkedHashMap`. A test enforces this at the source level, deliberately — the behavioural +test alone catches a reintroduction only about half the time, because the defect is probabilistic. + +## Build + +```bash +export JAVA_HOME=/path/to/jdk-25 +mvn verify # SPI-only: runway-spi + runway-spi-testkit +mvn -P host-it verify # + the host-integration tests (runway-app, test scope) +``` + +Produces the thin `target/runway-plugin-discoverability.jar` (running the plugin's unit tests — 178; +the `host-it` profile adds 6 that run the plugin against the real kernel classes) and **both** installable forms: +`target/discoverability/` (folder) and `target/runway-plugin-discoverability-.zip` (the UI-upload archive). + +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 `host-it` profile needs +`runway-app` there too). + +## Install (either path, then restart the host) + +> **Upgrading? Do not park the old version inside `external/plugins/`.** The loader scans that directory and +> reads every `plugin.yml`; a parked copy still declares the same `id:`, so the scan sees a duplicate id and +> **fails fast at startup** — the platform refuses to boot because someone kept a rollback copy. Renaming the +> folder does not help; the id inside the descriptor is what collides. Park it outside the tree, or keep the +> release zip. + + +```bash +cp -r target/discoverability /plugins/ # 1. filesystem +# 2. app console → /__app/plugins → install → upload runway-plugin-discoverability-.zip +``` + +Loads only in **ACTIVE** mode (after first-run setup). Configure per site on the plugin's tenant settings page. + +## Verify (one command) + +```bash +scripts/verify-against-host.sh # build → throwaway Runway → boot ACTIVE → prove the live contract +scripts/verify-against-host.sh --keep # ... and leave it running (prints the URL) +HOST_JAR=/path/runway-app--exec.jar VERIFY_TMPDIR=/dir VERIFY_LOG_DIR=/dir scripts/verify-against-host.sh +PREVIOUS_DIR=/path/to//target/discoverability scripts/compare-with-previous.sh # before/after diff +``` + +The verifier checks the load (zero host-linkage and bean-name warnings), JSON-LD on `/`, `/sitemap.xml`, +`/robots.txt`, `/llms.txt`, the settings form, the console card and fragment, and IndexNow both off (inert) and on +(an unpublished page's old URLs reach a local fake endpoint). It never runs `mvn install`. Both scripts need +`JAVA_HOME` set to a JDK 25 and use `mvn` from the `PATH` (or `MVN`). Without `HOST_JAR` they use the host exec +jar under `runway-app/target/` of the kernel at the root of this repository (`HOST_TARGET` names another), +matching the host pom's version. + +## Try it (after installing + enabling GEO on a site) + +- View any public page source → `", h, re.S)))'; } +capture() { # dir + local d="$1"; mkdir -p "$d" + curl -s "$BASE/sitemap.xml" > "$d/sitemap.xml" + curl -s -o /dev/null -w '%{http_code}\n' "$BASE/sitemap-1.xml" > "$d/sitemap-1.status" + curl -s "$BASE/robots.txt" > "$d/robots.txt" + curl -s "$BASE/llms.txt" > "$d/llms.txt" + curl -s -o /dev/null -w '%{http_code}\n' "$BASE/indexnow-key.txt" > "$d/indexnow-key.status" + for p in / /about /es/acerca /selfrel; do curl -s "$BASE$p" | ld > "$d/jsonld$(echo "$p" | tr / _).json"; done +} +capture_console() { # dir + local d="$1" t + rm -f "$JAR_C"; t="$(c "$BASE/login" | token)" + c -o /dev/null -X POST "$BASE/login" --data-urlencode "username=$SITE_USER" --data-urlencode "password=$SITE_PW" --data-urlencode "_csrf=$t" + c "$BASE/__admin/plugins/discoverability/settings" > "$d/settings.page" + python3 -I - "$d/settings.page" > "$d/settings-form.html" <<'PY' +import re, sys +h = open(sys.argv[1], encoding="utf-8").read() +forms = re.findall(r"", h, re.S) +print(re.sub(r'(name="_csrf" value=")[^"]*', r"\1MASKED", max(forms, key=len) if forms else "NO FORM")) +PY + c "$BASE/__admin" > "$d/dashboard.page" + for f in settings dashboard; do grep -oE 'id="d[ac]-[a-z-]+"[^>]*>[^<]*<' "$d/$f.page"; done > "$d/console-values.txt" + rm -f "$d"/*.page +} +cp "$S/site.yml" "$SCRATCH/site.yml.orig" +setup() { # configured | derived | origin + cp "$SCRATCH/site.yml.orig" "$S/site.yml" + case "$1" in + configured) perl -pi -e "s#^baseUrl: .*#baseUrl: \"$CONFIGURED\"#" "$S/site.yml" ;; + origin) perl -0pi -e 's/\nhosts:\n- "localhost"\n/\nhosts: []\n/' "$S/site.yml" ;; + esac +} +round() { # plugin-dir label + rm -rf "$EXT/plugins/discoverability"; cp -r "$1" "$EXT/plugins/discoverability" + for mode in configured derived origin; do + setup "$mode" + boot "$SCRATCH/$2-$mode.log"; capture "$SCRATCH/$2/$mode" + [ "$mode" != configured ] || capture_console "$SCRATCH/$2/$mode" + stop + done +} +round "$PREVIOUS_DIR" before +round "$HERE/target/discoverability" after + +( cd "$SCRATCH" && diff -ru before after ) > "$SCRATCH/before-after.diff" +echo "== differences (before = previous release, after = this build) ==" +cat "$SCRATCH/before-after.diff" + +# The documented fixes, and nothing else: +# - llms.txt links the Spanish-only page at its real address; +# - a root-relative self canonical no longer drops /selfrel from the sitemap; +# - for a site with no base URL and no host name, the trusted origin (http here) instead of the Host header with a +# guessed https. +python3 -I - "$SCRATCH" "$BASE" "$CONFIGURED" <<'PY' +import os, re, sys +root, base, configured = sys.argv[1:] +guessed = base.replace("http://", "https://") +problems = [] +def read(side, mode, name): + with open(os.path.join(root, side, mode, name), encoding="utf-8") as f: + return f.read() +def split(xml): + items = re.findall(r" \n.*? \n", xml, re.S) + head = xml[:xml.index(items[0])] if items else xml + tail = xml[xml.rindex(items[-1]) + len(items[-1]):] if items else "" + return head, items, tail +def loc(item): + return re.search(r"(.*?)", item).group(1) +for mode, origin in (("configured", configured), ("derived", "https://localhost"), ("origin", base)): + for name in sorted(os.listdir(os.path.join(root, "before", mode))): + before, after = read("before", mode, name), read("after", mode, name) + expected = before + if mode == "origin": + expected = expected.replace(guessed, base) # the trusted origin, not a guessed https + if name == "llms.txt": + expected = expected.replace("(" + origin + "/solo)", "(" + origin + "/es/solo-es)") # the Spanish-only page's real address + if name == "sitemap.xml": + # The root-relative self canonical: /selfrel's is listed now, in its sorted place. + head, items, tail = split(expected) + added = [i for i in split(after)[1] if loc(i) == origin + "/selfrel" and i not in items] + expected = head + "".join(sorted(items + added, key=loc)) + tail + if expected != after: + problems.append(mode + "/" + name) +if problems: + print("UNEXPECTED differences in: " + ", ".join(problems)) + sys.exit(1) +print("RESULT: identical except the documented fixes (llms.txt link, root-relative self canonical, trusted origin)") +PY diff --git a/plugins/discoverability/scripts/install-into.sh b/plugins/discoverability/scripts/install-into.sh new file mode 100755 index 0000000..c2d7582 --- /dev/null +++ b/plugins/discoverability/scripts/install-into.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# +# install-into.sh — copy the assembled discoverability 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 +# e.g. scripts/install-into.sh /opt/runway-data/external +set -euo pipefail + +EXTERNAL="${1:?usage: install-into.sh }" +PROJECT_DIR="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)" +STAGE="$PROJECT_DIR/target/discoverability" + +[ -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/discoverability" +cp -a "$STAGE" "$EXTERNAL/plugins/discoverability" +echo "installed discoverability → $EXTERNAL/plugins/discoverability" +echo "RESTART the Runway host for it to load (plugins load only in ACTIVE mode)." diff --git a/plugins/discoverability/scripts/verify-against-host.sh b/plugins/discoverability/scripts/verify-against-host.sh new file mode 100755 index 0000000..0cfe5ff --- /dev/null +++ b/plugins/discoverability/scripts/verify-against-host.sh @@ -0,0 +1,317 @@ +#!/usr/bin/env bash +# Build this plugin, drop it into a throwaway Runway deployment, boot the PACKAGED host in ACTIVE mode, and prove the +# discoverability contract end to end (SPI 1.0.0): +# - it loads with ZERO host-linkage and bean-name/surface findings (a 1.0 kernel blocks on either), and its IndexNow +# submitter is collected as an SPI event listener; +# - the public surfaces: JSON-LD on the home page (valid, one @graph), /sitemap.xml with hreflang alternates for a +# bilingual site, /robots.txt, /llms.txt (GEO on), the help page; for a site with neither a base URL nor a host +# name (the catch-all default site here) the absolute URLs use the request's trusted origin +# (http://localhost: — 1.x read the Host header and guessed https) — since 2.1.0 the page JSON-LD too +# (HeadContext.origin(): absolute @ids, a breadcrumb trail and the GEO SearchAction, none of which 2.0.0 had there); +# - llms.txt's Last-Modified advances when only geo.summary changes (2.0.0 kept it, so a crawler kept the old copy); +# - signed in as the site owner: the settings form keeps the 1.6.0 layout (sections, help lines, Advanced, +# the platform-off notice) and the admin fragment + dashboard card render through the renamed bean +# (`discoverabilityAdminModel`); +# - IndexNow, platform switch at its default (OFF): a tenant's opt-in only logs the inert WARN once, the key file +# is 404 and nothing is sent; +# - IndexNow, platform switch ON (second boot, local fake endpoint): an UNPUBLISHED page's old URLs are submitted +# (1.6.0 submitted nothing), a republish submits them again, with the key and keyLocation. +# The flush is a Spring @Scheduled method run by the HOST's scheduler, which the kernel enables unconditionally; the +# second boot keeps automatic backups OFF, so it also proves that. +# 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--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 fake endpoint's log and the +# fetched documents there (evidence) +# The script never runs `mvn install` (nothing is written to ~/.m2): it packages this plugin offline against +# whatever runway-spi is already in the local repository. +set -uo pipefail + +HERE="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)" +# JAVA_HOME must name a JDK 25. MVN (default: `mvn` on the PATH) and HOST_TARGET (default: see above) can be set in the environment. +if [ -z "${JAVA_HOME:-}" ] || [ ! -x "$JAVA_HOME/bin/java" ]; then echo "set JAVA_HOME to a JDK 25"; exit 2; fi +export JAVA_HOME +JAVA="$JAVA_HOME/bin/java" +MVN="${MVN:-mvn}" +# Default host: the kernel at the root of the repository this plugin sits in (plugins//), 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=Disco-Admin-2026; SITE_USER=owner; SITE_PW=Disco-Site-2026; KEY=disco-verify-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)" +FAKE_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 jar from the build under test. +if [ -n "${HOST_JAR:-}" ]; then + JAR="$HOST_JAR" +else + HOST_VERSION="$(sed -n 's:.*\(.*\).*:\1:p' "$HOST_TARGET/../pom.xml" | head -1)" + JAR="$HOST_TARGET/runway-app-$HOST_VERSION-exec.jar" +fi +[ -f "$JAR" ] || { echo "no host exec jar $JAR — build the host (mvn -pl runway-app package) or set HOST_JAR"; exit 1; } +echo "[verify] host jar: $JAR" + +SCRATCH="$(mktemp -d "${VERIFY_TMPDIR:-${TMPDIR:-/tmp}}/discover-verify.XXXXXX")" +cleanup() { + [ -z "${VERIFY_LOG_DIR:-}" ] || { mkdir -p "$VERIFY_LOG_DIR" \ + && cp "$SCRATCH"/*.log "$SCRATCH"/*.txt "$SCRATCH"/*.xml "$SCRATCH"/*.html "$VERIFY_LOG_DIR"/ 2>/dev/null; } + kill "${FAKE_PID:-0}" 2>/dev/null + # Wait for the host to exit before deleting: a JVM still shutting down rewrites files under external/ and + # makes `rm -rf` leave the scratch folder behind. + [ "$KEEP" = "yes" ] || { kill "${PID:-0}" 2>/dev/null; wait "${PID:-0}" 2>/dev/null; rm -rf "$SCRATCH"; } +} +trap cleanup EXIT +EXT="$SCRATCH/external" +mkdir -p "$EXT/plugins" +cp -r "$HERE/target/discoverability" "$EXT/plugins/discoverability" + +# Accurate JSON-LD check: exactly one breakout would truncate the block or leave a bare '<'/'>'). +cat > "$SCRATCH/ldcheck.py" <<'PY' +import re, json, sys +html = open(sys.argv[1], encoding='utf-8', errors='replace').read() +blocks = re.findall(r'', html, re.S) +if len(blocks) != 1: + sys.exit(1) +for b in blocks: + if '<' in b or '>' in b: + sys.exit(1) + json.loads(b) +sys.exit(0) +PY +# Re-submits the settings form exactly as the browser would (every field with its current value; a checkbox only when +# checked), with KEY=VALUE overrides — prints the urlencoded body. A partial POST would switch unchecked flags off. +cat > "$SCRATCH/resave.py" <<'PY' +import html.parser, sys, urllib.parse +class F(html.parser.HTMLParser): + def __init__(self): + super().__init__(); self.inform = False; self.fields = []; self.select = None; self.area = None + def handle_starttag(self, tag, attrs): + a = dict(attrs) + if tag == 'form' and a.get('id') == 'st-form': self.inform = True + if not self.inform: return + if tag == 'input' and a.get('name'): + t = (a.get('type') or 'text').lower() + if t in ('checkbox', 'radio'): + if 'checked' in a: self.fields.append([a['name'], a.get('value') or 'on']) + elif t not in ('submit', 'button', 'file'): + self.fields.append([a['name'], a.get('value') or '']) + elif tag == 'select' and a.get('name'): self.select = [a['name'], None] + elif tag == 'option' and self.select is not None and ('selected' in a or self.select[1] is None): + if 'selected' in a or self.select[1] is None: self.select[1] = a.get('value', '') + elif tag == 'textarea' and a.get('name'): self.area = [a['name'], ''] + def handle_data(self, d): + if self.area is not None: self.area[1] += d + def handle_endtag(self, tag): + if tag == 'form' and self.inform: self.inform = False + if tag == 'select' and self.select is not None: self.fields.append([self.select[0], self.select[1] or '']); self.select = None + if tag == 'textarea' and self.area is not None: self.fields.append(self.area); self.area = None +f = F(); f.feed(open(sys.argv[1], encoding='utf-8').read()) +over = dict(kv.split('=', 1) for kv in sys.argv[2:]) +print(urllib.parse.urlencode([(k, over.get(k, v)) for k, v in f.fields])) +PY +# A local IndexNow endpoint: records every POST body, answers 200. +cat > "$SCRATCH/fake_indexnow.py" <<'PY' +import http.server, sys +out = sys.argv[2] +class H(http.server.BaseHTTPRequestHandler): + def do_POST(self): + body = self.rfile.read(int(self.headers.get('Content-Length', 0))).decode('utf-8', 'replace') + with open(out, 'a') as f: + f.write(body + '\n') + self.send_response(200); self.end_headers() + def log_message(self, *a): + pass +http.server.HTTPServer(('127.0.0.1', int(sys.argv[1])), H).serve_forever() +PY + +wait_for() { for _ in $(seq 1 "$3"); do grep -q "$2" "$1" 2>/dev/null && return 0; sleep 1; done; return 1; } +PASS=0; FAIL=0 +ck() { if eval "$2" >/dev/null 2>&1; then echo " PASS $1"; PASS=$((PASS+1)); else echo " FAIL $1"; FAIL=$((FAIL+1)); fi; } +# The host reads spring.config.import: optional:file:external/application.yml RELATIVE to cwd, so run with cwd=root. +boot() { local log="$1"; shift; ( cd "$SCRATCH" && exec "$JAVA" -jar "$JAR" --server.port="$PORT" \ + --runway.storage.external="$EXT" "$@" ) >"$log" 2>&1 & PID=$!; } +stop() { kill "$PID" 2>/dev/null; wait "$PID" 2>/dev/null; } +code() { curl -s -o /dev/null -w '%{http_code}' "$@"; } + +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 + +# --- The fixture: the wizard's default site made bilingual (en + es; About also at /es/acerca), GEO on, an +# Organization, and the tenant's IndexNow opt-in with a key. Boot A: NO base URL and NO host name — the site is +# reached as the platform's catch-all default — so the host has no base to offer and the origin fallback runs. +# (A site with a host name gets https:// from the host as its base, exactly as under 1.x.) +S="$EXT/sites/default" +[ -f "$S/site.yml" ] || { echo "the wizard did not seed $S"; exit 1; } +perl -0pi -e 's/\nhosts:\n- "localhost"\n/\nhosts: []\n/' "$S/site.yml" +perl -0pi -e 's/\nlocales:\n- "en"\n/\nlocales:\n- "en"\n- "es"\n/' "$S/site.yml" +perl -0pi -e 's/\n en: About\n/\n en: About\n es: Acerca\n/' "$S/templates/about.meta.yml" +printf 'locales: [en, es]\nlocalizedPaths:\n es: /acerca\n' >> "$S/templates/about.meta.yml" +mkdir -p "$S/plugins" +cat > "$S/plugins/discoverability.yml" <", "uses +# host internals", …): a grep for one wording alone could never fail on a kernel that logs another. +LINKAGE="plugin 'discoverability' (uses host internals|linkage scan)|uses host internals" +SURFACE="plugin 'discoverability'.*(allowed until Runway 1.0|bean name|may not contribute)" +ck "ZERO host-linkage findings" "! grep -qE \"$LINKAGE\" '$LOG'" +ck "ZERO bean-name/surface findings" "! grep -qE \"$SURFACE\" '$LOG'" +ck "IndexNow collected as an SPI listener (1 consumer)" "grep -q 'SPI event listeners: 0 source-phase, 1 consumer-phase' '$LOG'" +ck "no startup WARN/ERROR names the plugin" "! sed -n '1,/Started RunwayApplication/p' '$LOG' | grep -E ' (WARN|ERROR) ' | grep -qi 'discover'" +ck "no key collision / degraded" "! grep -qiE 'collision|duplicate key|degraded' '$LOG'" + +echo "== SEO+ : structured data on the public home page ==" +curl -s "$BASE/" > "$SCRATCH/home.html" +ck "JSON-LD script present" "grep -q 'application/ld+json' '$SCRATCH/home.html'" +ck "WebSite + WebPage emitted" "grep -q '\"@type\":\"WebSite\"' '$SCRATCH/home.html' && grep -q '\"@type\":\"WebPage\"' '$SCRATCH/home.html'" +ck "Organization from config" "grep -q '\"@type\":\"Organization\"' '$SCRATCH/home.html' && grep -q 'Acme Corp' '$SCRATCH/home.html'" +ck "ONE JSON-LD block, valid, no raw <>" "python3 -I '$SCRATCH/ldcheck.py' '$SCRATCH/home.html'" +# No base URL and no host name: the graph is anchored on HeadContext.origin() (2.1.0) — 2.0.0 emitted "/#website". +ck "host-less JSON-LD is absolute at the trusted origin" "grep -q '\"@id\":\"$BASE/#website\"' '$SCRATCH/home.html' && grep -q '\"@id\":\"$BASE/#webpage\"' '$SCRATCH/home.html' && ! grep -q '\"@id\":\"/' '$SCRATCH/home.html'" +ck "…and carries the GEO SearchAction (none in 2.0.0)" "grep -q '\"urlTemplate\":\"$BASE/search?q={search_term_string}\"' '$SCRATCH/home.html'" +curl -s "$BASE/about" > "$SCRATCH/about.html" +ck "…a deep page gains its absolute breadcrumb trail" "grep -q '\"@type\":\"BreadcrumbList\"' '$SCRATCH/about.html' && grep -q '\"item\":\"$BASE/about\"' '$SCRATCH/about.html' && python3 -I '$SCRATCH/ldcheck.py' '$SCRATCH/about.html'" + +echo "== SEO+ : /sitemap.xml over the host's listing (no base URL, no host name: the trusted origin) ==" +ck "sitemap -> 200 application/xml" "curl -s -D - -o '$SCRATCH/sitemap.xml' '$BASE/sitemap.xml' | grep -qi '^content-type: application/xml'" +ck "lists the pages at the request's origin (http, port kept)" "grep -q '$BASE/about' '$SCRATCH/sitemap.xml' && grep -q '$BASE/' '$SCRATCH/sitemap.xml'" +ck "never a guessed https://" "! grep -q 'https://localhost' '$SCRATCH/sitemap.xml'" +ck "the Spanish address and its hreflang alternates" "grep -q '$BASE/es/acerca' '$SCRATCH/sitemap.xml' && grep -q 'hreflang=\"es\" href=\"$BASE/es/acerca\"' '$SCRATCH/sitemap.xml' && grep -q 'hreflang=\"x-default\" href=\"$BASE/about\"' '$SCRATCH/sitemap.xml'" +ck "every item carries a " "[ \"\$(grep -c '' '$SCRATCH/sitemap.xml')\" = \"\$(grep -c '' '$SCRATCH/sitemap.xml')\" ]" +LM="$(curl -s -D - -o /dev/null "$BASE/sitemap.xml" | sed -n 's/^[Ll]ast-[Mm]odified: //p' | tr -d '\r')" +ck "conditional GET: 304 for an unchanged sitemap" "[ -n '$LM' ] && [ \"\$(code -H 'If-Modified-Since: $LM' '$BASE/sitemap.xml')\" = 304 ]" +ck "a small site's shard path is 404" "[ \"\$(code '$BASE/sitemap-1.xml')\" = 404 ]" + +echo "== /robots.txt and GEO /llms.txt ==" +curl -s "$BASE/robots.txt" > "$SCRATCH/robots.txt" +ck "robots.txt: general group + AI group + Sitemap line at the origin" "grep -q '^User-agent: \\*' '$SCRATCH/robots.txt' && grep -q '^User-agent: GPTBot' '$SCRATCH/robots.txt' && grep -qx 'Sitemap: $BASE/sitemap.xml' '$SCRATCH/robots.txt'" +curl -s -o "$SCRATCH/llms.txt" "$BASE/llms.txt" +ck "llms.txt served (H1 + summary)" "head -1 '$SCRATCH/llms.txt' | grep -q '^# ' && grep -q 'We build things' '$SCRATCH/llms.txt'" +ck "llms.txt lists the pages at the origin" "grep -q '## Pages' '$SCRATCH/llms.txt' && grep -q '($BASE/about)' '$SCRATCH/llms.txt'" +LLM_LM="$(curl -s -D - -o /dev/null "$BASE/llms.txt" | sed -n 's/^[Ll]ast-[Mm]odified: //p' | tr -d '\r')" +ck "llms.txt: 304 while nothing changed" "[ -n '$LLM_LM' ] && [ \"\$(code -H 'If-Modified-Since: $LLM_LM' '$BASE/llms.txt')\" = 304 ]" +ck "GEO answer-schema (Speakable)" "grep -q 'SpeakableSpecification' '$SCRATCH/home.html'" +ck "help page served" "[ \"\$(code '$BASE/__plugin/discoverability/static/discoverability-help.html')\" = 200 ]" + +echo "== console: settings form layout (1.6.0), admin fragment and dashboard card (renamed bean) ==" +JAR_C="$SCRATCH/cookies.txt" +c() { curl -s -H 'Accept-Language: en' -c "$JAR_C" -b "$JAR_C" "$@"; } +token() { grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//'; } +login_site() { rm -f "$JAR_C"; local t; t="$(c "$BASE/login" | token)"; c -o /dev/null -X POST "$BASE/login" \ + --data-urlencode "username=$SITE_USER" --data-urlencode "password=$SITE_PW" --data-urlencode "_csrf=$t"; } +page_action() { local t; t="$(c "$BASE/__admin/pages" | token)"; c -o /dev/null -w '%{http_code}' -X POST \ + "$BASE/__admin/pages/$1/$2" --data-urlencode "_csrf=$t"; } +login_site +c "$BASE/__admin/plugins/discoverability/settings" > "$SCRATCH/settings.html" +ck "settings page with the six sections" "grep -q 'Structured data for search engines' '$SCRATCH/settings.html' && grep -q 'Notify search engines of changes (IndexNow)' '$SCRATCH/settings.html'" +ck "…help lines and an Advanced part" "grep -q 'Google does not' '$SCRATCH/settings.html' && grep -qi 'advanced' '$SCRATCH/settings.html'" +ck "admin fragment rendered by discoverabilityAdminModel (GEO on, page count)" "grep -q 'id=\"da-geo\">on<' '$SCRATCH/settings.html' && grep -qE 'id=\"da-pages\">[1-9][0-9]*<' '$SCRATCH/settings.html'" +ck "…and its Per-page types check (2.2.0)" "grep -q 'Per-page types check' '$SCRATCH/settings.html'" +c "$BASE/__admin/pages/about/edit" > "$SCRATCH/editor.html" +ck "the page editor says what the page is described as (2.2.0)" "grep -q 'Structured data: this page is a' '$SCRATCH/editor.html'" +c "$BASE/__admin" > "$SCRATCH/dashboard.html" +ck "dashboard card rendered (page count, GEO on)" "grep -qE 'id=\"dc-pages\">[1-9][0-9]*<' '$SCRATCH/dashboard.html' && grep -q 'id=\"dc-geo\">on<' '$SCRATCH/dashboard.html'" +ck "no template error in the log" "! grep -qiE 'TemplateProcessingException|SpelEvaluationException' '$LOG'" + +echo "== llms.txt's validator folds the summary (2.1.0) ==" +# Save the form unchanged except geo.summary (the console path: the kernel caches per-site settings and evicts on save, +# so a hand edit of the YAML would not be seen). 2.0.0 kept Last-Modified, so a crawler kept the old summary. +sleep 2 # HTTP dates are whole seconds: the advance must land in a later second than the validator it replaces +python3 -I "$SCRATCH/resave.py" "$SCRATCH/settings.html" "geo.summary=We build better things now." > "$SCRATCH/resave.txt" +RS="$(c -o /dev/null -w '%{http_code}' -X POST "$BASE/__admin/plugins/discoverability/settings" \ + -H 'Content-Type: application/x-www-form-urlencoded' --data-binary "@$SCRATCH/resave.txt")" +ck "settings saved through the console (summary only)" "[ '$RS' = 302 ] || [ '$RS' = 303 ]" +ck "…and nothing else changed in the stored file" "grep -q '^geo.enabled: true' '$S/plugins/discoverability.yml' && grep -q 'Acme Corp' '$S/plugins/discoverability.yml' && grep -q 'We build better things now.' '$S/plugins/discoverability.yml'" +ck "llms.txt: the old validator now gets a 200 with the new summary" \ + "[ \"\$(code -H 'If-Modified-Since: $LLM_LM' '$BASE/llms.txt')\" = 200 ] && curl -s '$BASE/llms.txt' | grep -q '^> We build better things now.'" +LLM_LM2="$(curl -s -D - -o /dev/null "$BASE/llms.txt" | sed -n 's/^[Ll]ast-[Mm]odified: //p' | tr -d '\r')" +ck "…and its new validator revalidates to 304" "[ -n '$LLM_LM2' ] && [ '$LLM_LM2' != '$LLM_LM' ] && [ \"\$(code -H 'If-Modified-Since: $LLM_LM2' '$BASE/llms.txt')\" = 304 ]" + +echo "== IndexNow, platform switch OFF (the default): inert ==" +ck "key file is 404" "[ \"\$(code '$BASE/indexnow-key.txt')\" = 404 ]" +CODE="$(page_action about disable)" +ck "unpublish via the console (redirect)" "[ '$CODE' = 302 ] || [ '$CODE' = 303 ]" +ck "the inert WARN, once, naming the site" "[ \"\$(grep -c \"site 'default' has IndexNow enabled, but the platform has not permitted it\" '$LOG')\" = 1 ]" +ck "nothing attempted" "! grep -q 'IndexNow submission' '$LOG'" +page_action about enable >/dev/null +stop + +echo "[verify] booting host (ACTIVE, IndexNow ON, fake endpoint :$FAKE_PORT, 2 s batches, base URL configured) ..." +perl -pi -e "s#^baseUrl: .*#baseUrl: \"$BASE\"#" "$S/site.yml" +python3 -I "$SCRATCH/fake_indexnow.py" "$FAKE_PORT" "$SCRATCH/indexnow-posts.txt" & FAKE_PID=$! +boot "$SCRATCH/active2.log" --runway.plugin.discoverability.indexnow.enabled=true \ + --runway.plugin.discoverability.indexnow.endpoint="http://127.0.0.1:$FAKE_PORT/indexnow" \ + --runway.plugin.discoverability.indexnow.batch-seconds=2 +wait_for "$SCRATCH/active2.log" "Started RunwayApplication" 90 || { echo "second ACTIVE boot failed"; tail -20 "$SCRATCH/active2.log"; exit 1; } +LOG2="$SCRATCH/active2.log" +echo "== IndexNow, platform switch ON ==" +ck "still 1 registered, 0 blocked, zero findings" "grep -q 'plugins: 1 registered, 0 blocked' '$LOG2' && ! grep -qE \"$LINKAGE\" '$LOG2' && ! grep -qE \"$SURFACE\" '$LOG2'" +ck "app-level settings bound: key file served" "curl -s '$BASE/indexnow-key.txt' | grep -qx '$KEY'" +# With a base URL the graph is anchored on that base (never the request origin), with the GEO SearchAction. +curl -s "$BASE/" > "$SCRATCH/home-based.html" +ck "GEO SearchAction on the anchored graph" "grep -q '\"potentialAction\":{\"@type\":\"SearchAction\"' '$SCRATCH/home-based.html' && grep -q '\"@id\":\"$BASE/#website\"' '$SCRATCH/home-based.html' && python3 -I '$SCRATCH/ldcheck.py' '$SCRATCH/home-based.html'" +curl -s -o /dev/null "$BASE/sitemap.xml" # the host lists the site once, so a change can report previous URLs +login_site +page_action about disable >/dev/null +for _ in $(seq 1 15); do [ -s "$SCRATCH/indexnow-posts.txt" ] && break; sleep 1; done +echo " fake endpoint received after the unpublish:"; sed 's/^/ /' "$SCRATCH/indexnow-posts.txt" 2>/dev/null +ck "an UNPUBLISHED page's old URLs are submitted (1.6.0 sent nothing)" \ + "grep -qF '\"urlList\":[\"$BASE/about\",\"$BASE/es/acerca\"]' '$SCRATCH/indexnow-posts.txt'" +ck "…with the key and the fixed keyLocation" "grep -qF '\"key\":\"$KEY\",\"keyLocation\":\"$BASE/indexnow-key.txt\"' '$SCRATCH/indexnow-posts.txt'" +cp "$SCRATCH/indexnow-posts.txt" "$SCRATCH/indexnow-posts-unpublish.txt" +: > "$SCRATCH/indexnow-posts.txt" +page_action about enable >/dev/null +for _ in $(seq 1 15); do [ -s "$SCRATCH/indexnow-posts.txt" ] && break; sleep 1; done +sleep 3 # one more batch period: a second submission for the same change would land now +echo " fake endpoint received after the republish:"; sed 's/^/ /' "$SCRATCH/indexnow-posts.txt" 2>/dev/null +ck "a republish submits the page's URLs again" "grep -qF '\"urlList\":[\"$BASE/about\",\"$BASE/es/acerca\"]' '$SCRATCH/indexnow-posts.txt'" +ck "one submission per batch (not one per URL)" "[ \"\$(grep -c urlList '$SCRATCH/indexnow-posts.txt')\" = 1 ]" +ck "no inert WARN while permitted" "! grep -q 'has not permitted it' '$LOG2'" +ck "no WARN/ERROR names the plugin" "! grep -E ' (WARN|ERROR) ' '$LOG2' | grep -qi 'discover'" + +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" diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/ArticleSchema.java b/plugins/discoverability/src/main/java/mx/quest/discover/ArticleSchema.java new file mode 100644 index 0000000..e98b08d --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/ArticleSchema.java @@ -0,0 +1,110 @@ +package mx.quest.discover; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import mx.quest.runway.spi.model.HeadContext; + +/** + * Emits a schema.org {@code Article} (or {@code BlogPosting} — the subtype the entry declares as its + * {@code type}) from a post's {@code content.schema} entry: {@code headline} (falls back to the page title), + * description, image, {@code author} (a {@code Person}), {@code datePublished}/{@code dateModified}, + * {@code publisher}→Organization. The declared type is the page's own type (since 2.2.0): the properties go on + * the page's {@code #webpage} node, which takes the declared {@code @type}, instead of a second node beside it. + * + *

Where author and dates come from, and why the order matters

+ * Each of {@code author}, {@code datePublished} and {@code dateModified} is taken from the page's own + * provenance first ({@link mx.quest.runway.spi.model.PageMeta#provenance()}), and only then from the + * hand-written {@code content.schema} block. + * + *

That order is the whole point of the change. {@code content.schema} matches by exact path or {@code *} + * prefix, so a blog is typed by a single {@code /blog/*} block shared by every entry. When these fields + * could only come from there, a site had exactly two honest options: omit dates and authorship entirely, or + * assert one date and one author identically on every post — a statement that is false of nearly + * every page it appears on. Asserting content that is not true of the page is precisely what structured-data + * policy prohibits, so the configuration-only design pushed a conscientious operator toward a violation. + * + *

Per-item provenance removes the dilemma: a source that knows its own publication date (a blog entry does) + * now supplies it, and the shared block is left to cover only what is genuinely shared. The config path is kept + * as a fallback so existing sites keep working unchanged, and so a source that has no provenance can still be + * annotated by hand. + */ +final class ArticleSchema implements SchemaType { + + @Override + public String key() { + return "Article"; + } + + /** Every token is a page type: an article (or blog post, or news article) is what the page is. */ + @Override + public boolean describesPage(String token) { + return true; + } + + /** Nothing as a separate node: the article is the page itself ({@link #describePage}). */ + @Override + public List> nodes(HeadContext ctx, SchemaContext sc) { + return List.of(); + } + + /** + * Adds the article's properties to the page's own node: {@code headline} in place of {@code name}, and + * author, dates and image. Without a headline (no page title and none configured) the page keeps its name. + */ + @Override + public void describePage(Map page, HeadContext ctx, SchemaContext sc, + List> graph) { + Map fields = fields(ctx, sc); + if (fields.isEmpty()) { + return; + } + page.remove("name"); + page.putAll(fields); + } + + /** The article's own properties, or an empty map when it has no headline. */ + private static Map fields(HeadContext ctx, SchemaContext sc) { + Map cfg = sc.pageConfig(); + String headline = Schemas.str(cfg, "headline", ctx.page().title()); + if (headline == null || headline.isBlank()) { + return Map.of(); // no headline — leave the page node as it is + } + Map article = new LinkedHashMap<>(); + Ld.put(article, "headline", headline); + Ld.put(article, "description", Schemas.str(cfg, "description", ctx.page().description())); + Ld.putList(article, "image", Schemas.absolute(Schemas.strings(cfg, "image"), sc.base())); + // Per-item provenance WINS over the shared content.schema block — see the class contract. + mx.quest.runway.spi.model.Provenance prov = ctx.page().provenance(); + Ld.put(article, "datePublished", isoDate(prov.publishedAt(), Schemas.str(cfg, "datePublished"))); + Ld.put(article, "dateModified", isoDate(prov.updatedAt(), Schemas.str(cfg, "dateModified"))); + Ld.put(article, "inLanguage", ctx.locale().toLanguageTag()); + String author = prov.author() != null ? prov.author() : Schemas.str(cfg, "author"); + if (author != null) { + Map person = new LinkedHashMap<>(); + person.put("@type", "Person"); + person.put("name", author); + article.put("author", person); + } + if (sc.hasOrg()) { + Ld.ref(article, "publisher", sc.organizationId()); + } + return article; + } + + /** + * The item's own instant as a schema.org date, else the configured fallback. + * + *

Rendered as {@code yyyy-MM-dd} (UTC) rather than a full timestamp: schema.org accepts either, and a + * publication date is an editorial fact at day granularity. Emitting a second-precision instant would imply + * a precision the platform does not actually have — {@code dateModified} in particular is derived from a + * file mtime, which moves for reasons that are not editorial. + */ + private static String isoDate(java.time.Instant instant, String fallback) { + if (instant == null) { + return fallback; + } + return java.time.format.DateTimeFormatter.ISO_LOCAL_DATE + .format(instant.atZone(java.time.ZoneOffset.UTC)); + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/CollectionSchema.java b/plugins/discoverability/src/main/java/mx/quest/discover/CollectionSchema.java new file mode 100644 index 0000000..fbb46ff --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/CollectionSchema.java @@ -0,0 +1,75 @@ +package mx.quest.discover; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import mx.quest.runway.spi.model.HeadContext; + +/** + * Emits a schema.org {@code ItemList} for a collection / index page (a coffee listing, a services or blog index) + * from an {@code items:} list of {@code {name, url}}. Without it a listing page is invisible as a list to + * crawlers (no carousel eligibility) and answer engines. Registered under both {@code ItemList} and + * {@code CollectionPage}; the node is {@code @id}'d and {@code mainEntityOfPage}-linked to the page. Declared as + * {@code CollectionPage} it also makes the page itself a {@code CollectionPage} whose {@code mainEntity} is the list + * (since 2.2.0; until then the page stayed the site default and only the list was emitted). + */ +final class CollectionSchema implements SchemaType { + + @Override + public String key() { + return "ItemList"; + } + + /** {@code CollectionPage} names what the page is; {@code ItemList} only adds the list. */ + @Override + public boolean describesPage(String token) { + return "CollectionPage".equals(token); + } + + @Override + public void describePage(Map page, HeadContext ctx, SchemaContext sc, + List> graph) { + for (Map list : nodes(ctx, sc)) { + graph.add(list); + Ld.ref(page, "mainEntity", (String) list.get("@id")); + } + } + + /** No item with a {@code url}: no list is published (a CollectionPage is still a CollectionPage). */ + @Override + public Gap gap(String token, Map block) { + for (Map member : Schemas.maps(block, "items")) { + if (Schemas.str(member, "url") != null) { + return null; + } + } + return new Gap("discover.gap.items", "{0} has no item with a url:, so no list is published."); + } + + @Override + public List> nodes(HeadContext ctx, SchemaContext sc) { + List> members = Schemas.maps(sc.pageConfig(), "items"); + List> elements = new ArrayList<>(); + int position = 1; + for (Map member : members) { + String url = Schemas.str(member, "url"); + if (url == null) { + continue; // a list item without a target URL is not useful + } + Map item = new LinkedHashMap<>(); + item.put("@type", "ListItem"); + item.put("position", position++); + Ld.put(item, "name", Schemas.str(member, "name")); + item.put("url", url.startsWith("/") ? sc.base() + url : url); + elements.add(item); + } + if (elements.isEmpty()) { + return List.of(); + } + Map list = Ld.node("ItemList", sc.canonical() + "#itemlist"); + Ld.ref(list, "mainEntityOfPage", sc.webpageId()); + list.put("itemListElement", elements); + return List.of(list); + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/CrawlConditional.java b/plugins/discoverability/src/main/java/mx/quest/discover/CrawlConditional.java new file mode 100644 index 0000000..23c7e75 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/CrawlConditional.java @@ -0,0 +1,210 @@ +package mx.quest.discover; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import mx.quest.runway.spi.model.CatalogEntry; +import mx.quest.runway.spi.model.LocalizedUrl; +import mx.quest.runway.spi.model.RouteRequest; +import mx.quest.runway.spi.model.RouteResponse; + +/** + * Conditional-GET support for the crawl surfaces (sitemap.xml, llms.txt): crawlers hit these often, and the + * content only changes when the site's content does — so both endpoints emit {@code Last-Modified} with + * {@code Cache-Control: no-cache} (cache it, but REVALIDATE every time), and answer {@code If-Modified-Since} + * with an empty {@code 304} instead of re-serializing the whole document. + * + *

The validator must reflect MEMBERSHIP, not just member mtimes. These documents are lists: deleting + * or unpublishing an item only removes an {@code updatedAt} from the pool, so a naive + * {@code max(updatedAt)} stays the same (or moves backward) and a revalidating crawler would keep its cached + * copy — still advertising the removed URL — indefinitely. The validator therefore combines a per-site + * fingerprint of the document-shaping facts (item identity, paths, {@code updatedAt}, {@code noindex}, + * and the host-computed URLs: every locale's address and canonical, and the {@code x-default}) — plus, per + * document, the document-level facts it prints that no item carries (llms.txt's site name and + * {@code geo.summary}) — with a monotonic emitted instant: while the fingerprint is unchanged the emitted value is stable; any + * change advances it to {@code max(newest updatedAt, previous)} — or to now when the change carries no + * newer mtime (a removal, an addition with a null {@code updatedAt}). A future-dated {@code updatedAt} (clock + * skew, a touched file) is clamped to now so it cannot pin the validator and mask later real changes. + * + *

State is in-memory only. On restart the first request per site seeds the emitted instant with now + * — deliberately: seeding with the content mtime would resurrect the removal blind spot for any membership + * change that happened around the restart. The cost is one full {@code 200} per crawler after a restart; the + * value then stabilizes until content actually changes. HTTP dates are second-granular, so instants are + * truncated before comparing. + */ +final class CrawlConditional { + + private static final DateTimeFormatter HTTP_DATE = + DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneOffset.UTC); + + /** What the site's crawl documents last looked like (fingerprint) and the validator emitted for it. */ + private record Validator(String fingerprint, Instant emitted) { + } + + /** + * Validator state per site and document. Until 2.1.0 the sitemap and llms.txt shared one record per site + * (both derive from the same catalog list); llms.txt now also folds facts the sitemap does not print, and two + * documents with different fingerprints sharing one record would advance each other's validator on every + * alternate request. + */ + private static final ConcurrentMap STATE = new ConcurrentHashMap<>(); + + /** The sitemap's document name — its validator folds the catalog only. */ + static final String SITEMAP = "sitemap.xml"; + /** The llms.txt document name — its validator also folds the site name and summary it prints. */ + static final String LLMS = "llms.txt"; + + /** The time source — a test hook ({@link #reset} restores it); production always uses the system clock. */ + static java.util.function.Supplier clock = Instant::now; + + private CrawlConditional() { + } + + /** Test hook: forget all per-site validator state (simulates a restart) and restore the system clock. */ + static void reset() { + STATE.clear(); + clock = Instant::now; + } + + /** The sitemap's validator: {@link #lastModified(String, String, List, List)} with no document-level facts. */ + static Instant lastModified(String siteId, List items) { + return lastModified(siteId, SITEMAP, items, List.of()); + } + + /** + * The {@code Last-Modified} validator for {@code siteId}'s crawl document {@code document} built from + * {@code items} and the document-level {@code facts} it prints besides them (in a fixed order; a {@code null} + * fact folds as empty) — membership-aware and monotonic per the class contract (never in the future, never moves + * backward). A change to a fact advances the validator to now: it carries no mtime of its own. + */ + static Instant lastModified(String siteId, String document, List items, List facts) { + Instant now = clock.get().truncatedTo(ChronoUnit.SECONDS); + Instant newest = newestUpdatedAt(items, now); + String fingerprint = fingerprint(items, facts); + // A printable separator ('|' is never part of a site id), never a control character. + Validator computed = STATE.compute(siteId + '|' + document, (id, prev) -> { + if (prev == null) { + return new Validator(fingerprint, now); // restart seed: now, per the class contract + } + if (prev.fingerprint().equals(fingerprint)) { + return prev; // unchanged document keeps its validator — this is what makes 304s possible + } + Instant advanced = (newest != null && newest.isAfter(prev.emitted())) ? newest : now; + if (!advanced.isAfter(prev.emitted())) { + // Cannot advance within HTTP-date granularity (a change in the same second as the previous + // advance, or a backward clock). Keep the OLD state — fingerprint included — so a later + // request re-detects the change and advances once the clock has moved; committing the new + // fingerprint now would absorb the change at the old validator forever. + return prev; + } + return new Validator(fingerprint, advanced); + }); + return computed.emitted(); + } + + /** The newest {@code updatedAt} across {@code items} clamped to {@code now}, or null when none carries one. */ + private static Instant newestUpdatedAt(List items, Instant now) { + Instant newest = null; + for (CatalogEntry item : items) { + Instant updated = item.ref().updatedAt(); + if (updated != null && (newest == null || updated.isAfter(newest))) { + newest = updated; + } + } + if (newest == null) { + return null; + } + newest = newest.truncatedTo(ChronoUnit.SECONDS); + return newest.isAfter(now) ? now : newest; // a future mtime must not pin the validator + } + + /** + * A digest of the document-shaping facts: identity, paths, mtime, indexability, and the URLs the host computed — + * order-sensitive. The URLs are folded in because they change without any item changing: a site that starts + * serving another locale gains alternates, and a canonical override moves an item in or out of the sitemap. + * (Until 2.0.0 they were not, so a crawler revalidating after such a change kept its old copy.) The document-level + * facts come first, each length-prefixed so no fact can shift characters into the next (until 2.1.0 there were + * none, so editing the site name or {@code geo.summary} changed llms.txt without advancing its validator). + */ + private static String fingerprint(List items, List facts) { + MessageDigest digest; + try { + digest = MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + StringBuilder sb = new StringBuilder(128); + sb.append("facts#").append(facts.size()).append(';'); + for (String fact : facts) { + String value = fact == null ? "" : fact; + sb.append(value.length()).append(':').append(value); + } + sb.append('\n'); + digest.update(sb.toString().getBytes(StandardCharsets.UTF_8)); + for (CatalogEntry item : items) { + sb.setLength(0); + sb.append(item.compositeId()).append('|').append(item.ref().path()).append('|') + .append(item.ref().localizedPaths()).append('|').append(item.ref().updatedAt()).append('|') + .append(item.ref().noindex()).append('|').append(item.xDefaultPath()); + for (LocalizedUrl url : item.urls()) { + sb.append('|').append(url.locale().toLanguageTag()).append('=').append(url.path()) + .append('>').append(url.canonical()); + } + sb.append('\n'); + digest.update(sb.toString().getBytes(StandardCharsets.UTF_8)); + } + return java.util.HexFormat.of().formatHex(digest.digest()); + } + + /** Whether the request's {@code If-Modified-Since} already covers {@code lastModified} (null ⇒ no). */ + static boolean notModified(RouteRequest req, Instant lastModified) { + if (lastModified == null) { + return false; + } + String header = header(req, "If-Modified-Since"); + if (header == null || header.isBlank()) { + return false; + } + try { + Instant since = Instant.from(HTTP_DATE.parse(header.trim())); + return !lastModified.truncatedTo(ChronoUnit.SECONDS).isAfter(since); + } catch (RuntimeException unparseable) { + return false; // an invalid date = an unconditional request + } + } + + /** The empty {@code 304} carrying the same validator/caching headers as the {@code 200} would. */ + static RouteResponse notModifiedResponse(Instant lastModified) { + return new RouteResponse(304, cacheHeaders(lastModified, null), new byte[0]); + } + + /** The response headers for a fresh {@code 200}: content type + validator + revalidate-always caching. */ + static Map cacheHeaders(Instant lastModified, String contentType) { + Map headers = new java.util.LinkedHashMap<>(); + if (contentType != null) { + headers.put("Content-Type", contentType); + } + if (lastModified != null) { + headers.put("Last-Modified", HTTP_DATE.format(lastModified.truncatedTo(ChronoUnit.SECONDS))); + } + headers.put("Cache-Control", "no-cache"); + return headers; + } + + private static String header(RouteRequest req, String name) { + for (var entry : req.headers().entrySet()) { + if (entry.getKey().equalsIgnoreCase(name)) { + return entry.getValue(); + } + } + return null; + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/DiscoverAdminModel.java b/plugins/discoverability/src/main/java/mx/quest/discover/DiscoverAdminModel.java new file mode 100644 index 0000000..7ef02e7 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/DiscoverAdminModel.java @@ -0,0 +1,151 @@ +package mx.quest.discover; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import mx.quest.runway.spi.service.ContentCatalogView; +import mx.quest.runway.spi.service.Messages; +import mx.quest.runway.spi.service.PluginSettings; + +/** + * Backs the tenant dashboard card and the admin fragment rendered below the plugin's per-tenant + * settings form. The templates call it as {@code ${@discoverabilityAdminModel.(tenantSiteId)}} (the bean + * name carries the plugin id, as every plugin bean must) to show the plugin's live state for the current site + * (which surfaces are on, how many items the sitemap draws from). + * + *

Read-only. A missing or malformed site id (the fragments are only rendered for a tenant, so neither happens in + * practice) answers the defaults and a count of {@code 0} rather than failing the console page. + */ +public class DiscoverAdminModel { + + private final PluginSettings settings; + private final ContentCatalogView catalog; + private final Map types; + private final Messages messages; + + public DiscoverAdminModel(PluginSettings settings, ContentCatalogView catalog) { + this(settings, catalog, DiscoverabilityConfig.schemaTypes(), null); + } + + DiscoverAdminModel(PluginSettings settings, ContentCatalogView catalog, Map types, + Messages messages) { + this.settings = settings; + this.catalog = catalog; + this.types = types; + this.messages = messages; + } + + /** + * What is wrong with the site's Per-page types ({@code content.schema}), one line each, in the operator's UI + * language; empty when nothing is. Shown below the settings form after every save. + * + *

Why

+ * A mistake there never breaks a page: unreadable YAML turns typing off, and an unknown type or a misplaced + * {@code *} is skipped. That is the right behaviour for visitors and the wrong one for the person who typed it, + * who until 2.2.0 had no way to see it. A block that applies but publishes nothing of its own (an + * {@code FAQPage} with no complete question: {@link SchemaType#gap}) is listed too; an ignored second page type + * is reported once, not also for its gaps. + */ + public List schemaProblems(String siteId) { + String text = SiteConfig.str(cfg(siteId), "content.schema", ""); + List out = new ArrayList<>(); + String syntax = PageSchemaConfig.syntaxProblem(text); + if (syntax != null) { + out.add(text("discover.schema.syntax", + "Per-page types cannot be read, so no page gets a per-page type: {0}", syntax)); + return out; + } + for (String pattern : PageSchemaConfig.ignoredPatterns(text)) { + out.add(text("discover.schema.notBlock", + "{0}: the value must be a type block (type: ...) or a list of them; ignored.", pattern)); + } + Map patterns = PageSchemaConfig.parse(text); + for (Map.Entry entry : patterns.entrySet()) { + String pattern = entry.getKey(); + if (!pattern.startsWith("/")) { + out.add(text("discover.schema.slash", "{0}: a pattern starts with / and matches page paths.", + pattern)); + } + int star = pattern.indexOf('*'); + if (star >= 0 && star < pattern.length() - 1) { + out.add(text("discover.schema.star", + "{0}: * works only at the end of a pattern; here it is matched as a character.", pattern)); + } + int pageTypes = 0; + for (Map block : PageSchemaConfig.blocks(entry.getValue())) { + String token = Schemas.str(block, "type", ""); + if (token.isBlank()) { + continue; + } + SchemaType handler = types.get(token); + if (handler == null) { + out.add(text("discover.schema.unknown", + "{0}: {1} is not a type this plugin knows; ignored.", pattern, token)); + } else if (handler.describesPage(token) && ++pageTypes > 1) { + if (pageTypes == 2) { + out.add(text("discover.schema.twoPageTypes", + "{0}: more than one page type; only the first applies.", pattern)); + } + } else { + SchemaType.Gap gap = handler.gap(token, block); + if (gap != null) { + out.add(pattern + ": " + text(gap.code(), gap.fallback(), token)); + } + } + } + } + return out; + } + + private String text(String code, String fallback, Object... args) { + return messages == null ? java.text.MessageFormat.format(fallback, args) + : messages.console(code, fallback, args); + } + + public boolean jsonldEnabled(String siteId) { + return SiteConfig.bool(cfg(siteId), "jsonld.enabled", true); + } + + public String jsonldType(String siteId) { + return PageTypes.defaultType(cfg(siteId)); + } + + public boolean sitemapEnabled(String siteId) { + return SiteConfig.bool(cfg(siteId), "sitemap.enabled", true); + } + + public boolean geoEnabled(String siteId) { + return SiteConfig.bool(cfg(siteId), "geo.enabled", false); + } + + public boolean orgConfigured(String siteId) { + return !SiteConfig.str(cfg(siteId), "org.name", "").isBlank(); + } + + /** + * The number of published content items the sitemap draws from — kernel pages AND plugin content alike, through + * the same host listing the sitemap itself serves from (so this count is always truthful). Items marked + * {@code noindex} are included, as before: the count is of the published surface. + */ + public long pageCount(String siteId) { + if (siteId == null) { + return 0L; + } + try { + return catalog.entries(siteId).size(); + } catch (IllegalArgumentException malformedId) { + return 0L; + } + } + + private Map cfg(String siteId) { + if (siteId == null) { + return Map.of(); + } + try { + return settings.site(siteId).values(); + } catch (IllegalArgumentException malformedId) { + return Map.of(); + } + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/DiscoverabilityConfig.java b/plugins/discoverability/src/main/java/mx/quest/discover/DiscoverabilityConfig.java new file mode 100644 index 0000000..3d43f98 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/DiscoverabilityConfig.java @@ -0,0 +1,145 @@ +package mx.quest.discover; + +import java.util.LinkedHashMap; +import java.util.Map; +import mx.quest.runway.spi.EndpointContributor; +import mx.quest.runway.spi.HeadContributor; +import mx.quest.runway.spi.PageQualityCheck; +import mx.quest.runway.spi.service.ContentCatalogView; +import mx.quest.runway.spi.service.Messages; +import mx.quest.runway.spi.service.PluginSettings; +import mx.quest.runway.spi.service.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. It wires every bean EXPLICITLY (no {@code @ComponentScan}: scanning a plugin's own package across the + * shared child classloader is fragile). The plugin package ({@code mx.quest.discover}) is deliberately OUTSIDE + * {@code mx.quest.runway} so the host never double-scans it. + * + *

The {@link HeadContributor} and {@link EndpointContributor}s are list-collected SPIs — plain + * {@code @Bean}s, NEVER {@code @Primary}. The head contributor is ordered AFTER the kernel's own SEO + * ({@code @Order 100}) and icon ({@code @Order 90}) head contributors, so the plugin's structured data is + * spliced last. + * + *

Links only the Runway SPI (since 2.0.0). Every host service arrives by ordinary injection of an SPI + * type: {@link PluginSettings} (this plugin's per-site settings, bound to this plugin by the jar its code was + * loaded from), {@link ContentCatalogView} (the site's published content surface with host-computed URLs) and + * {@link Sites}. Every bean name starts with the plugin id ({@code discoverability…}): plugins share the host's + * bean namespace. + */ +@Configuration(proxyBeanMethods = false) +public class DiscoverabilityConfig { + + // --- app-level (platform) settings ---------------------------------------------------------------- + + /** + * The app-level settings, bound from {@code runway.plugin.discoverability.*}. Declared as a named {@code @Bean} + * rather than through {@code @EnableConfigurationProperties}, which would register it under the generated name + * {@code runway.plugin.discoverability-mx.quest.discover.DiscoverabilityProperties} — outside the plugin's bean + * prefix. + */ + @Bean + @ConfigurationProperties("runway.plugin.discoverability") + public DiscoverabilityProperties discoverabilityProperties() { + return new DiscoverabilityProperties(); + } + + // --- head contributor (SEO+ and GEO in one @graph) ------------------------------------------------ + + @Bean + @Order(150) + public HeadContributor discoverabilityStructuredData(PluginSettings settings) { + return new StructuredDataHead(settings, schemaTypes()); + } + + /** + * The content-type registry (item 5), indexed by the type token a tenant declares in {@code content.schema}. + * Subtypes are registered under aliases that share one implementation (e.g. {@code BlogPosting}→Article). + * Fails fast on a duplicate key so a wiring mistake never silently shadows a type. + */ + static Map schemaTypes() { + Map types = new LinkedHashMap<>(); + register(types, new FaqPageSchema()); + register(types, new ProductSchema()); + register(types, new ArticleSchema(), "BlogPosting", "NewsArticle"); + register(types, new LocalBusinessSchema(), "CafeOrCoffeeShop"); + register(types, new ServiceSchema(), "ProfessionalService"); + register(types, new PersonSchema()); + register(types, new CollectionSchema(), "CollectionPage"); + for (String key : SimplePageType.KEYS) { + register(types, new SimplePageType(key)); + } + return types; + } + + private static void register(Map types, SchemaType type, String... aliases) { + put(types, type.key(), type); + for (String alias : aliases) { + put(types, alias, type); + } + } + + private static void put(Map types, String key, SchemaType type) { + if (types.putIfAbsent(key, type) != null) { + throw new IllegalStateException("duplicate schema type key: " + key); + } + } + + // --- crawl-surface endpoints ---------------------------------------------------------------------- + + @Bean + public EndpointContributor discoverabilitySitemap(ContentCatalogView catalog, PluginSettings settings) { + return new SitemapEndpoint(catalog, settings); + } + + @Bean + public EndpointContributor discoverabilityLlms(ContentCatalogView catalog, PluginSettings settings) { + return new LlmsTxtEndpoint(catalog, settings); + } + + @Bean + public EndpointContributor discoverabilityRobots(PluginSettings settings, DiscoverabilityProperties properties) { + return new RobotsTxtEndpoint(settings, properties); + } + + @Bean + public EndpointContributor discoverabilityIndexNowKey(PluginSettings settings, + DiscoverabilityProperties properties) { + return new IndexNowKeyEndpoint(settings, properties); + } + + // --- IndexNow (outbound: OFF unless the platform operator AND the tenant both enable it) ----------- + + /** A {@code SiteEventListener} (collected by type by the host) that queues changed URLs, plus the flush. */ + @Bean + public IndexNowSubmitter discoverabilityIndexNow(Sites sites, PluginSettings settings, + DiscoverabilityProperties properties) { + return new IndexNowSubmitter(sites, settings, properties); + } + + // --- advisory quality check (edit-time detect-and-lift for on-page FAQs) -------------------------- + + @Bean + public PageQualityCheck discoverabilityFaqAdvisory(PluginSettings settings) { + return new FaqAdvisoryCheck(settings, schemaTypes()); + } + + /** The page editor's line saying what each page is described as, and where that comes from. */ + @Bean + public PageQualityCheck discoverabilityPageType(PluginSettings settings, Messages messages) { + return new PageTypeCheck(settings, schemaTypes(), messages); + } + + // --- console surface (dashboard card + admin fragment) -------------------------------------------- + + /** Read by the templates as {@code ${@discoverabilityAdminModel…}} (renamed from {@code discoverAdminModel}). */ + @Bean + public DiscoverAdminModel discoverabilityAdminModel(PluginSettings settings, ContentCatalogView catalog, + Messages messages) { + return new DiscoverAdminModel(settings, catalog, schemaTypes(), messages); + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/DiscoverabilityProperties.java b/plugins/discoverability/src/main/java/mx/quest/discover/DiscoverabilityProperties.java new file mode 100644 index 0000000..96c36a6 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/DiscoverabilityProperties.java @@ -0,0 +1,172 @@ +package mx.quest.discover; + +import java.util.ArrayList; +import java.util.List; + +/** + * App-level settings for the discoverability plugin, bound from {@code runway.plugin.discoverability.*} + * (the host loads {@code external/plugin-settings/discoverability.yml} as a property source). These are + * platform concerns — the default AI/LLM-crawler posture a site inherits, the IndexNow egress switch — never + * per-tenant behaviour (which lives in the descriptor's {@code siteSettings} and is read live via + * {@code PluginSettings}). Bound by {@code @ConfigurationProperties} on its {@code @Bean} method in + * {@link DiscoverabilityConfig#discoverabilityProperties()}; applied on restart. + */ +public class DiscoverabilityProperties { + + private Robots robots = new Robots(); + private IndexNow indexnow = new IndexNow(); + + public Robots getRobots() { + return robots; + } + + public void setRobots(Robots robots) { + this.robots = robots; + } + + public IndexNow getIndexnow() { + return indexnow; + } + + public void setIndexnow(IndexNow indexnow) { + this.indexnow = indexnow == null ? new IndexNow() : indexnow; + } + + /** + * IndexNow platform settings — the operator's control over whether this deployment talks to third parties + * at all. + * + *

Why the platform switch exists and why it is OFF

+ * IndexNow is the first thing in this plugin that makes an outbound request on a tenant's behalf: a + * tenant enabling it causes this server to POST that tenant's URLs to an external service. Who this + * deployment is allowed to talk to is the platform operator's decision — they own the network, the + * egress firewall and the incident if it misbehaves — so a tenant cannot switch it on unilaterally. + * + *

Off by default because an upgrade must never start making network calls a deployment was not making + * before. A tenant who enables it while the platform has not gets a WARN naming the tenant and the setting + * to flip, rather than silence. + */ + public static class IndexNow { + + /** Whether tenants of this deployment may use IndexNow at all. Off until the operator permits it. */ + private boolean enabled = false; + + /** + * The submission endpoint. Configurable so an operator can point at a specific engine's endpoint or an + * internal proxy that carries their egress policy; the default is the shared endpoint, which forwards + * to every participating engine. + */ + private String endpoint = "https://api.indexnow.org/indexnow"; + + /** + * Seconds to gather changes before submitting. Batching is not an optimisation here — a page save + * touching five URLs must not become five outbound requests, and an editor working through a section + * would otherwise generate one per keystroke-to-save. + */ + private int batchSeconds = 60; + + /** + * Most URLs in one submission. The spec allows 10,000; a lower cap bounds both the request body and how + * much a single misbehaving tenant can send. Overflow is dropped with a WARN, never silently. + */ + private int maxUrlsPerSubmission = 1000; + + /** Most URLs queued per site between submissions. A bound on memory during a bulk edit or a restore. */ + private int maxQueuedPerSite = 5000; + + /** Connect/read timeout for the submission. Short: nothing waits on it, and a hung call helps nobody. */ + private int timeoutSeconds = 10; + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getEndpoint() { + return endpoint; + } + + public void setEndpoint(String endpoint) { + this.endpoint = endpoint; + } + + public int getBatchSeconds() { + return batchSeconds; + } + + public void setBatchSeconds(int batchSeconds) { + this.batchSeconds = batchSeconds; + } + + public int getMaxUrlsPerSubmission() { + return maxUrlsPerSubmission; + } + + public void setMaxUrlsPerSubmission(int maxUrlsPerSubmission) { + this.maxUrlsPerSubmission = maxUrlsPerSubmission; + } + + public int getMaxQueuedPerSite() { + return maxQueuedPerSite; + } + + public void setMaxQueuedPerSite(int maxQueuedPerSite) { + this.maxQueuedPerSite = maxQueuedPerSite; + } + + public int getTimeoutSeconds() { + return timeoutSeconds; + } + + public void setTimeoutSeconds(int timeoutSeconds) { + this.timeoutSeconds = timeoutSeconds; + } + } + + /** {@code /robots.txt} platform defaults. */ + public static class Robots { + + /** + * The default AI/LLM-crawler policy a site inherits when its per-tenant {@code robots.ai-policy} is + * {@code inherit} (the default): {@code allow} (GEO-friendly — the platform default) or {@code disallow} + * (opt every un-overriding site out of AI crawling). Bound from {@code robots.ai-default}. + */ + private String aiDefault = "allow"; + + public String getAiDefault() { + return aiDefault; + } + + public void setAiDefault(String aiDefault) { + this.aiDefault = aiDefault; + } + + /** + * Extra AI/LLM crawler user-agent names to cover, appended to the plugin's built-in list. Bound + * from {@code robots.ai-agents-extra}; empty by default, so the shipped behaviour is unchanged. + * + *

This exists because the built-in list is a compile-time constant that goes stale silently: when an + * operator announces a new agent, every site set to {@code disallow} is un-covered for it until a plugin + * release ships — and nothing reports the gap. This setting closes it the same day, without a release. + * + *

It is app-level, not per-tenant, deliberately: the set of agents that exist in the world is a + * platform fact, not tenant-owned behaviour. What a tenant chooses to do about them stays + * per-tenant, in {@code robots.ai-policy}. + * + *

Additive only, by design — there is no removal list. Naming an agent that has been retired costs one + * inert {@code User-agent:} line; being unable to add one that exists costs an un-covered opt-out. + */ + private List aiAgentsExtra = new ArrayList<>(); + + public List getAiAgentsExtra() { + return aiAgentsExtra; + } + + public void setAiAgentsExtra(List aiAgentsExtra) { + this.aiAgentsExtra = aiAgentsExtra == null ? new ArrayList<>() : aiAgentsExtra; + } + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/FaqAdvisoryCheck.java b/plugins/discoverability/src/main/java/mx/quest/discover/FaqAdvisoryCheck.java new file mode 100644 index 0000000..8a6d4c5 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/FaqAdvisoryCheck.java @@ -0,0 +1,103 @@ +package mx.quest.discover; + +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +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.service.PluginSettings; + +/** + * An advisory {@link PageQualityCheck} that closes the loop on the type-aware structured data: the plugin + * emits {@code FAQPage} from {@code content.schema}, and this check detects when a page has an + * on-page FAQ (a cluster of {@code

……
} disclosures) that isn't + * declared in {@code content.schema} yet, and nudges the author to add it — the "detect & lift" the audit + * asked for. FAQ is the single highest-leverage GEO win, so surfacing an unmarked one is worth an INFO finding. + * + *

It runs at edit/advisory time (the host passes the freshly-rendered {@link PageView#resolvedHtml()}), + * never at render, and it never edits the page — it only reports. It is quiet when there's nothing to say: + * it stays silent unless the page has at least two disclosure clusters (a single {@code

} is usually a + * "read more", not an FAQ), when the page is already typed {@code FAQPage} (the head renders it as one; no + * nagging about a FAQ that's already marked up), and on a noindex page, which carries no structured data. The + * finding is localized by its {@code code} via the host's message source + * ({@code quality.discoverability.faq.unmarked}); the string here is only the English fallback. + */ +public class FaqAdvisoryCheck implements PageQualityCheck { + + /** A {@code
} disclosure carrying a {@code } — i.e. a question/answer cluster. */ + private static final Pattern DISCLOSURE = Pattern.compile( + "]*>.*?]*>.*?.*?
", + Pattern.CASE_INSENSITIVE | Pattern.DOTALL); + + /** Below this many disclosures a page is unlikely to be an FAQ (avoids flagging a lone "read more"). */ + private static final int MIN_DISCLOSURES = 2; + + private static final String FALLBACK = + "This page has an on-page FAQ (a
/ block) that isn't emitting FAQPage structured " + + "data. Add it to the discoverability plugin's content.schema for this path (see the plugin help)."; + + private final PluginSettings settings; + private final Map types; + + public FaqAdvisoryCheck(PluginSettings settings) { + this(settings, DiscoverabilityConfig.schemaTypes()); + } + + FaqAdvisoryCheck(PluginSettings settings, Map types) { + this.settings = settings; + this.types = types; + } + + @Override + public String key() { + return "discoverability/faq-advisory"; + } + + @Override + public List inspect(PageView page) { + if (page == null || page.resolvedHtml().isBlank() || countDisclosures(page.resolvedHtml()) < MIN_DISCLOSURES) { + return List.of(); + } + if (page.page() != null && page.page().noindex()) { + return List.of(); // a noindex page carries no structured data, so FAQPage would do nothing there + } + if (!SiteConfig.bool(settings.site(page.site().id()).values(), "jsonld.enabled", true)) { + return List.of(); // structured data is off for the site, so FAQPage markup would never be published + } + if (alreadyTypedFaq(page)) { + return List.of(); // already marked up as FAQPage — nothing to advise + } + return List.of(Finding.info("discoverability.faq.unmarked", FALLBACK)); + } + + private static int countDisclosures(String html) { + Matcher m = DISCLOSURE.matcher(html); + int count = 0; + while (m.find()) { + count++; + } + return count; + } + + /** + * Whether the head renders this page as an {@code FAQPage}: the same {@link PageTypes} answer the head and the + * editor's line use. So a misspelt {@code faqpage} (an unknown type) or an {@code FAQPage} block after another + * page type (ignored) does not count as typed, as the page served does not carry it either. + */ + private boolean alreadyTypedFaq(PageView page) { + String canonical = page.canonical(); + if (canonical == null || canonical.isBlank()) { + return false; // no canonical to derive a path from — advise rather than assume it's typed + } + Map cfg = settings.site(page.site().id()).values(); + return "FAQPage".equals(PageTypes.describe(cfg, PageTypes.pathOf(page), types).type()); + } + + @Override + public Capabilities capabilities() { + return Capabilities.of("quality.advisory", "quality.geo"); + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/FaqPageSchema.java b/plugins/discoverability/src/main/java/mx/quest/discover/FaqPageSchema.java new file mode 100644 index 0000000..d742980 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/FaqPageSchema.java @@ -0,0 +1,72 @@ +package mx.quest.discover; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import mx.quest.runway.spi.model.HeadContext; + +/** + * Emits a schema.org {@code FAQPage} from a {@code faq:} list of question/answer pairs in the page's + * {@code content.schema} entry. FAQ is the highest-leverage GEO type — answer engines lift Q&A directly — + * so it is the first built-in {@link SchemaType}. The node is {@code mainEntityOfPage}-linked to this page's + * {@code WebPage} {@code @id}; each entry becomes a {@code Question} with an {@code acceptedAnswer}. + */ +final class FaqPageSchema implements SchemaType { + + @Override + public String key() { + return "FAQPage"; + } + + /** An FAQ page is what the page is: the questions become its own {@code mainEntity} (since 2.2.0). */ + @Override + public boolean describesPage(String token) { + return true; + } + + @Override + public List> nodes(HeadContext ctx, SchemaContext sc) { + return List.of(); // describes the page itself; see describePage + } + + @Override + public void describePage(Map page, HeadContext ctx, SchemaContext sc, + List> graph) { + List> questions = questions(sc); + if (!questions.isEmpty()) { + page.put("mainEntity", questions); + } + } + + /** No pair with both {@code q} and {@code a}: the page is an FAQPage with no questions. */ + @Override + public Gap gap(String token, Map block) { + return questions(block).isEmpty() ? new Gap("discover.gap.faq", + "{0} has no question with both q: and a:, so the page is an {0} with no questions.") : null; + } + + private static List> questions(SchemaContext sc) { + return questions(sc.pageConfig()); + } + + private static List> questions(Map block) { + List> questions = new ArrayList<>(); + for (Map qa : Schemas.maps(block, "faq")) { + String question = Schemas.str(qa, "q"); + String answer = Schemas.str(qa, "a"); + if (question == null || answer == null) { + continue; + } + Map node = new LinkedHashMap<>(); + node.put("@type", "Question"); + node.put("name", question); + Map accepted = new LinkedHashMap<>(); + accepted.put("@type", "Answer"); + accepted.put("text", answer); + node.put("acceptedAnswer", accepted); + questions.add(node); + } + return questions; + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/IndexNowKeyEndpoint.java b/plugins/discoverability/src/main/java/mx/quest/discover/IndexNowKeyEndpoint.java new file mode 100644 index 0000000..ac675d4 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/IndexNowKeyEndpoint.java @@ -0,0 +1,70 @@ +package mx.quest.discover; + +import java.util.List; +import java.util.Map; +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.PluginSettings; + +/** + * Serves the site's IndexNow key file — the proof of ownership the protocol requires. + * + *

Why a fixed path rather than {@code /.txt}

+ * IndexNow's usual pattern is a file named after the key itself. That cannot work here: the host matches + * routes by exact path and builds the table at startup, while the key is per-site configuration that changes + * at runtime. The spec's own {@code keyLocation} field exists for exactly this — a submission may name any URL + * on the host as the key's location — so the file lives at a stable path and every submission points there. + * + *

Not indexable, not in the sitemap, not cached

+ * It is a verification artifact, not content: it should never appear in search results, and a cached copy + * would keep answering with an old key after a tenant rotates it — which fails verification for as long as the + * cache lives, in a way that looks like the engine's fault. + */ +public class IndexNowKeyEndpoint implements EndpointContributor { + + private final PluginSettings settings; + private final DiscoverabilityProperties properties; + + public IndexNowKeyEndpoint(PluginSettings settings, DiscoverabilityProperties properties) { + this.settings = settings; + this.properties = properties; + } + + @Override + public String key() { + return "discoverability/indexnow-key"; + } + + @Override + public List routes() { + return List.of(new Route("GET", IndexNowSubmitter.KEY_PATH, Realm.TENANT, + new SurfacePosture(false, false, false))); + } + + @Override + public RouteResponse handle(RouteRequest req) { + Map cfg = settings.site(req.site().id()).values(); + String key = SiteConfig.str(cfg, "indexnow.key", "").trim(); + + // 404 unless the platform permits IndexNow AND this site turned it on AND a key is set. Serving a key + // for a site that is not using the feature would publish a value that only exists to be verified. + if (!properties.getIndexnow().isEnabled() + || !SiteConfig.bool(cfg, "indexnow.enabled", false) + || key.isEmpty()) { + return new RouteResponse(404, Map.of("Cache-Control", "no-store"), new byte[0]); + } + return new RouteResponse(200, + Map.of("Content-Type", "text/plain; charset=utf-8", "Cache-Control", "no-store"), + key.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + + @Override + public Capabilities capabilities() { + return Capabilities.of("endpoint.tenant", "endpoint.indexnow-key"); + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/IndexNowSubmitter.java b/plugins/discoverability/src/main/java/mx/quest/discover/IndexNowSubmitter.java new file mode 100644 index 0000000..c0f3a22 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/IndexNowSubmitter.java @@ -0,0 +1,395 @@ +package mx.quest.discover; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import mx.quest.runway.spi.model.CatalogChange; +import mx.quest.runway.spi.model.LocalizedUrl; +import mx.quest.runway.spi.model.SiteView; +import mx.quest.runway.spi.service.PluginSettings; +import mx.quest.runway.spi.service.SiteEventListener; +import mx.quest.runway.spi.service.Sites; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; + +/** + * Tells the IndexNow-participating search engines that a site's content changed, instead of waiting for them + * to come back and find out. + * + *

What this is, and what it is not

+ * IndexNow is a published protocol (Bing, Yandex, Seznam, Naver, Yep). It is a freshness signal, not a + * ranking one: it shortens the gap between publishing and being re-crawled by those engines. Google does + * not participate, so this changes nothing about Google's view of a site — worth saying plainly, because + * the opposite is widely implied and a tenant who turns this on should know what they are buying. + * + *

Two switches, both off by default, and why

+ * This is the first thing in the product that makes an outbound request on a tenant's behalf. So it + * needs the platform operator's permission (they own the network and the egress policy) and the + * tenant's (they own the URLs being disclosed). An upgrade must never start making network calls a deployment + * was not making before, so neither switch defaults on. A tenant who enables it while the platform has not + * gets a WARN naming both the tenant and the setting to flip — a feature that is silently inert is worse than + * one that is off, because nobody can tell the difference from inside. + * + *

What a change submits: where the item was, and where it is now

+ * The submitter is a {@link SiteEventListener} in the {@code CONSUMER} phase. Each page write or content change + * arrives as a {@link CatalogChange} carrying the item's URLs before the change (as the host last listed + * them) and after it; the submitter queues the union. So a deleted, unpublished or moved item reports + * its old address — the change most worth telling an engine about, and the one 1.x could not report, because it + * resolved the URLs after the host had already dropped the item from its listing. Only the node where the change + * happened submits ({@link CatalogChange#local()}): a cluster replays every change on its other nodes, and N nodes + * must not send N submissions. + * + *

Batched, bounded, and off every request thread

+ * Changes accumulate per site and are submitted by a scheduled flush ({@link #flush()}, a Spring + * {@code @Scheduled} method — it runs only while the host has scheduling enabled; see the method). A page save touching five localized URLs + * must not become five outbound requests, and a bulk edit or a site restore must not become thousands. + * Everything is bounded — queued URLs per site, URLs per submission — and overflow is dropped with a WARN + * naming the tenant, never silently. No save ever waits on the network, and a failed submission is logged and + * dropped rather than retried indefinitely: a stale IndexNow ping is worthless, and an unbounded retry queue + * during an outage is a liability. + * + *

The HTTP call is injected as an {@link Exchange} seam (the same pattern the protection plugin's captcha + * verifier uses), so the payload building, the gating and the bounds are unit-testable with no network at all. + */ +public class IndexNowSubmitter implements SiteEventListener { + + private static final Logger log = LoggerFactory.getLogger(IndexNowSubmitter.class); + + /** The fixed path the site's key file is served at — see {@link IndexNowKeyEndpoint}. */ + static final String KEY_PATH = "/indexnow-key.txt"; + + private final Sites sites; + private final PluginSettings settings; + private final DiscoverabilityProperties properties; + private final Exchange exchange; + + /** siteId → the URLs changed since the last flush. Bounded per site; insertion-ordered for stable batches. */ + private final Map> pending = new ConcurrentHashMap<>(); + + /** Sites already warned that they turned IndexNow on while the platform has it off — once per site per run. */ + private final Set warnedInert = ConcurrentHashMap.newKeySet(); + + public IndexNowSubmitter(Sites sites, PluginSettings settings, DiscoverabilityProperties properties) { + this(sites, settings, properties, defaultExchange(properties)); + } + + /** + * @param exchange the HTTP seam that performs the submission POST — injectable so the payload, the gating + * and the bounds are exercised without a real network call + */ + IndexNowSubmitter(Sites sites, PluginSettings settings, DiscoverabilityProperties properties, Exchange exchange) { + this.sites = sites; + this.settings = settings; + this.properties = properties; + this.exchange = exchange; + } + + // --- collecting ----------------------------------------------------------------------------------- + + /** + * A page was created, saved, renamed, deleted, published or unpublished, or a content source announced a change: + * every URL the item answered on before the change and every URL it answers on now is stale upstream. + * + *

Acts only on {@link CatalogChange#local() local} changes — the node where the change happened submits; a + * peer's replay is ignored. A change that names no item (a site lifecycle event, a settings save, a whole-site + * page reload) carries no URLs and is ignored, as 1.x ignored the events without an id. Runs on the writer's + * thread, so it only enqueues: the network call happens in {@link #flush()}. + */ + @Override + public void onCatalogChanged(CatalogChange change) { + if (!change.local() || change.id() == null) { + return; + } + enqueue(change.siteId(), change.previousUrls(), change.currentUrls()); + } + + /** + * Queues the item's URLs from before and after the change — {@code previous ∪ current}, in that order, + * duplicates dropped — if the site has IndexNow on. + * + *

Gated before doing any work, so a deployment with the feature off pays nothing per save. + */ + void enqueue(String siteId, List previous, List current) { + if (siteId == null) { + return; + } + if (!properties.getIndexnow().isEnabled()) { + warnIfInert(siteId); + return; + } + SiteView site = siteView(siteId); + if (site == null || key(siteId).isEmpty()) { + return; + } + Set urls = urlsOf(site, previous, current); + if (urls.isEmpty()) { + return; + } + int cap = Math.max(1, properties.getIndexnow().getMaxQueuedPerSite()); + Set queue = pending.computeIfAbsent(siteId, k -> java.util.Collections.synchronizedSet( + new LinkedHashSet<>())); + synchronized (queue) { + for (String url : urls) { + if (queue.size() >= cap) { + log.warn("IndexNow queue for site '{}' is full ({} URLs) — dropping further changes until " + + "the next submission. Raise indexnow.max-queued-per-site if this is routine.", + siteId, cap); + return; + } + queue.add(url); + } + } + } + + // --- submitting ----------------------------------------------------------------------------------- + + /** + * Submits each site's accumulated URLs. + * + *

The fixed rate is the platform's {@code indexnow.batch-seconds}; Spring cannot read a bean field for + * {@code @Scheduled}, so the annotation names the property and the default matches + * {@link DiscoverabilityProperties.IndexNow#getBatchSeconds()}. The value is kept inside the settings form's + * range, 5 to 3600 seconds, because a value set by hand (in the host's configuration or the settings file) + * never passes the form: 0 or a negative value made the start fail (the scheduler refuses a delay of 0 or less). + * A site with nothing queued costs one map lookup. + * + *

Scheduling is the host's. The method runs only while the host application has Spring scheduling + * enabled, which the kernel does unconditionally. This plugin deliberately does not start a scheduler of its own + * (a plugin thread the host neither knows about nor stops). + */ + @Scheduled(fixedDelayString = "#{T(java.lang.Math).max(5, T(java.lang.Math).min(3600, " + + "${runway.plugin.discoverability.indexnow.batch-seconds:60})) * 1000}") + public void flush() { + if (!properties.getIndexnow().isEnabled() || pending.isEmpty()) { + return; + } + for (String siteId : List.copyOf(pending.keySet())) { + Set queue = pending.remove(siteId); + if (queue == null || queue.isEmpty()) { + continue; + } + List urls; + synchronized (queue) { + urls = List.copyOf(queue); + } + submit(siteId, urls); + } + } + + /** + * Submits {@code urls} for one site, trimming to the per-submission cap and logging what was dropped. + * + *

Re-checks the platform switch even though every caller already has. A gate on outbound traffic is not + * a place to rely on "no caller can reach here without checking" — the check costs a field read, and the + * failure mode of getting it wrong is a deployment making network calls its operator refused. + */ + void submit(String siteId, List urls) { + if (!properties.getIndexnow().isEnabled()) { + return; + } + SiteView site = siteView(siteId); + String key = key(siteId); + if (site == null || key.isEmpty() || site.baseUrl() == null || site.baseUrl().isBlank()) { + return; + } + int cap = Math.max(1, properties.getIndexnow().getMaxUrlsPerSubmission()); + List batch = urls; + if (urls.size() > cap) { + // Named, counted, and attributed to the tenant: a silent trim is indistinguishable from a site + // that simply changed less than it did. + log.warn("IndexNow submission for site '{}' has {} URLs, over the {} cap — submitting the first {} " + + "and DROPPING {}. The dropped pages are still crawled normally.", + siteId, urls.size(), cap, cap, urls.size() - cap); + batch = urls.subList(0, cap); + } + String host = hostOf(site.baseUrl()); + String payload = payload(host, key, site.baseUrl() + KEY_PATH, batch); + try { + Exchange.Response response = exchange.post(properties.getIndexnow().getEndpoint(), payload); + if (response.status() >= 200 && response.status() < 300) { + log.debug("IndexNow: submitted {} URL(s) for site '{}' ({})", batch.size(), siteId, + response.status()); + } else { + // 403 means the key file did not verify — the single most likely misconfiguration, and one the + // tenant can fix, so say what it means rather than only what happened. + log.warn("IndexNow submission for site '{}' was refused ({}): {}{}", siteId, response.status(), + abbreviate(response.body()), + response.status() == 403 + ? " — the engine could not verify " + site.baseUrl() + KEY_PATH + + "; check the key matches and the path is publicly reachable." : ""); + } + } catch (IOException | RuntimeException failed) { + // Dropped, not retried: a stale freshness ping is worthless, and an unbounded retry queue during an + // outage is a liability. The pages are still crawled the ordinary way. + log.warn("IndexNow submission for site '{}' failed ({} URL(s) not submitted): {}", + siteId, batch.size(), failed.toString()); + } + } + + /** + * The IndexNow JSON body. + * + *

Hand-built rather than through a mapper because it is four fields and a string list, and the plugin + * has no JSON dependency of its own. Every value is escaped — {@code host} and {@code keyLocation} derive + * from tenant-controlled configuration, so an unescaped quote would be a payload-injection hole, not a + * formatting bug. + */ + static String payload(String host, String key, String keyLocation, List urls) { + StringBuilder json = new StringBuilder(128 + urls.size() * 64); + json.append("{\"host\":\"").append(escape(host)) + .append("\",\"key\":\"").append(escape(key)) + .append("\",\"keyLocation\":\"").append(escape(keyLocation)) + .append("\",\"urlList\":["); + for (int i = 0; i < urls.size(); i++) { + if (i > 0) { + json.append(','); + } + json.append('"').append(escape(urls.get(i))).append('"'); + } + return json.append("]}").toString(); + } + + private static String escape(String value) { + if (value == null) { + return ""; + } + StringBuilder out = new StringBuilder(value.length()); + for (char c : value.toCharArray()) { + switch (c) { + case '"' -> out.append("\\\""); + case '\\' -> out.append("\\\\"); + case '\n' -> out.append("\\n"); + case '\r' -> out.append("\\r"); + case '\t' -> out.append("\\t"); + default -> { + if (c < 0x20) { + out.append(String.format("\\u%04x", (int) c)); + } else { + out.append(c); + } + } + } + } + return out.toString(); + } + + // --- helpers -------------------------------------------------------------------------------------- + + /** The absolute form of every URL in {@code previous} then {@code current}, without duplicates. */ + private static Set urlsOf(SiteView site, List previous, List current) { + String base = site.baseUrl(); + Set urls = new LinkedHashSet<>(); + if (base == null || base.isBlank()) { + return urls; + } + for (List list : List.of(previous, current)) { + for (LocalizedUrl url : list) { + urls.add(url.absolute(base.trim())); + } + } + return urls; + } + + /** The site's IndexNow key, or empty when unset — which is how a tenant leaves the feature off. */ + /** + * The promise in the class Javadoc: a site that turned IndexNow on while the platform has it off is told, in + * the log, which setting to flip — once per site per run (the platform switch only changes on restart), and + * after that at no cost per save. The site's settings form says the same thing to the tenant. + */ + private void warnIfInert(String siteId) { + if (warnedInert.contains(siteId)) { + return; + } + Map cfg = settings.site(siteId).values(); + if (SiteConfig.bool(cfg, "indexnow.enabled", false) && warnedInert.add(siteId)) { + log.warn("site '{}' has IndexNow enabled, but the platform has not permitted it — nothing is submitted. " + + "The platform operator turns it on with discoverability's app-level indexnow.enabled.", siteId); + } + } + + /** Whether the inert-site warning has been logged for this site (tests). */ + boolean warnedInert(String siteId) { + return warnedInert.contains(siteId); + } + + private String key(String siteId) { + Map cfg = settings.site(siteId).values(); + if (!SiteConfig.bool(cfg, "indexnow.enabled", false)) { + return ""; + } + String key = SiteConfig.str(cfg, "indexnow.key", "").trim(); + if (key.isEmpty()) { + log.warn("site '{}' has IndexNow enabled but no indexnow.key — nothing is submitted. Generate a " + + "random key and set it, then confirm {} serves it.", siteId, KEY_PATH); + } + return key; + } + + private SiteView siteView(String siteId) { + return sites.find(siteId).orElse(null); + } + + /** The bare host of a base URL — what IndexNow's {@code host} field expects (no scheme, no path). */ + static String hostOf(String baseUrl) { + try { + String host = URI.create(baseUrl).getHost(); + return host == null ? "" : host; + } catch (IllegalArgumentException notAUrl) { + return ""; + } + } + + private static String abbreviate(String body) { + if (body == null) { + return ""; + } + String flat = body.replaceAll("[\\r\\n]+", " ").trim(); + return flat.length() <= 200 ? flat : flat.substring(0, 200) + "…"; + } + + // --- the HTTP seam -------------------------------------------------------------------------------- + + /** The outbound call, isolated so everything around it is testable without a network. */ + public interface Exchange { + + /** + * POSTs {@code json} ({@code application/json}) to {@code url}. + * + * @return the endpoint's response (status + body) + * @throws IOException if the request cannot be completed + */ + Response post(String url, String json) throws IOException; + + /** A minimal HTTP response view — the status and body this submitter needs to log an outcome. */ + record Response(int status, String body) { + } + } + + private static Exchange defaultExchange(DiscoverabilityProperties properties) { + Duration timeout = Duration.ofSeconds(Math.max(1, properties.getIndexnow().getTimeoutSeconds())); + HttpClient client = HttpClient.newBuilder().connectTimeout(timeout).build(); + return (url, json) -> { + try { + HttpRequest request = HttpRequest.newBuilder(URI.create(url)) + .timeout(timeout) + .header("Content-Type", "application/json; charset=utf-8") + .POST(HttpRequest.BodyPublishers.ofString(json)) + .build(); + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + return new Exchange.Response(response.statusCode(), response.body()); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IOException("IndexNow submission interrupted", interrupted); + } + }; + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/Ld.java b/plugins/discoverability/src/main/java/mx/quest/discover/Ld.java new file mode 100644 index 0000000..d3f31e5 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/Ld.java @@ -0,0 +1,108 @@ +package mx.quest.discover; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import tools.jackson.databind.json.JsonMapper; + +/** + * The schema.org JSON-LD builder — the shared spine of both SEO+ and GEO. It builds ordered node maps, + * serializes them into a single {@code @graph}, and wraps that in a {@code "; + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/LlmsTxtEndpoint.java b/plugins/discoverability/src/main/java/mx/quest/discover/LlmsTxtEndpoint.java new file mode 100644 index 0000000..fc002a2 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/LlmsTxtEndpoint.java @@ -0,0 +1,124 @@ +package mx.quest.discover; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import mx.quest.runway.spi.EndpointContributor; +import mx.quest.runway.spi.model.Capabilities; +import mx.quest.runway.spi.model.CatalogEntry; +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.ContentCatalogView; +import mx.quest.runway.spi.service.PluginSettings; + +/** + * GEO — serves a per-site {@code /llms.txt}, the emerging convention for exposing a site's content to + * large-language-model / answer engines in a compact, machine-friendly form: an {@code H1} of the site name, a + * one-line summary (the tenant's {@code geo.summary}), then the site's whole published content surface — + * kernel pages AND every content source's items (blog entries, any plugin content) — as Markdown links with + * their descriptions, in the site's default locale. Built from the host's {@link ContentCatalogView} + * (kernel-re-filtered, metadata-only: no item's body is ever read serving this route). + * + *

Each item is linked at {@link CatalogEntry#pathFor(Locale) its address in the default locale}, or — for an + * item that does not exist in the default locale — at its primary locale's real address. (Until 2.0.0 such an item + * was linked at its unprefixed default path, which the site answers with a 404.) + * + *

Part of the opt-in GEO area: gated by the per-tenant {@code geo.enabled} flag — disabled ⇒ {@code 404}. + */ +public class LlmsTxtEndpoint implements EndpointContributor { + + private final ContentCatalogView catalog; + private final PluginSettings settings; + + public LlmsTxtEndpoint(ContentCatalogView catalog, PluginSettings settings) { + this.catalog = catalog; + this.settings = settings; + } + + @Override + public String key() { + return "discoverability/llms"; + } + + @Override + public List routes() { + // Cacheable: this endpoint manages its own caching (Last-Modified + no-cache revalidation). + return List.of(new Route("GET", "/llms.txt", Realm.TENANT, new SurfacePosture(true, true, true))); + } + + @Override + public RouteResponse handle(RouteRequest req) { + Map cfg = settings.site(req.site().id()).values(); + if (!SiteConfig.bool(cfg, "geo.enabled", false)) { + // The route posture is cacheable (so the 200/304 carry their own validators), which means the + // dispatcher no longer stamps a fail-safe no-store — so this disabled-path 404 must forbid caching + // itself, or a heuristically-cacheable 404 could outlive the tenant re-enabling the surface. + return new RouteResponse(404, java.util.Map.of("Cache-Control", "no-store"), new byte[0]); + } + String base = PageUrls.base(req.site(), req); + Locale def = req.site().defaultLocale(); + + List items = catalog.entries(req.site().id()); + String summary = SiteConfig.str(cfg, "geo.summary", ""); + // The validator folds what this document prints besides the items: the H1 (the site name), the summary, + // the locale every title and link is chosen in, and the site's base URL every link starts with — so editing + // any of them advances Last-Modified and a revalidating crawler refetches (until 2.1.0 it kept the old copy). + // The base URL, not the request origin: a host-less site reached under two names serves each its own links, + // and each crawler's copy stays right for the address it fetched — folding the origin would only make the + // validator advance on every alternate request. + java.time.Instant newest = CrawlConditional.lastModified(req.site().id(), CrawlConditional.LLMS, items, + java.util.Arrays.asList(req.site().displayName(), summary, def.toLanguageTag(), + req.site().baseUrl())); + if (CrawlConditional.notModified(req, newest)) { + return CrawlConditional.notModifiedResponse(newest); + } + + StringBuilder out = new StringBuilder(512); + out.append("# ").append(req.site().displayName()).append("\n\n"); + if (!summary.isBlank()) { + out.append("> ").append(oneLine(summary)).append("\n\n"); + } + out.append("## Pages\n\n"); + for (CatalogEntry item : items) { + // Same rule as the sitemap: content the site tells robots not to index has no business being + // advertised to answer engines either. llms.txt is a recommendation list, not a site dump. + if (item.ref().noindex()) { + continue; + } + String title = item.ref().titleFor(def); + String label = mdLabel((title == null || title.isBlank()) ? item.ref().id() : title); + String url = base + item.pathFor(def); + out.append("- [").append(label).append("](").append(url).append(")"); + String desc = item.ref().descriptionFor(def); + if (desc != null && !desc.isBlank()) { + out.append(": ").append(oneLine(desc)); + } + out.append('\n'); + } + return new RouteResponse(200, + CrawlConditional.cacheHeaders(newest, "text/plain; charset=utf-8"), + out.toString().getBytes(StandardCharsets.UTF_8)); + } + + private static String oneLine(String text) { + return text.replace('\n', ' ').replace('\r', ' ').trim(); + } + + /** + * A markdown-safe link label: one line, with the link metacharacters mapped to parentheses-free forms so a + * legitimate title like {@code FAQ [updated]} cannot terminate the {@code [label](url)} early and corrupt + * the machine-parsed index. + */ + private static String mdLabel(String text) { + return oneLine(text).replace('[', '(').replace(']', ')'); + } + + @Override + public Capabilities capabilities() { + return Capabilities.of("endpoint.tenant", "endpoint.geo"); + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/LocalBusinessSchema.java b/plugins/discoverability/src/main/java/mx/quest/discover/LocalBusinessSchema.java new file mode 100644 index 0000000..15a4ea7 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/LocalBusinessSchema.java @@ -0,0 +1,75 @@ +package mx.quest.discover; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import mx.quest.runway.spi.model.HeadContext; + +/** + * Emits one or more schema.org {@code LocalBusiness} nodes (or the entry's declared subtype, e.g. + * {@code CafeOrCoffeeShop}) from a {@code content.schema} entry. A {@code locations:} list yields one node per + * location (name/address/geo/telephone/openingHours/priceRange); with no list, a single node is built from the + * entry's own fields. {@code geo} is emitted only when both latitude and longitude are provided. + */ +final class LocalBusinessSchema implements SchemaType { + + @Override + public String key() { + return "LocalBusiness"; + } + + @Override + public List> nodes(HeadContext ctx, SchemaContext sc) { + Map cfg = sc.pageConfig(); + String type = Schemas.str(cfg, "type", "LocalBusiness"); // LocalBusiness | CafeOrCoffeeShop | … + List> locations = Schemas.maps(cfg, "locations"); + List> out = new ArrayList<>(); + if (locations.isEmpty()) { + out.add(business(type, cfg, ctx, sc, 1)); + } else { + int index = 1; + for (Map location : locations) { + out.add(business(type, location, ctx, sc, index++)); + } + } + return out; + } + + private static Map business(String type, Map b, HeadContext ctx, + SchemaContext sc, int index) { + // A stable @id per location (canonical#business-N) + a link back to the page, so each node is part of the + // graph rather than a bare, unlinked node. geo is emitted below when the tenant supplies coordinates. + Map node = Ld.node(type, sc.canonical() + "#business-" + index); + Ld.ref(node, "mainEntityOfPage", sc.webpageId()); + Ld.put(node, "url", Schemas.absolute(Schemas.str(b, "url", sc.canonical()), sc.base())); + Ld.put(node, "name", Schemas.str(b, "name", ctx.site().displayName())); + Ld.put(node, "telephone", Schemas.str(b, "telephone")); + Ld.putList(node, "image", Schemas.absolute(Schemas.strings(b, "image"), sc.base())); + Ld.put(node, "priceRange", Schemas.str(b, "priceRange")); + Ld.putList(node, "openingHours", Schemas.strings(b, "hours")); + + String street = Schemas.str(b, "street"); + String locality = Schemas.str(b, "locality"); + if (street != null || locality != null) { + Map address = Ld.node("PostalAddress", null); + Ld.put(address, "streetAddress", street); + Ld.put(address, "addressLocality", locality); + Ld.put(address, "addressRegion", Schemas.str(b, "region")); + Ld.put(address, "postalCode", Schemas.str(b, "postalCode")); + Ld.put(address, "addressCountry", Schemas.str(b, "country")); + node.put("address", address); + } + + String latitude = Schemas.str(b, "latitude"); + String longitude = Schemas.str(b, "longitude"); + if (latitude != null && longitude != null) { + Map geo = new LinkedHashMap<>(); + geo.put("@type", "GeoCoordinates"); + geo.put("latitude", latitude); + geo.put("longitude", longitude); + node.put("geo", geo); + } + return node; + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/PageSchemaConfig.java b/plugins/discoverability/src/main/java/mx/quest/discover/PageSchemaConfig.java new file mode 100644 index 0000000..b551847 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/PageSchemaConfig.java @@ -0,0 +1,164 @@ +package mx.quest.discover; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import tools.jackson.dataformat.yaml.YAMLMapper; + +/** + * Parses the per-tenant {@code content.schema} text (a small YAML document keyed by URL-path pattern) and + * resolves the entry for a given page path. Parsing is memoized by the raw text, so it happens once per distinct + * config value (which changes only when the tenant edits it) rather than per request. + * + *

Format — a map of path pattern → entry. An entry is either one type-block (a map with a {@code type} + * plus type-specific fields) or a list of type-blocks when a single page carries several types (e.g. a + * pricing page that is both an {@code FAQPage} and a set of {@code Offer}s): + *

+ * /coffee-*:
+ *   type: Product
+ *   currency: USD
+ * /pricing:
+ *   - type: FAQPage
+ *     faq: [ { q: "Why ranges?", a: "Scope drives cost…" } ]
+ *   - type: Service
+ *     offers: [ { name: "Advisory Sprint", price: "18000", currency: USD } ]
+ * 
+ * A pattern ending in {@code *} is a prefix match; an exact path always wins, and among prefix patterns + * the longest wins. A malformed document disables typing (returns no entries) rather than breaking the page. + */ +final class PageSchemaConfig { + + private static final YAMLMapper YAML = YAMLMapper.builder().build(); + private static final int MAX_CACHE = 128; + // Memo keyed by the raw config text — self-evicting (a changed value is a new key); bounded as a backstop. + // Value: pattern → entry, where an entry is a Map (one type-block) or a List of Maps (several). + private static final Map> CACHE = new ConcurrentHashMap<>(); + + private PageSchemaConfig() { + } + + /** Parses {@code content.schema} into {@code pattern → entry}; empty for blank/malformed input. */ + static Map parse(String text) { + if (text == null || text.isBlank()) { + return Map.of(); + } + Map cached = CACHE.get(text); + if (cached != null) { + return cached; + } + Map parsed = doParse(text); + if (CACHE.size() > MAX_CACHE) { + CACHE.clear(); + } + CACHE.put(text, parsed); + return parsed; + } + + /** + * Why {@code text} cannot be used at all, or {@code null} when it parses (blank included): the YAML error, or a + * root that is not a map of patterns. {@link #parse} turns either into "no types" so a page never breaks; this + * tells the site manager instead. + */ + static String syntaxProblem(String text) { + if (text == null || text.isBlank()) { + return null; + } + try { + Object root = YAML.readValue(text, Object.class); + return root instanceof Map ? null : "the text is not a list of 'pattern: type' entries"; + } catch (Exception e) { + String message = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage(); + int newline = message.indexOf('\n'); + return newline > 0 ? message.substring(0, newline) : message; + } + } + + /** The raw entries whose value is neither one block nor a list of blocks: they are ignored. */ + static List ignoredPatterns(String text) { + List out = new ArrayList<>(); + try { + Object root = YAML.readValue(text, Object.class); + if (root instanceof Map map) { + for (var entry : map.entrySet()) { + if (!(entry.getValue() instanceof Map || entry.getValue() instanceof List)) { + out.add(String.valueOf(entry.getKey())); + } + } + } + } catch (Exception ignored) { + // syntaxProblem reports it + } + return out; + } + + private static Map doParse(String text) { + try { + Object root = YAML.readValue(text, Object.class); + if (!(root instanceof Map map)) { + return Map.of(); + } + Map out = new LinkedHashMap<>(); + for (var entry : map.entrySet()) { + // An entry is one type-block (Map) or several (List); anything else is ignored. + if (entry.getKey() != null && (entry.getValue() instanceof Map || entry.getValue() instanceof List)) { + out.put(entry.getKey().toString(), entry.getValue()); + } + } + return out; + } catch (Exception ex) { + return Map.of(); // a malformed content.schema disables typing rather than breaking the page + } + } + + /** The entry (a Map or a List) whose pattern matches {@code path}: exact wins, else the longest {@code *}-prefix. */ + static Object resolve(Map patterns, String path) { + String pattern = matchingPattern(patterns, path); + return pattern == null ? null : patterns.get(pattern); + } + + /** + * The pattern that matches {@code path}: the path itself when listed, else the longest {@code *}-prefix whose + * prefix starts the path; {@code null} when none does. A {@code *} anywhere but at the end is a literal + * character. + */ + static String matchingPattern(Map patterns, String path) { + if (patterns.isEmpty() || path == null) { + return null; + } + if (patterns.containsKey(path)) { + return path; + } + String best = null; + int bestLen = -1; + for (String pattern : patterns.keySet()) { + if (pattern.endsWith("*")) { + String prefix = pattern.substring(0, pattern.length() - 1); + if (path.startsWith(prefix) && prefix.length() > bestLen) { + best = pattern; + bestLen = prefix.length(); + } + } + } + return best; + } + + /** Normalizes a resolved entry to its list of type-blocks: a single Map → one block; a List → its Map items. */ + @SuppressWarnings("unchecked") + static List> blocks(Object entry) { + if (entry instanceof Map map) { + return List.of((Map) map); + } + if (entry instanceof List list) { + List> out = new ArrayList<>(); + for (Object item : list) { + if (item instanceof Map map) { + out.add((Map) map); + } + } + return out; + } + return List.of(); + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/PageTypeCheck.java b/plugins/discoverability/src/main/java/mx/quest/discover/PageTypeCheck.java new file mode 100644 index 0000000..6d9a677 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/PageTypeCheck.java @@ -0,0 +1,127 @@ +package mx.quest.discover; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +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.service.Messages; +import mx.quest.runway.spi.service.PluginSettings; + +/** + * The page editor's line about structured data: what this page is described as, and where that comes from — the + * site's Default page type, or a Per-page types ({@code content.schema}) pattern — plus what the entry adds, and a + * warning for a type the plugin does not know, a second page type it ignores, or a block that publishes nothing of + * its own (an {@code FAQPage} with no complete question). A noindex page carries no structured data, and the line + * says so first, as the head checks it first. A translated page that the default language's entry does not reach + * gets a note naming the key that would. + * + *

Why

+ * The site form says "Default page type", and nothing showed whether a + * given page took it or something else. The answer is computed by {@link PageTypes}, the same code the public page's + * {@code } uses, so the editor cannot describe a page differently from how it is served. + * + *

Reported through the existing quality-check seam as {@code INFO} (a neutral observation, never a gate) and + * {@code WARNING} findings; their text is resolved here in the operator's UI language, since a finding carries no + * message arguments. + */ +public class PageTypeCheck implements PageQualityCheck { + + static final String CODE = "discoverability.page-type"; + static final String CODE_UNKNOWN = "discoverability.page-type.unknown"; + static final String CODE_EXTRA = "discoverability.page-type.extra"; + static final String CODE_GAP = "discoverability.page-type.gap"; + static final String CODE_OTHER_LANGUAGE = "discoverability.page-type.other-language"; + + private final PluginSettings settings; + private final Map types; + private final Messages messages; + + PageTypeCheck(PluginSettings settings, Map types, Messages messages) { + this.settings = settings; + this.types = types; + this.messages = messages; + } + + @Override + public String key() { + return "discoverability/page-type"; + } + + @Override + public List inspect(PageView page) { + if (page == null || page.canonical() == null || page.canonical().isBlank()) { + return List.of(); + } + if (page.page() != null && page.page().noindex()) { + // The head emits no JSON-LD on a noindex page, before it looks at anything else; so does this line. + return List.of(Finding.info(CODE, text("discover.pagetype.noindex", + "Structured data: this page is excluded from search engines (noindex), so it carries no " + + "structured data."))); + } + Map cfg = settings.site(page.site().id()).values(); + if (!SiteConfig.bool(cfg, "jsonld.enabled", true)) { + return List.of(Finding.info(CODE, text("discover.pagetype.off", + "Structured data is switched off for this site, so this page is not described to search " + + "engines."))); + } + String path = PageTypes.pathOf(page); + PageTypes.Description d = PageTypes.describe(cfg, path, types); + List findings = new ArrayList<>(); + String main = d.source() == PageTypes.Source.SCHEMA + ? text("discover.pagetype.schema", "Structured data: this page is a {0}, set by Per-page types " + + "(pattern {1}).", d.type(), d.pattern()) + : text("discover.pagetype.default", "Structured data: this page is a {0}, the site''s Default " + + "page type.", d.type()); + if (!d.added().isEmpty()) { + main = main + " " + text("discover.pagetype.added", "Per-page types also add: {0}.", + String.join(", ", d.addedTypes())); + } + findings.add(Finding.info(CODE, main)); + PageTypes.OtherLanguageEntry other = PageTypes.otherLanguageEntry(cfg, path, page.site()); + if (other != null) { + findings.add(Finding.info(CODE_OTHER_LANGUAGE, text("discover.pagetype.otherLanguage", + "Per-page types: {0} describes the default language''s page, not this one; a page in another " + + "language is matched only by its own path. To describe this page, add {1}.", + other.pattern(), other.suggestion()))); + } + if (d.pageBlock() != null) { + gap(findings, d.type(), d.pageBlock()); + } + for (Map block : d.added()) { + gap(findings, Schemas.str(block, "type", ""), block); + } + if (!d.unknown().isEmpty()) { + findings.add(Finding.warning(CODE_UNKNOWN, text("discover.pagetype.unknown", + "Per-page types name {0} for this page, which this plugin does not know; it is ignored.", + String.join(", ", d.unknown())))); + } + if (!d.extraPageTypes().isEmpty()) { + findings.add(Finding.warning(CODE_EXTRA, text("discover.pagetype.extra", + "Per-page types give this page more than one page type; only the first ({0}) applies, " + + "{1} is ignored.", d.type(), String.join(", ", d.extraPageTypes())))); + } + return findings; + } + + /** A warning for a block that applies but publishes nothing of its own ({@link SchemaType#gap}). */ + private void gap(List findings, String token, Map block) { + SchemaType handler = types.get(token); + SchemaType.Gap gap = handler == null ? null : handler.gap(token, block); + if (gap != null) { + findings.add(Finding.warning(CODE_GAP, text(gap.code(), gap.fallback(), token))); + } + } + + private String text(String code, String fallback, Object... args) { + return messages == null ? java.text.MessageFormat.format(fallback, args) + : messages.console(code, fallback, args); + } + + @Override + public Capabilities capabilities() { + return Capabilities.of("quality.advisory", "quality.structured-data"); + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/PageTypes.java b/plugins/discoverability/src/main/java/mx/quest/discover/PageTypes.java new file mode 100644 index 0000000..2a58558 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/PageTypes.java @@ -0,0 +1,182 @@ +package mx.quest.discover; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import mx.quest.runway.spi.model.SiteView; + +/** + * How one page is described in structured data: its own type, where that type comes from, and what else its + * {@code content.schema} entry adds. The one answer both the public page ({@link StructuredDataHead}) and the page + * editor's line ({@link PageTypeCheck}) use, so the two can never disagree. + * + *

The rule

+ *
    + *
  • The page's {@code content.schema} entry is found by its own path: the exact path, else the longest + * {@code *}-prefix. A page behind a language prefix ({@code /es/faq}) is matched only by a key written for that + * path ({@code /es/faq}, {@code /es/*}, {@code /*}); {@code /faq} does not reach it, because an entry's text + * (questions, names, a breadcrumb parent) is written in one language and would be published on the other + * language's page.
  • + *
  • The first block whose type describes the page itself ({@link SchemaType#describesPage}) sets the page's + * type; otherwise the page has the site's Default page type ({@code jsonld.type}).
  • + *
  • Every other recognized block adds an entity (a product, a service, a business, a person, a list).
  • + *
  • A block naming an unknown type is ignored, and so is a second block that describes the page (a page has one + * type); both are reported in the editor so neither goes unnoticed.
  • + *
+ */ +final class PageTypes { + + /** Where the page's own type came from. */ + enum Source { + /** The site's Default page type ({@code jsonld.type}). */ + DEFAULT, + /** A {@code content.schema} block for this page. */ + SCHEMA + } + + /** + * One page's description. + * + * @param type the page's own {@code @type} + * @param source where {@code type} came from + * @param pattern the matching {@code content.schema} pattern, or {@code null} when none matches + * @param pageBlock the block that set the type ({@code null} when it is the default) + * @param added the blocks that add an entity, in declared order + * @param unknown type tokens in the entry that no handler knows (a block with no {@code type} is not listed) + * @param extraPageTypes page-describing tokens after the first, which are ignored + */ + record Description(String type, Source source, String pattern, Map pageBlock, + List> added, List unknown, List extraPageTypes) { + + /** The type tokens of the added blocks, in order. */ + List addedTypes() { + List out = new ArrayList<>(); + for (Map block : added) { + out.add(Schemas.str(block, "type", "")); + } + return out; + } + } + + private PageTypes() { + } + + /** + * The path of the page a {@link mx.quest.runway.spi.model.PageView} shows, relative to the site base, the way the + * head derives it from the canonical URL. + */ + static String pathOf(mx.quest.runway.spi.model.PageView page) { + String base = page.site().baseUrl(); + base = (base != null && !base.isBlank()) ? base.trim() : ""; + if (base.endsWith("/")) { + base = base.substring(0, base.length() - 1); + } + return StructuredDataHead.pathOf(base, page.canonical()); + } + + /** The site's Default page type as the head uses it: {@code Article} when so configured, else {@code WebPage}. */ + static String defaultType(Map cfg) { + return "Article".equals(SiteConfig.str(cfg, "jsonld.type", "WebPage")) ? "Article" : "WebPage"; + } + + /** + * Describes the page at {@code path}. + * + * @param cfg the site's discoverability settings + * @param path the page's path relative to the site base, starting with {@code /} + * @param types the type registry, by token + */ + static Description describe(Map cfg, String path, Map types) { + Map patterns = PageSchemaConfig.parse(SiteConfig.str(cfg, "content.schema", "")); + String pattern = PageSchemaConfig.matchingPattern(patterns, path); + Map pageBlock = null; + String pageType = null; + List> added = new ArrayList<>(); + List unknown = new ArrayList<>(); + List extraPageTypes = new ArrayList<>(); + if (pattern != null) { + for (Map block : PageSchemaConfig.blocks(patterns.get(pattern))) { + String token = Schemas.str(block, "type", ""); + if (token.isBlank()) { + continue; // a block with no type only carries shared fields (a breadcrumb parent) + } + SchemaType handler = types.get(token); + if (handler == null) { + unknown.add(token); + } else if (handler.describesPage(token)) { + if (pageBlock == null) { + pageBlock = block; + pageType = token; + } else { + extraPageTypes.add(token); + } + } else { + added.add(block); + } + } + } + return pageBlock != null + ? new Description(pageType, Source.SCHEMA, pattern, pageBlock, added, unknown, extraPageTypes) + : new Description(defaultType(cfg), Source.DEFAULT, pattern, null, added, unknown, extraPageTypes); + } + + /** The matching {@code content.schema} entry for {@code path}, or {@code null}. */ + static Object entry(Map cfg, String path) { + Map patterns = PageSchemaConfig.parse(SiteConfig.str(cfg, "content.schema", "")); + String pattern = PageSchemaConfig.matchingPattern(patterns, path); + return pattern == null ? null : patterns.get(pattern); + } + + /** + * The default language's entry that does not reach a translated page. + * + * @param pattern the pattern matching the same path in the default language ({@code /faq}) + * @param suggestion the key that would describe this page ({@code /es/faq}; {@code /es/blog/*} for {@code /blog/*}) + */ + record OtherLanguageEntry(String pattern, String suggestion) { + } + + /** + * For a page behind a non-default language prefix ({@code /es/faq}): the pattern that matches the same path in + * the default language ({@code /faq}) but not this page; {@code null} when there is none, or when this page's own + * match is at least as specific (the same {@code /*}, or {@code /es/*} beside {@code /*}). Only the page editor + * uses it, to say that the other language's entry does not reach this page and which key would. + */ + static OtherLanguageEntry otherLanguageEntry(Map cfg, String path, SiteView site) { + String prefix = path == null || site == null ? null : languagePrefix(path, site); + if (prefix == null) { + return null; + } + String stripped = path.length() <= prefix.length() + 1 ? "/" : path.substring(prefix.length()); + Map patterns = PageSchemaConfig.parse(SiteConfig.str(cfg, "content.schema", "")); + String base = PageSchemaConfig.matchingPattern(patterns, stripped); + String own = PageSchemaConfig.matchingPattern(patterns, path); + if (base == null || (own != null && specificity(own, path) >= specificity(base, stripped))) { + return null; // nothing to say, or this page's own match is at least as specific (/es/*, /*) + } + return new OtherLanguageEntry(base, base.equals(stripped) ? path : prefix + base); + } + + /** How specific a matching pattern is: an exact key above any prefix, a longer prefix above a shorter one. */ + private static int specificity(String pattern, String path) { + return pattern.equals(path) ? Integer.MAX_VALUE : pattern.length(); + } + + /** + * The leading {@code /} of {@code path} when that language is one of the site's languages other than + * the default ({@code /es} for {@code /es/faq} and for {@code /es}); {@code null} otherwise. + */ + static String languagePrefix(String path, SiteView site) { + for (Locale locale : site.locales()) { + if (locale.equals(site.defaultLocale())) { + continue; // the default language's pages are unprefixed + } + String prefix = "/" + locale.getLanguage(); + if (path.equals(prefix) || path.startsWith(prefix + "/")) { + return prefix; + } + } + return null; + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/PageUrls.java b/plugins/discoverability/src/main/java/mx/quest/discover/PageUrls.java new file mode 100644 index 0000000..13b4842 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/PageUrls.java @@ -0,0 +1,33 @@ +package mx.quest.discover; + +import mx.quest.runway.spi.model.RouteRequest; +import mx.quest.runway.spi.model.SiteView; + +/** + * The absolute base of the crawl-surface endpoints (sitemap, robots.txt, llms.txt). The URLs themselves come from + * the host's content listing ({@code CatalogEntry} / {@code LocalizedUrl}, root-relative) — this plugin never + * applies the URL scheme itself; it only prefixes the origin. + */ +final class PageUrls { + + private PageUrls() { + } + + /** + * The site's absolute base ({@code scheme://host[:port]}, no trailing slash): the site view's base URL — which + * the host fills with the configured base URL, else {@code https://} — and, for a + * site with neither (a host-less catch-all site), the request's trusted origin + * ({@link RouteRequest#origin()}: the scheme and host as the host's trusted-proxy gate leaves them — a configured + * proxy's forwarded values applied, raw values otherwise). Empty only when none is known. + * + *

Until 2.0.0 that last fallback was built from the raw {@code Host} header with the scheme read from + * {@code X-Forwarded-Proto} — which the kernel does not pass to plugins — or else guessed as + * {@code https}. The origin replaces both: no header is trusted unless the operator trusted the proxy that set + * it, and the scheme is the one the request actually arrived on. + */ + static String base(SiteView site, RouteRequest req) { + String configured = site.baseUrl(); + String base = (configured != null && !configured.isBlank()) ? configured.trim() : req.origin().trim(); + return base.endsWith("/") ? base.substring(0, base.length() - 1) : base; + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/PersonSchema.java b/plugins/discoverability/src/main/java/mx/quest/discover/PersonSchema.java new file mode 100644 index 0000000..b8d2ccd --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/PersonSchema.java @@ -0,0 +1,56 @@ +package mx.quest.discover; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import mx.quest.runway.spi.model.HeadContext; + +/** + * Emits schema.org {@code Person} node(s) from a {@code content.schema} entry — a {@code people:} list yields + * one {@code Person} per member (name/jobTitle/image/sameAs, {@code worksFor}→Organization); with no list, a + * single {@code Person} is built from the entry's own fields. A person with no name is skipped. + */ +final class PersonSchema implements SchemaType { + + @Override + public String key() { + return "Person"; + } + + @Override + public List> nodes(HeadContext ctx, SchemaContext sc) { + Map cfg = sc.pageConfig(); + List> people = Schemas.maps(cfg, "people"); + List> out = new ArrayList<>(); + if (people.isEmpty()) { + Map single = person(cfg, sc); + if (single != null) { + out.add(single); + } + } else { + for (Map member : people) { + Map node = person(member, sc); + if (node != null) { + out.add(node); + } + } + } + return out; + } + + private static Map person(Map p, SchemaContext sc) { + String name = Schemas.str(p, "name"); + if (name == null) { + return null; + } + Map node = Ld.node("Person", null); + Ld.put(node, "name", name); + Ld.put(node, "jobTitle", Schemas.str(p, "jobTitle")); + Ld.putList(node, "image", Schemas.absolute(Schemas.strings(p, "image"), sc.base())); + Ld.putList(node, "sameAs", Schemas.strings(p, "sameAs")); + if (sc.hasOrg()) { + Ld.ref(node, "worksFor", sc.organizationId()); + } + return node; + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/ProductSchema.java b/plugins/discoverability/src/main/java/mx/quest/discover/ProductSchema.java new file mode 100644 index 0000000..77a46b0 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/ProductSchema.java @@ -0,0 +1,53 @@ +package mx.quest.discover; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import mx.quest.runway.spi.model.HeadContext; + +/** + * Emits a schema.org {@code Product} (with a nested {@code Offer}) from a product page's {@code content.schema} + * entry — name/description/image/sku, {@code brand}→Organization, and {@code offers}(price/currency/availability/ + * url). Name and description fall back to the page's title/description. The node is {@code mainEntityOfPage}-linked + * to this page's {@code WebPage}. + */ +final class ProductSchema implements SchemaType { + + @Override + public String key() { + return "Product"; + } + + @Override + public List> nodes(HeadContext ctx, SchemaContext sc) { + Map cfg = sc.pageConfig(); + String name = Schemas.str(cfg, "name", ctx.page().title()); + if (name == null || name.isBlank()) { + return List.of(); // nothing substantive to say — don't emit a bare {@type: Product} node + } + Map product = Ld.node("Product", null); + Ld.put(product, "name", name); + Ld.put(product, "description", Schemas.str(cfg, "description", ctx.page().description())); + Ld.putList(product, "image", Schemas.absolute(Schemas.strings(cfg, "image"), sc.base())); + Ld.put(product, "sku", Schemas.str(cfg, "sku")); + Ld.ref(product, "mainEntityOfPage", sc.webpageId()); + if (sc.hasOrg()) { + Ld.ref(product, "brand", sc.organizationId()); + } + String price = Schemas.str(cfg, "price"); + if (price != null) { + Map offer = new LinkedHashMap<>(); + offer.put("@type", "Offer"); + offer.put("price", price); + offer.put("priceCurrency", Schemas.str(cfg, "currency", "USD")); + String availability = Schemas.str(cfg, "availability"); + if (availability != null) { + offer.put("availability", + availability.startsWith("http") ? availability : "https://schema.org/" + availability); + } + offer.put("url", sc.canonical()); + product.put("offers", offer); + } + return List.of(product); + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/RobotsTxtEndpoint.java b/plugins/discoverability/src/main/java/mx/quest/discover/RobotsTxtEndpoint.java new file mode 100644 index 0000000..3c250e4 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/RobotsTxtEndpoint.java @@ -0,0 +1,393 @@ +package mx.quest.discover; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +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.PluginSettings; + +/** + * SEO+/GEO — serves a per-site {@code /robots.txt}. The kernel deliberately does not own this + * route (an {@code EndpointContributor} route has exactly one owner, and a kernel handler reading a plugin's + * config would hard-code a plugin id into the core); the discoverability plugin owns it because the two things + * a rich {@code robots.txt} needs are already the plugin's: the {@code Sitemap:} line points at the plugin's own + * {@code /sitemap.xml} (and is emitted only when that surface is enabled, so it never points at a {@code 404}), + * and the AI/LLM-crawler policy is a GEO concern that sits beside {@code llms.txt}. + * + *

The body is an explicit named AI/LLM-crawler group (always emitted, so the AI posture is stated + * rather than merely implied by the wildcard), then a general {@code User-agent: *} group (allow-all, plus any + * tenant {@code robots.extra-disallow} paths), followed by the {@code Sitemap:} line. On the allow posture the + * AI group mirrors the general group's exclusions (a most-specific match wins in robots.txt, so a bare + * {@code Allow: /} would let those agents bypass the tenant's own Disallow paths); on opt-out it is a clean + * {@code Disallow: /}. The AI posture is per-tenant ({@code robots.ai-policy}: {@code allow}/{@code disallow}/ + * {@code inherit}) falling back to the app-level default ({@code robots.ai-default}, GEO-friendly {@code allow}). + * {@code robots.custom} is a full-body escape hatch that replaces the generated output verbatim. + * + *

An install without this plugin serves no {@code /robots.txt} at all, which crawlers treat as + * allow-all — functionally identical to the old permissive kernel default. + */ +public class RobotsTxtEndpoint implements EndpointContributor { + + /** + * AI/LLM crawler user-agents grouped under one {@code Disallow: /} when a site opts out of AI crawling. + * These are training/answer-engine agents kept distinct from the classic search crawlers (e.g. + * {@code Google-Extended} ≠ {@code Googlebot}, {@code Applebot-Extended} ≠ {@code Applebot}), so opting out + * of AI never deindexes the site from web search. + * + *

This list goes stale, and it fails silently when it does. Operators publish, rename and retire + * agent names on their own schedule; an agent missing from this list is simply not covered by an + * opt-out, and nothing anywhere reports that — the site owner believes they opted out and did not. That is + * not hypothetical: {@code Claude-User} and {@code Claude-SearchBot} were absent from the shipped 1.3.0 list + * while {@code ClaudeBot} was present, so a site set to {@code disallow} was still reachable by two of the + * three Anthropic agents. + * + *

Because a compile-time constant cannot be corrected without a plugin release, the effective list is + * this constant plus the app-level {@code robots.ai-agents-extra} setting + * ({@link DiscoverabilityProperties.Robots#getAiAgentsExtra()}) — so an operator can cover a newly announced + * agent the same day it is announced. See {@link #aiAgents()}. + * + *

Each agent is also assigned an {@link AiClass}, so a site can decline training while staying + * citable by answer engines — see {@link #AI_CLASSES}. + */ + static final List AI_CRAWLERS = List.of( + "GPTBot", "OAI-SearchBot", "ChatGPT-User", // OpenAI: training / retrieval / user-triggered + "ClaudeBot", "Claude-SearchBot", "Claude-User", // Anthropic: training / retrieval / user-triggered + "anthropic-ai", "Claude-Web", // Anthropic legacy names, kept: harmless if retired + "Google-Extended", // Google (Gemini training; NOT Googlebot) + "PerplexityBot", "Perplexity-User", // Perplexity: retrieval / user-triggered + "CCBot", // Common Crawl (feeds many LLMs) + "Bytespider", // ByteDance + "Amazonbot", // Amazon + "Applebot-Extended", // Apple (AI training opt-out; NOT Applebot) + "Meta-ExternalAgent", "FacebookBot", // Meta + "cohere-ai", "Diffbot", "Omgilibot", "Timpibot", "YouBot"); + + /** + * What an AI agent is for. The three roles the operators themselves distinguish, and the reason a + * single AI switch was not enough: they carry opposite consequences for a site. + */ + enum AiClass { + + /** Collecting text to train a model. Declining costs the site nothing it can see. */ + TRAINING("training"), + + /** Building an index an answer engine cites from. Declining removes the site from those answers. */ + RETRIEVAL("retrieval"), + + /** Fetching one page because a person asked about it. Declining breaks a visit somebody initiated. */ + USER("user"); + + private final String key; + + AiClass(String key) { + this.key = key; + } + + /** The token used in setting keys and in operator-supplied {@code class=Agent} entries. */ + String key() { + return key; + } + + static AiClass of(String token) { + for (AiClass value : values()) { + if (value.key.equalsIgnoreCase(token)) { + return value; + } + } + return null; + } + } + + /** + * Which class each built-in agent belongs to. + * + *

How these were assigned, and where the uncertainty is

+ * The triads are the operators' own published distinction and are not in doubt: OpenAI's + * {@code GPTBot}/{@code OAI-SearchBot}/{@code ChatGPT-User}, Anthropic's + * {@code ClaudeBot}/{@code Claude-SearchBot}/{@code Claude-User}, Perplexity's + * {@code PerplexityBot}/{@code Perplexity-User}. So are the training-only opt-out agents that exist + * precisely to be separable from their search siblings — {@code Google-Extended} (not {@code Googlebot}), + * {@code Applebot-Extended} (not {@code Applebot}). + * + *

The rest are a best-effort reading of each operator's own description, and some genuinely serve more + * than one purpose. An agent whose role is ambiguous is placed in {@link AiClass#TRAINING}, because + * that is the class a site opting out is most likely to mean, and a misplaced agent should fail toward + * honouring the site's stated intent rather than around it. + * + *

An agent absent from this map is governed by the site's overall {@code robots.ai-policy} — the + * behaviour every site had before classes existed, so an operator-added name keeps working unchanged. + */ + static final Map AI_CLASSES = Map.ofEntries( + Map.entry("GPTBot", AiClass.TRAINING), + Map.entry("OAI-SearchBot", AiClass.RETRIEVAL), + Map.entry("ChatGPT-User", AiClass.USER), + Map.entry("ClaudeBot", AiClass.TRAINING), + Map.entry("Claude-SearchBot", AiClass.RETRIEVAL), + Map.entry("Claude-User", AiClass.USER), + Map.entry("anthropic-ai", AiClass.TRAINING), + Map.entry("Claude-Web", AiClass.TRAINING), + Map.entry("Google-Extended", AiClass.TRAINING), + Map.entry("PerplexityBot", AiClass.RETRIEVAL), + Map.entry("Perplexity-User", AiClass.USER), + Map.entry("CCBot", AiClass.TRAINING), + Map.entry("Bytespider", AiClass.TRAINING), + Map.entry("Amazonbot", AiClass.TRAINING), + Map.entry("Applebot-Extended", AiClass.TRAINING), + Map.entry("Meta-ExternalAgent", AiClass.TRAINING), + Map.entry("FacebookBot", AiClass.TRAINING), + Map.entry("cohere-ai", AiClass.TRAINING), + Map.entry("Diffbot", AiClass.TRAINING), + Map.entry("Omgilibot", AiClass.TRAINING), + Map.entry("Timpibot", AiClass.TRAINING), + Map.entry("YouBot", AiClass.RETRIEVAL)); + + /** + * One AI agent as it will be emitted: its name, and the class governing it ({@code null} = the site's + * overall policy). + * + *

Name and class together, rather than a name list beside a shared lookup map, because + * {@code /robots.txt} is a public route served on many threads at once: a map rebuilt per request would + * let one thread read it mid-rebuild and emit an agent under a policy the operator never chose. There is + * no shared mutable state here at all — the classification is derived per call and thrown away. + */ + record Agent(String name, AiClass declaredClass) { + } + + private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(RobotsTxtEndpoint.class); + + private final PluginSettings settings; + private final DiscoverabilityProperties properties; + + public RobotsTxtEndpoint(PluginSettings settings, DiscoverabilityProperties properties) { + this.settings = settings; + this.properties = properties; + } + + @Override + public String key() { + return "discoverability/robots"; + } + + @Override + public List routes() { + // Not indexable, not in sitemap, cacheable (content is per-host stable). + return List.of(new Route("GET", "/robots.txt", Realm.TENANT, new SurfacePosture(false, false, true))); + } + + @Override + public RouteResponse handle(RouteRequest req) { + Map cfg = settings.site(req.site().id()).values(); + + // Full-body override — replaces the generated output entirely. + String custom = SiteConfig.str(cfg, "robots.custom", ""); + if (!custom.isBlank()) { + return RouteResponse.text(200, ensureTrailingNewline(custom)); + } + + String base = PageUrls.base(req.site(), req); + StringBuilder body = new StringBuilder(256); + List extra = extraDisallow(cfg); + + // Named AI/LLM-crawler group(s), ALWAYS emitted so the crawl posture is EXPLICIT rather than implied by + // the wildcard (a GEO signal). On opt-out a group is a clean Disallow: /. On allow it MIRRORS the + // general group (Allow: / + the same tenant Disallow paths) — a most-specific match wins in robots.txt, + // so an explicit Allow: / with no exclusions would otherwise let these agents ignore the site's own + // extra Disallows. + // + // ONE group when every class resolves the same way — which is every site that has not set a per-class + // override, so their robots.txt is byte-identical to before classes existed. Splitting a site that made + // no such choice into three identical groups would churn every crawler's copy to say the same thing. + appendAiGroups(body, cfg, extra); + + // The general group: allow-all, plus any tenant-declared extra Disallow paths. + body.append("User-agent: *\n"); + appendAllowWithExclusions(body, extra); + + // Sitemap reference — only when the sitemap surface is actually served (matches SitemapEndpoint's gate). + if (!base.isBlank() && SiteConfig.bool(cfg, "sitemap.enabled", true)) { + body.append("\nSitemap: ").append(base).append("/sitemap.xml\n"); + } + + return RouteResponse.text(200, body.toString()); + } + + + /** + * Writes the AI-crawler group(s): one per distinct policy across the three classes. + * + *

A site that has expressed no per-class preference gets exactly the single group it always got — + * identical bytes, identical agent order. Only a site that actually distinguishes the classes pays the + * extra groups. + */ + private void appendAiGroups(StringBuilder body, Map cfg, List extra) { + boolean training = aiDisallowed(cfg, AiClass.TRAINING); + boolean retrieval = aiDisallowed(cfg, AiClass.RETRIEVAL); + boolean user = aiDisallowed(cfg, AiClass.USER); + List agents = aiAgentsClassified(); + + if (training == retrieval && retrieval == user) { + appendAiGroup(body, agents.stream().map(Agent::name).toList(), training, extra); + return; + } + // Split. Unclassified agents (operator additions with no class= prefix) follow the site's overall + // policy, exactly as they did before classes existed — inventing a class for a name we do not + // recognise would silently apply a policy the operator never chose. + for (AiClass aiClass : AiClass.values()) { + List ofClass = agents.stream() + .filter(a -> classOf(a) == aiClass).map(Agent::name).toList(); + if (!ofClass.isEmpty()) { + appendAiGroup(body, ofClass, aiDisallowed(cfg, aiClass), extra); + } + } + List unclassified = agents.stream() + .filter(a -> classOf(a) == null).map(Agent::name).toList(); + if (!unclassified.isEmpty()) { + appendAiGroup(body, unclassified, aiDisallowed(cfg), extra); + } + } + + /** One {@code User-agent:} block: the names, then either {@code Disallow: /} or the mirrored allow. */ + private static void appendAiGroup(StringBuilder body, List agents, boolean disallowed, + List extra) { + for (String agent : agents) { + body.append("User-agent: ").append(agent).append('\n'); + } + if (disallowed) { + body.append("Disallow: /\n\n"); + } else { + appendAllowWithExclusions(body, extra); + body.append('\n'); + } + } + + /** The class of {@code agent} — its declared {@code class=} prefix if any, else the built-in map. */ + private static AiClass classOf(Agent agent) { + return agent.declaredClass() != null ? agent.declaredClass() : AI_CLASSES.get(agent.name()); + } + + /** + * Whether {@code aiClass} is disallowed for this site: its own override if set, else the site's overall + * {@code robots.ai-policy}, else the app-level default. + * + *

The per-class key is {@code robots.ai-training} / {@code -retrieval} / {@code -user} — deliberately + * NOT {@code robots.ai-policy.training}, which would make one key both a scalar and a map prefix and is + * the kind of shape that parses today and breaks the first time the config is read as a tree. + */ + private boolean aiDisallowed(Map cfg, AiClass aiClass) { + String policy = SiteConfig.str(cfg, "robots.ai-" + aiClass.key(), "inherit").trim(); + if (policy.equalsIgnoreCase("allow")) { + return false; + } + if (policy.equalsIgnoreCase("disallow")) { + return true; + } + return aiDisallowed(cfg); // inherit → the site's overall AI policy + } + + /** + * The built-in {@link #AI_CRAWLERS} plus any operator-added names from {@code robots.ai-agents-extra}, + * de-duplicated case-insensitively and sanitised. + * + *

Sanitisation is not cosmetic: an operator-supplied value lands in a {@code User-agent:} line, so a name + * containing CR/LF would let one setting inject arbitrary robots directives into every tenant's file — the + * same injection this class already closes for tenant {@code extra-disallow} paths. Whitespace and colons are + * stripped for the same reason (a colon would forge a second directive on one line). + * + *

Order is stable: built-ins first in declaration order, then operator additions in the order given, so + * the emitted file diffs cleanly between restarts. + */ + List aiAgents() { + return aiAgentsClassified().stream().map(Agent::name).toList(); + } + + /** As {@link #aiAgents()}, but each name paired with the class its entry declared (if any). */ + List aiAgentsClassified() { + List agents = new ArrayList<>(); + Set seen = new HashSet<>(); + for (String a : AI_CRAWLERS) { + agents.add(new Agent(a, null)); + seen.add(a.toLowerCase(Locale.ROOT)); + } + for (String raw : properties.getRobots().getAiAgentsExtra()) { + if (raw == null) { + continue; + } + // An entry may declare which class the agent belongs to: `training=SomeNewBot`. Without it the + // agent follows the site's overall AI policy, which is what every operator addition did before + // classes existed — so nothing already configured changes meaning. + String value = raw; + AiClass declared = null; + int eq = value.indexOf('='); + if (eq > 0) { + String token = value.substring(0, eq).trim(); + declared = AiClass.of(token); + // A misspelt class is reported and the AGENT is still honoured, unclassified. Folding the bad + // prefix into the name instead would produce a user-agent token that matches nothing, and the + // operator would believe they had covered an agent they had not — the exact silent failure + // this whole list exists to warn about. + if (declared == null) { + log.warn("robots.ai-agents-extra entry '{}' names an unknown AI class '{}' — the agent is " + + "still listed, but it follows the site's overall AI policy. Valid classes: {}.", + raw, token, java.util.Arrays.stream(AiClass.values()).map(AiClass::key).toList()); + } + value = value.substring(eq + 1); + } + String clean = value.replaceAll("[\\r\\n:=\\s]", "").trim(); + if (!clean.isEmpty() && seen.add(clean.toLowerCase(Locale.ROOT))) { + agents.add(new Agent(clean, declared)); + } + } + return List.copyOf(agents); + } + + /** True when this site opts out of AI/LLM crawlers: per-tenant {@code robots.ai-policy}, else the app default. */ + private boolean aiDisallowed(Map cfg) { + String policy = SiteConfig.str(cfg, "robots.ai-policy", "inherit").trim(); + if (policy.equalsIgnoreCase("allow")) { + return false; + } + if (policy.equalsIgnoreCase("disallow")) { + return true; + } + return "disallow".equalsIgnoreCase(properties.getRobots().getAiDefault()); // inherit → app-level default + } + + /** Writes {@code Allow: /} followed by one {@code Disallow:} line per tenant exclusion path. */ + private static void appendAllowWithExclusions(StringBuilder body, List extra) { + body.append("Allow: /\n"); + for (String path : extra) { + body.append("Disallow: ").append(path).append('\n'); + } + } + + /** Tenant extra Disallow paths, each normalized to start with {@code /} and stripped of CR/LF. */ + private static List extraDisallow(Map cfg) { + List paths = new ArrayList<>(); + for (String p : SiteConfig.list(cfg, "robots.extra-disallow")) { + // Strip CR/LF so one list entry can never inject extra robots lines/directives. + String clean = p.replaceAll("[\\r\\n]", "").trim(); + if (!clean.isEmpty()) { + paths.add(clean.startsWith("/") ? clean : "/" + clean); + } + } + return paths; + } + + private static String ensureTrailingNewline(String s) { + return s.endsWith("\n") ? s : s + "\n"; + } + + @Override + public Capabilities capabilities() { + return Capabilities.of("endpoint.tenant", "endpoint.robots"); + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/SchemaContext.java b/plugins/discoverability/src/main/java/mx/quest/discover/SchemaContext.java new file mode 100644 index 0000000..713bdde --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/SchemaContext.java @@ -0,0 +1,27 @@ +package mx.quest.discover; + +import java.util.Locale; +import java.util.Map; + +/** + * The immutable inputs a {@link SchemaType} needs beyond the {@link mx.quest.runway.spi.model.HeadContext}: the + * resolved site {@code base} and this page's {@code path}/{@code canonical}, whether it is a homepage, whether + * the site declares an Organization, the shared {@code @id}s (so a typed node cross-references the + * {@code WebPage}/{@code Organization} by reference rather than redefining them), the current {@code locale}, + * and the matched per-page config subtree parsed from {@code content.schema}. + * + * @param base the site base URL (no trailing slash) + * @param canonical this page's absolute canonical URL + * @param path this page's path relative to base (starts with {@code /}) + * @param home whether this page is a homepage + * @param hasOrg whether the site has a configured Organization (so {@code publisher}/{@code brand} refs apply) + * @param websiteId the {@code @id} of the graph's {@code WebSite} node + * @param webpageId the {@code @id} of the graph's {@code WebPage} node (for {@code mainEntityOfPage}/{@code isPartOf}) + * @param organizationId the {@code @id} of the graph's {@code Organization} node ({@code null}/unused when absent) + * @param pageConfig the matched {@code content.schema} entry (its {@code type} + type-specific fields) + * @param locale the resolved request locale + */ +record SchemaContext(String base, String canonical, String path, boolean home, boolean hasOrg, + String websiteId, String webpageId, String organizationId, + Map pageConfig, Locale locale) { +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/SchemaType.java b/plugins/discoverability/src/main/java/mx/quest/discover/SchemaType.java new file mode 100644 index 0000000..94e7118 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/SchemaType.java @@ -0,0 +1,75 @@ +package mx.quest.discover; + +import java.util.List; +import java.util.Map; +import mx.quest.runway.spi.model.HeadContext; + +/** + * A plugin-internal content type that maps a tenant-declared page/section type (e.g. {@code FAQPage}, + * {@code Product}) to schema.org JSON-LD {@code @graph} node(s). This is the extension seam behind item 5's + * type-aware structured data: {@link StructuredDataHead} holds a registry of these keyed by {@link #key()} and, + * for a page whose path matches a {@code content.schema} entry, appends {@link #nodes(HeadContext, SchemaContext)} + * to the graph — with zero type-aware branching in the contributor itself (capability/registry dispatch, per the + * host's capability-driven-SPI principle). + * + *

Implementations are pure and stateless: they read the immutable {@link HeadContext} and the matched + * per-page config carried by {@link SchemaContext}, and return plain node maps that reference the shared + * {@code #webpage}/{@code #organization} entities by {@code @id}. Content values are tenant-owned (they + * come from the config); the plugin owns only the typing mechanism. + */ +interface SchemaType { + + /** The type token a tenant declares in {@code content.schema} (e.g. {@code "FAQPage"}); the registry key. */ + String key(); + + /** + * The schema.org node(s) for this typed page, or an empty list when the config has nothing to emit. + * + * @param ctx the immutable head context (site, page, locale, canonical) + * @param sc the resolved schema context (base, path, shared {@code @id}s, the matched per-page config) + */ + List> nodes(HeadContext ctx, SchemaContext sc); + + /** + * Whether a block declaring {@code token} (one of the tokens this type is registered under) describes the page + * itself — its own {@code #webpage} node's {@code @type} — rather than adding a separate entity. Such a block + * replaces the site's Default page type for the pages it matches, and the head then calls + * {@link #describePage} instead of {@link #nodes}. Until 2.2.0 every block added a node, so a page declared + * {@code Article} carried two Article nodes when the site default was Article as well. + */ + default boolean describesPage(String token) { + return false; + } + + /** + * For a block that {@linkplain #describesPage describes the page}: adds this type's properties to the page's own + * node (whose {@code @type} the caller has already set to the declared token) and appends any separate nodes the + * type needs to {@code graph}. + * + * @param page the page's own node, mutable + * @param graph the graph being built, for nodes the page refers to by {@code @id} + */ + default void describePage(Map page, HeadContext ctx, SchemaContext sc, + List> graph) { + } + + /** + * What a block declaring {@code token} lacks to publish what it is for, or {@code null} when it lacks nothing: + * an {@code FAQPage} with no complete question, a list with no item that has a {@code url}. Such a block breaks + * nothing, so the page is still served; the settings form's Per-page types check and the page editor report it, + * since until 2.2.0 nobody saw it. A key that has a default (a product's name falls back to the page title) is + * not a gap. + */ + default Gap gap(String token, Map block) { + return null; + } + + /** + * A gap: the message code and its English text, whose {@code {0}} is the type token. + * + * @param code the message key, resolved in the operator's UI language + * @param fallback the English text + */ + record Gap(String code, String fallback) { + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/Schemas.java b/plugins/discoverability/src/main/java/mx/quest/discover/Schemas.java new file mode 100644 index 0000000..879e45c --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/Schemas.java @@ -0,0 +1,84 @@ +package mx.quest.discover; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * Null-safe readers over the parsed {@code content.schema} entry maps (nested {@code Map}/{@code List} produced + * by the YAML parser). Shared by the {@link SchemaType} implementations so each stays a small pure mapper. + */ +final class Schemas { + + private Schemas() { + } + + /** The string value of {@code key}, or {@code null} when absent/blank. */ + static String str(Map map, String key) { + Object v = map == null ? null : map.get(key); + if (v == null) { + return null; + } + String s = v.toString(); + return s.isBlank() ? null : s; + } + + /** The string value of {@code key}, or {@code def} when absent/blank. */ + static String str(Map map, String key, String def) { + String v = str(map, key); + return v == null ? def : v; + } + + /** The list-of-maps value of {@code key} (e.g. {@code faq}, {@code locations}, {@code people}); never null. */ + @SuppressWarnings("unchecked") + static List> maps(Map map, String key) { + Object v = map == null ? null : map.get(key); + if (!(v instanceof List list)) { + return List.of(); + } + List> out = new ArrayList<>(); + for (Object o : list) { + if (o instanceof Map m) { + out.add((Map) m); + } + } + return out; + } + + /** The list-of-strings value of {@code key} (a scalar is treated as a one-element list); never null. */ + static List strings(Map map, String key) { + Object v = map == null ? null : map.get(key); + if (v instanceof List list) { + List out = new ArrayList<>(); + for (Object o : list) { + if (o != null && !o.toString().isBlank()) { + out.add(o.toString()); + } + } + return out; + } + if (v instanceof String s && !s.isBlank()) { + return List.of(s); + } + return List.of(); + } + + /** + * {@code url} made absolute against the site {@code base} when it is root-relative ({@code /img/a.png}); any + * other value as given. JSON-LD URLs must be absolute; until 2.2.0 a root-relative image was emitted as written, + * which search engines reject. + */ + static String absolute(String url, String base) { + return url != null && url.startsWith("/") && !url.startsWith("//") && base != null && !base.isBlank() + ? base + url : url; + } + + /** {@link #absolute} applied to each URL of a list. */ + static List absolute(List urls, String base) { + List out = new ArrayList<>(urls.size()); + for (String url : urls) { + out.add(absolute(url, base)); + } + return out; + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/ServiceSchema.java b/plugins/discoverability/src/main/java/mx/quest/discover/ServiceSchema.java new file mode 100644 index 0000000..864f721 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/ServiceSchema.java @@ -0,0 +1,79 @@ +package mx.quest.discover; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import mx.quest.runway.spi.model.HeadContext; + +/** + * Emits a schema.org {@code Service} (or the entry's declared subtype, e.g. {@code ProfessionalService}) from a + * service page's {@code content.schema} entry: name/description/{@code serviceType}/{@code areaServed}/{@code offers}, + * with {@code provider}→Organization and {@code mainEntityOfPage}→WebPage. Name and description fall back to the + * page's title/description. An {@code offers:} list turns a pricing page's tiers into machine-readable + * {@code Offer}s (a recurring tier declares {@code unit:} → a {@code UnitPriceSpecification}, e.g. per month). + */ +final class ServiceSchema implements SchemaType { + + @Override + public String key() { + return "Service"; + } + + @Override + public List> nodes(HeadContext ctx, SchemaContext sc) { + Map cfg = sc.pageConfig(); + String name = Schemas.str(cfg, "name", ctx.page().title()); + if (name == null || name.isBlank()) { + return List.of(); // nothing substantive to say — don't emit a bare {@type: Service} node + } + String type = Schemas.str(cfg, "type", "Service"); // Service | ProfessionalService + Map service = Ld.node(type, null); + Ld.put(service, "name", name); + Ld.put(service, "description", Schemas.str(cfg, "description", ctx.page().description())); + Ld.put(service, "serviceType", Schemas.str(cfg, "serviceType")); + Ld.putList(service, "areaServed", Schemas.strings(cfg, "areaServed")); + List> offers = offers(cfg); + if (!offers.isEmpty()) { + service.put("offers", offers); + } + Ld.ref(service, "mainEntityOfPage", sc.webpageId()); + if (sc.hasOrg()) { + Ld.ref(service, "provider", sc.organizationId()); + } + return List.of(service); + } + + /** + * The {@code offers:} list mapped to schema.org {@code Offer} nodes. An offer needs a {@code price}; a + * {@code unit:} (e.g. {@code month}) makes it a recurring {@code UnitPriceSpecification}, else a flat + * {@code price}/{@code priceCurrency}. Currency defaults to USD. Offers without a price are skipped. + */ + private static List> offers(Map cfg) { + List> out = new ArrayList<>(); + for (Map o : Schemas.maps(cfg, "offers")) { + String price = Schemas.str(o, "price"); + if (price == null) { + continue; + } + String currency = Schemas.str(o, "currency", "USD"); + String unit = Schemas.str(o, "unit"); + Map offer = new LinkedHashMap<>(); + offer.put("@type", "Offer"); + Ld.put(offer, "name", Schemas.str(o, "name")); + if (unit != null) { + Map spec = new LinkedHashMap<>(); + spec.put("@type", "UnitPriceSpecification"); + spec.put("price", price); + spec.put("priceCurrency", currency); + spec.put("unitText", unit); + offer.put("priceSpecification", spec); + } else { + offer.put("price", price); + offer.put("priceCurrency", currency); + } + out.add(offer); + } + return out; + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/SimplePageType.java b/plugins/discoverability/src/main/java/mx/quest/discover/SimplePageType.java new file mode 100644 index 0000000..ffcc081 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/SimplePageType.java @@ -0,0 +1,43 @@ +package mx.quest.discover; + +import java.util.List; +import java.util.Map; +import mx.quest.runway.spi.model.HeadContext; + +/** + * A schema.org page type that only names what the page is — {@code AboutPage}, {@code ContactPage}, + * {@code WebPage} and the like — with no properties of its own. Declared in {@code content.schema}, it becomes the + * page's own {@code @type}, replacing the site's Default page type; so a site whose default is {@code Article} can + * say its contact page is a {@code ContactPage}, and a single page can go back to a plain {@code WebPage}. + */ +final class SimplePageType implements SchemaType { + + /** + * The page types this class serves, each registered as its own key. Not {@code ProfilePage} or {@code QAPage}: + * Google requires a {@code mainEntity} on both (the person; the one user-submitted question with its answers), + * which a type with no keys cannot give, so declaring them would only earn a Search Console error. Site-authored + * questions are an {@code FAQPage}. + */ + static final List KEYS = List.of("WebPage", "AboutPage", "ContactPage", "ItemPage", "SearchResultsPage"); + + private final String key; + + SimplePageType(String key) { + this.key = key; + } + + @Override + public String key() { + return key; + } + + @Override + public List> nodes(HeadContext ctx, SchemaContext sc) { + return List.of(); // describes the page itself; see describesPage + } + + @Override + public boolean describesPage(String token) { + return true; + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/SiteConfig.java b/plugins/discoverability/src/main/java/mx/quest/discover/SiteConfig.java new file mode 100644 index 0000000..7d06f07 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/SiteConfig.java @@ -0,0 +1,50 @@ +package mx.quest.discover; + +import java.util.List; +import java.util.Map; + +/** + * Null/absent-safe typed readers over this plugin's effective per-site settings map — the + * {@code SettingsView.values()} that {@code PluginSettings.site(siteId)} returns: the descriptor's + * {@code siteSettings} defaults overlaid by the values stored for the site, each already coerced by the host to + * its declared type (boolean→Boolean, int→Long, list→List<String>, enum/string/text→String). + * + *

Kept instead of the {@code SettingsView} accessors on purpose: these are the readers 1.x used, and their + * lenient rules for a hand-edited value (any string other than true/on/yes/1 reads as {@code false}; a blank value + * falls back) are part of what an unchanged site renders. The code fallbacks passed in equal the descriptor's + * declared defaults ({@code DescriptorDefaultsTest} proves the rendered surfaces do not change when the defaults + * are applied), so they matter only for a key the descriptor declares without a default. + */ +final class SiteConfig { + + private SiteConfig() { + } + + static boolean bool(Map cfg, String key, boolean def) { + Object v = cfg.get(key); + if (v instanceof Boolean b) { + return b; + } + if (v instanceof String s && !s.isBlank()) { + return s.equalsIgnoreCase("true") || s.equalsIgnoreCase("on") || s.equalsIgnoreCase("yes") || s.equals("1"); + } + return def; + } + + static String str(Map cfg, String key, String def) { + Object v = cfg.get(key); + return (v == null || v.toString().isBlank()) ? def : v.toString(); + } + + @SuppressWarnings("unchecked") + static List list(Map cfg, String key) { + Object v = cfg.get(key); + if (v instanceof List l) { + return l.stream().map(String::valueOf).map(String::trim).filter(s -> !s.isBlank()).toList(); + } + if (v instanceof String s && !s.isBlank()) { + return List.of(s.split("[,\\n]")).stream().map(String::trim).filter(x -> !x.isBlank()).toList(); + } + return List.of(); + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/SitemapEndpoint.java b/plugins/discoverability/src/main/java/mx/quest/discover/SitemapEndpoint.java new file mode 100644 index 0000000..d5a7085 --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/SitemapEndpoint.java @@ -0,0 +1,331 @@ +package mx.quest.discover; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import mx.quest.runway.spi.EndpointContributor; +import mx.quest.runway.spi.model.Alternate; +import mx.quest.runway.spi.model.Capabilities; +import mx.quest.runway.spi.model.CatalogEntry; +import mx.quest.runway.spi.model.LocalizedUrl; +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.ContentCatalogView; +import mx.quest.runway.spi.service.PluginSettings; + +/** + * SEO+ — serves a per-site {@code /sitemap.xml} enumerating the site's whole published content surface — + * kernel pages AND every content source's items (blog entries, any plugin content) through the host's + * {@link ContentCatalogView} — each {@code } carrying its {@code hreflang} alternates, {@code x-default}, and + * (when the item knows it) a {@code }. Every URL is one the host computed ({@link CatalogEntry#urls()}, + * {@link CatalogEntry#xDefaultPath()}) with the SAME code the head-injection alternates use, so the + * {@code } and the sitemap provably agree about every item's URLs; this class only prefixes the origin. + * + *

The catalog is already kernel-re-filtered (published-only, path-safe, reserved paths dropped) and + * metadata-only (no item's body is ever read serving this route — a sitemap request stays cheap no matter how + * many sources are installed). + * + *

The route is tenant-scoped and {@link SurfacePosture#discoverable()}. It honors the per-tenant + * {@code sitemap.enabled} flag — disabled ⇒ {@code 404}, so a tenant can opt out without uninstalling the + * plugin. + */ +public class SitemapEndpoint implements EndpointContributor { + + private final ContentCatalogView catalog; + private final PluginSettings settings; + + public SitemapEndpoint(ContentCatalogView catalog, PluginSettings settings) { + this.catalog = catalog; + this.settings = settings; + } + + @Override + public String key() { + return "discoverability/sitemap"; + } + + @Override + public List routes() { + // Indexable + in-sitemap + CACHEABLE: this endpoint manages its own caching (Last-Modified + + // no-cache revalidation below) — the dispatcher must not stamp no-store over it. + SurfacePosture posture = new SurfacePosture(true, true, true); + List routes = new java.util.ArrayList<>(MAX_SHARDS + 1); + routes.add(new Route("GET", SITEMAP_PATH, Realm.TENANT, posture)); + // Shard routes are declared STATICALLY, one per possible shard, because the host matches routes by + // exact path — there is no pattern form, deliberately (a pattern on a public tenant route is a + // path-safety surface nobody needs). A shard beyond what a site actually has answers 404; nothing + // links to it, so the only way to reach one is to type it. + for (int shard = 1; shard <= MAX_SHARDS; shard++) { + routes.add(new Route("GET", shardPath(shard), Realm.TENANT, posture)); + } + return List.copyOf(routes); + } + + /** The path of shard {@code n} (1-based), e.g. {@code /sitemap-3.xml}. */ + private static String shardPath(int n) { + return "/sitemap-" + n + ".xml"; + } + + /** The shard number a path names, or {@code 0} when it is the index itself / not a shard path. */ + private static int shardNumber(String path) { + if (path == null || !path.startsWith("/sitemap-") || !path.endsWith(".xml")) { + return 0; + } + try { + return Integer.parseInt(path.substring("/sitemap-".length(), path.length() - ".xml".length())); + } catch (NumberFormatException notAShard) { + return 0; + } + } + + @Override + public RouteResponse handle(RouteRequest req) { + Map cfg = settings.site(req.site().id()).values(); + if (!SiteConfig.bool(cfg, "sitemap.enabled", true)) { + // The route posture is cacheable (so the 200/304 carry their own validators), which means the + // dispatcher no longer stamps a fail-safe no-store — so this disabled-path 404 must forbid caching + // itself, or a heuristically-cacheable 404 could outlive the tenant re-enabling the surface. + return new RouteResponse(404, java.util.Map.of("Cache-Control", "no-store"), new byte[0]); + } + String base = PageUrls.base(req.site(), req); + List items = catalog.entries(req.site().id()); + + // Conditional GET: crawlers revalidate constantly; when nothing changed since their copy, answer 304 + // without re-serializing the document. The index and every shard share the site's newest instant — + // coarse (any edit revalidates all of them) but honest: a per-shard instant would claim a shard is + // unchanged while an item moved into or out of it. + java.time.Instant newest = CrawlConditional.lastModified(req.site().id(), items); + if (CrawlConditional.notModified(req, newest)) { + return CrawlConditional.notModifiedResponse(newest); + } + + Listing listing = listing(items, base); + int shard = shardNumber(req.path()); + if (shard > 0) { + return shardResponse(listing, shard, newest, req.site().id()); + } + if (listing.urls().size() <= SHARD_URLS) { + // The ordinary case, and the shape every small site keeps: one plain , no index, no extra + // round trip. Splitting a 40-URL site across an index would cost a crawler two fetches to learn + // nothing. + return ok(urlsetDocument(listing.urls(), 0, listing.urls().size()), newest); + } + return ok(indexDocument(listing, base, newest), newest); + } + + /** One sitemap entry: the URL to list, its alternates block (pre-rendered), and its {@code }. */ + private record Entry(String url, String alternates, String lastmod) { + } + + /** The site's whole sitemap surface, and what was left out of it. */ + private record Listing(List urls, int skippedNoindex, int skippedCanonical) { + } + + /** + * Every URL this site advertises, in a stable, content-derived order. + * + *

Why it is sorted

+ * {@link ContentCatalogView#entries} returns items grouped by source in an order it does not promise, which is stable + * within a boot and says nothing across boots or across the nodes of a cluster. Shard membership is + * derived from position in this list, so an unsorted list would let two nodes behind the same load + * balancer serve different content for the same shard number — a crawler alternating between them + * would see URLs appear and vanish with nothing in the response to explain it. Sorting by URL makes the + * boundaries a function of the content alone. + * + *

Metadata only: no item's body is read here, so this stays cheap however many sources are installed. + */ + private static Listing listing(List items, String base) { + List entries = new java.util.ArrayList<>(); + int skippedNoindex = 0; + int skippedCanonical = 0; + + for (CatalogEntry item : items) { + // A sitemap is a set of RECOMMENDATIONS to index. Listing a URL the same site tells robots not to + // index contradicts itself, so drop those here rather than in the host listing — the router, the search + // indexer and llms.txt all legitimately need the full published set. + if (item.ref().noindex()) { + skippedNoindex++; + continue; + } + // Likewise a page whose canonical points somewhere ELSE is, by its own declaration, not the + // authoritative URL. Emitting it would advertise a self-declared non-canonical address. (A canonical + // equal to the item's own URL is the normal self-referential case and stays.) + if (pointsElsewhere(item, base)) { + skippedCanonical++; + continue; + } + // The host's URLs — the same computation the head-injection alternates use (provable agreement): one + // per available locale, each a REAL routing address (never the canonical override). + List alternates = item.urls().stream().map(url -> url.alternate(base)).toList(); + String xDefault = base + item.xDefaultPath(); + String lastmod = item.ref().updatedAt() == null ? null : item.ref().updatedAt().toString(); + + StringBuilder links = new StringBuilder(128); + for (Alternate alt : alternates) { + links.append(" \n"); + } + links.append(" \n"); + String block = links.toString(); + + for (Alternate self : alternates) { + entries.add(new Entry(self.url(), block, lastmod)); + } + } + entries.sort(java.util.Comparator.comparing(Entry::url)); + return new Listing(List.copyOf(entries), skippedNoindex, skippedCanonical); + } + + /** One shard's {@code }, or {@code 404} for a shard this site does not have. */ + private RouteResponse shardResponse(Listing listing, int shard, java.time.Instant newest, String siteId) { + int total = listing.urls().size(); + if (total <= SHARD_URLS) { + // Not sharded at all: the shard paths exist as routes on every site, so they must say "no" rather + // than duplicate /sitemap.xml at a second address — two URLs serving one document is exactly the + // duplicate-content shape the rest of this plugin works to avoid. + return new RouteResponse(404, java.util.Map.of("Cache-Control", "no-store"), new byte[0]); + } + int from = (shard - 1) * SHARD_URLS; + if (from >= total) { + return new RouteResponse(404, java.util.Map.of("Cache-Control", "no-store"), new byte[0]); + } + int to = Math.min(from + SHARD_URLS, total); + warnIfTruncated(listing, siteId); + return ok(urlsetDocument(listing.urls(), from, to), newest); + } + + /** The {@code } naming each shard this site actually has. */ + private byte[] indexDocument(Listing listing, String base, java.time.Instant newest) { + int shards = Math.min(shardCount(listing.urls().size()), MAX_SHARDS); + StringBuilder xml = new StringBuilder(256 + shards * 128); + xml.append("\n") + .append("\n"); + for (int shard = 1; shard <= shards; shard++) { + xml.append(" \n") + .append(" ").append(xml(base + shardPath(shard))).append("\n"); + if (newest != null) { + xml.append(" ").append(newest).append("\n"); + } + xml.append(" \n"); + } + xml.append("\n"); + return xml.toString().getBytes(StandardCharsets.UTF_8); + } + + /** A {@code } over {@code urls[from, to)}. */ + private static byte[] urlsetDocument(List urls, int from, int to) { + StringBuilder xml = new StringBuilder(512 + (to - from) * 256); + xml.append("\n") + .append("\n"); + for (int i = from; i < to; i++) { + Entry entry = urls.get(i); + xml.append(" \n") + .append(" ").append(xml(entry.url())).append("\n"); + if (entry.lastmod() != null) { + xml.append(" ").append(entry.lastmod()).append("\n"); + } + xml.append(entry.alternates()).append(" \n"); + } + xml.append("\n"); + return xml.toString().getBytes(StandardCharsets.UTF_8); + } + + /** How many shards {@code total} URLs need. */ + private static int shardCount(int total) { + return (total + SHARD_URLS - 1) / SHARD_URLS; + } + + private static void warnIfTruncated(Listing listing, String siteId) { + int needed = shardCount(listing.urls().size()); + if (needed > MAX_SHARDS) { + // LOUD, and naming the tenant: a silently truncated sitemap is indistinguishable from a small site, + // so an operator would have no way to learn that content stopped being advertised. + log.warn("sitemap for site '{}' needs {} shards but only {} are served ({} URLs per shard) — " + + "{} URL(s) beyond {} are NOT advertised.", siteId, needed, MAX_SHARDS, SHARD_URLS, + listing.urls().size() - (long) MAX_SHARDS * SHARD_URLS, (long) MAX_SHARDS * SHARD_URLS); + } + } + + private static RouteResponse ok(byte[] body, java.time.Instant newest) { + return new RouteResponse(200, + CrawlConditional.cacheHeaders(newest, "application/xml; charset=utf-8"), body); + } + + /** The route the index (or, for a small site, the single {@code }) is served at. */ + private static final String SITEMAP_PATH = "/sitemap.xml"; + + /** + * URLs per shard, and how many shards are served — together the ceiling on what a site can advertise + * ({@value #SHARD_URLS} × {@value #MAX_SHARDS}). + * + *

Why 10,000 and not the spec's 50,000

+ * sitemaps.org allows 50,000 URLs and 50 MB per file, and a conformant consumer may reject a + * document that exceeds either — so an unbounded generator does not degrade gracefully on a large tenant, + * it loses the whole sitemap at once. But the spec cap is not the binding constraint here: this is a + * public, anonymous route, and a 50,000-URL document with {@code hreflang} alternates is tens of + * megabytes assembled in the heap, per concurrent request. A smaller shard keeps each response comfortably + * inside both the spec and a sane memory envelope, and costs a crawler only extra round trips it makes + * anyway. + * + *

{@value #MAX_SHARDS} shards is a real ceiling — {@value #SHARD_URLS} × {@value #MAX_SHARDS} + * URLs — because the host matches routes by exact path, so each shard is a declared route rather than a + * pattern. Well past any filesystem-backed tenant, four times the single-file limit it replaces, and it + * still WARNs loudly rather than truncating in silence. + */ + private static final int SHARD_URLS = 10_000; + private static final int MAX_SHARDS = 20; + + private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(SitemapEndpoint.class); + + /** + * Whether {@code item} declares a canonical URL pointing somewhere other than its own address — in which case + * the item asks not to be treated as the authoritative URL and has no business in the sitemap. + * + *

The override is read from {@link LocalizedUrl#canonical()} (the host hands it over as given; equal to the + * URL's own path when there is none). A root-relative override ({@code /about}) is resolved against + * {@code base} before comparing, as the kernel does for the {@code } canonical: it names an address on + * this site, so {@code /about} on the {@code /about} page is the self-referential case. (Until 2.0.0 the raw + * value was compared with the absolute URLs, so such a page was dropped from the sitemap.) + * + *

Compared against every locale's address and the {@code x-default}, because a localized variant is its own + * address: a canonical matching any of the item's own URLs is the ordinary self-referential case. + */ + private static boolean pointsElsewhere(CatalogEntry item, String base) { + String override = null; + for (LocalizedUrl url : item.urls()) { + if (!url.canonical().equals(url.path())) { + override = url.canonical(); + break; + } + } + if (override == null || override.isBlank()) { + return false; + } + String want = override.trim(); + if (want.startsWith("/")) { + want = base + want; + } + for (LocalizedUrl url : item.urls()) { + if (url.absolute(base).equals(want)) { + return false; + } + } + return !want.equals(base + item.xDefaultPath()); + } + + /** XML text/attribute escaping for URLs (chiefly {@code &} in query strings). */ + private static String xml(String value) { + return value.replace("&", "&").replace("<", "<").replace(">", ">") + .replace("\"", """).replace("'", "'"); + } + + @Override + public Capabilities capabilities() { + return Capabilities.of("endpoint.tenant", "endpoint.sitemap"); + } +} diff --git a/plugins/discoverability/src/main/java/mx/quest/discover/StructuredDataHead.java b/plugins/discoverability/src/main/java/mx/quest/discover/StructuredDataHead.java new file mode 100644 index 0000000..fae48ec --- /dev/null +++ b/plugins/discoverability/src/main/java/mx/quest/discover/StructuredDataHead.java @@ -0,0 +1,405 @@ +package mx.quest.discover; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import mx.quest.runway.spi.HeadContributor; +import mx.quest.runway.spi.model.Capabilities; +import mx.quest.runway.spi.model.HeadContext; +import mx.quest.runway.spi.service.PluginSettings; + +/** + * SEO+ and GEO — the single {@code HeadContributor} that injects one schema.org {@code @graph} of JSON-LD into + * every indexable page's {@code }. This is the layer the lean kernel deliberately leaves out: the kernel + * already emits canonical, hreflang, robots, Open Graph and Twitter cards, so this contributor adds only the + * structured-data {@code @graph} — never a tag the kernel already produces. + * + *

It emits one {@code & c"); + String out = Ld.script(List.of(node)); + assertFalse(out.contains(""), "raw < / > / & must not survive inside the script element"); + assertTrue(out.contains("\\u003c")); + assertTrue(out.contains("\\u003e")); + assertTrue(out.contains("\\u0026")); + } + + @Test + void putOmitsBlanksAndPutListCollapsesSingletons() { + Map node = Ld.node("Organization", null); + Ld.put(node, "name", " "); + Ld.put(node, "url", null); + assertFalse(node.containsKey("name")); + assertFalse(node.containsKey("url")); + Ld.putList(node, "sameAs", List.of("https://x.test")); + assertEquals("https://x.test", node.get("sameAs"), "a single sameAs is a scalar"); + Ld.putList(node, "sameAs", List.of("https://a", "https://b")); + assertEquals(List.of("https://a", "https://b"), node.get("sameAs"), "multiple is an array"); + } +} diff --git a/plugins/discoverability/src/test/java/mx/quest/discover/LlmsTxtEndpointTest.java b/plugins/discoverability/src/test/java/mx/quest/discover/LlmsTxtEndpointTest.java new file mode 100644 index 0000000..8d885cc --- /dev/null +++ b/plugins/discoverability/src/test/java/mx/quest/discover/LlmsTxtEndpointTest.java @@ -0,0 +1,250 @@ +package mx.quest.discover; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import mx.quest.runway.spi.model.ContentRef; +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.testkit.FakeContentCatalog; +import mx.quest.runway.spi.testkit.FakePluginSettings; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * /llms.txt: opt-in (geo.enabled) Markdown index of the host's published listing, in the site's default locale; + * disabled ⇒ 404. The listing (published only, safe paths, reserved paths dropped) is the host's; what this + * endpoint adds is the selection (noindex out), the labels, the summary and the absolute URLs. + */ +class LlmsTxtEndpointTest { + + private static final Locale EN = Locale.ENGLISH; + private static final Locale ES = Locale.forLanguageTag("es"); + + private final SiteView site = new SiteView("acme", "Acme", EN, List.of(EN, ES), "https://acme.test"); + private final FakePluginSettings settings = TestSettings.declared(); + private final FakeContentCatalog catalog = new FakeContentCatalog().site("acme"); + private final LlmsTxtEndpoint endpoint = new LlmsTxtEndpoint(catalog, settings); + + private static final ContentRef ABOUT = ContentRef.of("about", "/about", Map.of(), List.of(EN), + Map.of("en", "About"), Map.of("en", "Who we are."), "__site__/acme/about", null); + private static final ContentRef ENTRY = ContentRef.of("my-post", "/blog/my-post", Map.of(), List.of(EN), + Map.of("en", "My post"), Map.of("en", "A fine read."), "__plugin__/blog/entry", null); + /** Published in Spanish only, on an English-default site. */ + private static final ContentRef SPANISH_ONLY = ContentRef.of("solo", "/solo", Map.of("es", "/solo-es"), + List.of(ES), Map.of("es", "Sólo en español"), Map.of(), "__site__/acme/solo", null); + private static final ContentRef HIDDEN = new ContentRef("hidden", "/hidden", Map.of(), List.of(EN), + Map.of("en", "Hidden"), Map.of(), null, "__site__/acme/hidden", true, null, true, null, null, Map.of()); + + @BeforeEach + @org.junit.jupiter.api.AfterEach + void freshValidators() { + CrawlConditional.reset(); // also restores the system clock a test may have stepped + } + + private RouteRequest req(SiteView s, Map headers, String origin) { + return new RouteRequest(s, EN, "GET", "/llms.txt", Map.of(), headers, new byte[0], Map.of(), null, origin); + } + + private String body(RouteResponse r) { + assertEquals(200, r.status()); + return new String(r.body(), StandardCharsets.UTF_8); + } + + private void geo(Map extra) { + Map cfg = new java.util.HashMap<>(Map.of("geo.enabled", true)); + cfg.putAll(extra); + settings.site("acme", cfg); + } + + @Test + void servesMarkdownIndexWhenGeoEnabled() { + geo(Map.of("geo.summary", "We build things.")); + catalog.entry("acme", Entries.page(ABOUT, site)).entry("acme", Entries.of("blog", ENTRY, site)); + + RouteResponse r = endpoint.handle(req(site, Map.of(), "http://ignored.test")); + assertEquals("text/plain; charset=utf-8", r.headers().get("Content-Type")); + assertEquals(""" + # Acme + + > We build things. + + ## Pages + + - [About](https://acme.test/about): Who we are. + - [My post](https://acme.test/blog/my-post): A fine read. + """, body(r), "the exact 1.x document shape; plugin content is a first-class citizen"); + } + + @Test + void disabledReturns404WhenGeoOff() { + settings.site("acme", Map.of("geo.enabled", false)); + RouteResponse r = endpoint.handle(req(site, Map.of(), "")); + assertEquals(404, r.status()); + assertEquals("no-store", r.headers().get("Cache-Control")); + } + + @Test + void geoIsOffByDefault() { + assertEquals(404, endpoint.handle(req(site, Map.of(), "")).status(), "GEO is opt-in"); + } + + /** + * An intended change: an item that does not exist in the default locale is linked where it exists + * (its primary locale's real URL), never at the unprefixed default path that 1.x produced and the site 404s. + */ + @Test + void anItemMissingFromTheDefaultLocaleIsLinkedWhereItExists() { + geo(Map.of()); + catalog.entry("acme", Entries.page(SPANISH_ONLY, site)); + + String md = body(endpoint.handle(req(site, Map.of(), ""))); + assertTrue(md.contains("- [Sólo en español](https://acme.test/es/solo-es)"), md); + assertFalse(md.contains("https://acme.test/solo)"), "never the default path, which 404s: " + md); + } + + @Test + void noindexContentIsNotAdvertised() { + geo(Map.of()); + catalog.entry("acme", Entries.page(ABOUT, site)).entry("acme", Entries.page(HIDDEN, site)); + String md = body(endpoint.handle(req(site, Map.of(), ""))); + assertTrue(md.contains("[About]")); + assertFalse(md.contains("Hidden"), md); + } + + @Test + void labelsAreOneLineWithoutLinkMetacharactersAndFallBackToTheId() { + geo(Map.of("geo.summary", "Line one\nline two")); + ContentRef bracketed = ContentRef.of("faq", "/faq", Map.of(), List.of(EN), Map.of("en", "FAQ [updated]\nnow"), + Map.of("en", "Two\nlines"), "__site__/acme/faq", null); + ContentRef untitled = ContentRef.of("no-title", "/no-title", Map.of(), List.of(EN), Map.of(), Map.of(), + "__site__/acme/nt", null); + catalog.entry("acme", Entries.page(bracketed, site)).entry("acme", Entries.page(untitled, site)); + + String md = body(endpoint.handle(req(site, Map.of(), ""))); + assertTrue(md.contains("> Line one line two\n"), md); + assertTrue(md.contains("- [FAQ (updated) now](https://acme.test/faq): Two lines\n"), md); + assertTrue(md.contains("- [no-title](https://acme.test/no-title)\n"), md); + } + + @Test + void withoutABaseUrlTheTrustedOriginIsUsed() { + geo(Map.of()); + SiteView noBase = new SiteView("acme", "Acme", EN, List.of(EN, ES), null); + catalog.entry("acme", Entries.page(ABOUT, noBase)); + String md = body(endpoint.handle(req(noBase, Map.of("Host", "spoofed.test"), "http://acme.test:8080"))); + assertTrue(md.contains("(http://acme.test:8080/about)"), md); + assertFalse(md.contains("spoofed"), md); + } + + @Test + void conditionalGetRevalidatesWith304() { + geo(Map.of()); + catalog.entry("acme", Entries.page(ABOUT, site)); + RouteResponse fresh = endpoint.handle(req(site, Map.of(), "")); + String lastModified = fresh.headers().get("Last-Modified"); + assertEquals("no-cache", fresh.headers().get("Cache-Control")); + RouteResponse again = endpoint.handle(req(site, Map.of("if-modified-since", lastModified), "")); + assertEquals(304, again.status()); + assertEquals(0, again.body().length); + } + + @Test + void anUnknownSiteListsNothingButStillAnswers() { + geo(Map.of()); + SiteView ghost = new SiteView("ghost", "Ghost", EN, List.of(EN), "https://ghost.test"); + settings.site("ghost", Map.of("geo.enabled", true)); + assertEquals("# Ghost\n\n## Pages\n\n", body(endpoint.handle(req(ghost, Map.of(), "")))); + } + + // --- the validator folds what the document prints besides the items (2.1.0) ----------------------------- + + private RouteResponse revalidate(SiteView s, RouteResponse fresh) { + return endpoint.handle(req(s, Map.of("If-Modified-Since", fresh.headers().get("Last-Modified")), "")); + } + + /** Stepping the validator's clock past HTTP-date granularity, so an advance is observable. */ + private static void tick(int seconds) { + java.time.Instant at = java.time.Instant.now().plusSeconds(seconds); + CrawlConditional.clock = () -> at; + } + + @Test + void editingTheSummaryAdvancesLastModified() { + geo(Map.of("geo.summary", "We build things.")); + catalog.entry("acme", Entries.page(ABOUT, site)); + RouteResponse fresh = endpoint.handle(req(site, Map.of(), "")); + assertEquals(304, revalidate(site, fresh).status(), "unchanged: 304"); + + tick(5); + geo(Map.of("geo.summary", "We build better things.")); + RouteResponse after = revalidate(site, fresh); + assertEquals(200, after.status(), "a crawler holding the old summary refetches"); + assertTrue(body(after).contains("> We build better things.")); + } + + @Test + void renamingTheSiteAdvancesLastModified() { + geo(Map.of()); + catalog.entry("acme", Entries.page(ABOUT, site)); + RouteResponse fresh = endpoint.handle(req(site, Map.of(), "")); + + tick(5); + SiteView renamed = new SiteView("acme", "Acme Industries", EN, List.of(EN, ES), "https://acme.test"); + RouteResponse after = revalidate(renamed, fresh); + assertEquals(200, after.status(), "the H1 is the site name: a rename is a document change"); + assertTrue(body(after).startsWith("# Acme Industries\n")); + } + + @Test + void aNewBaseUrlAdvancesLastModified() { + geo(Map.of()); + catalog.entry("acme", Entries.page(ABOUT, site)); + RouteResponse fresh = endpoint.handle(req(site, Map.of(), "")); + + tick(5); + SiteView moved = new SiteView("acme", "Acme", EN, List.of(EN, ES), "https://www.acme.test"); + RouteResponse after = revalidate(moved, fresh); + assertEquals(200, after.status(), "every link starts with the base URL"); + assertTrue(body(after).contains("(https://www.acme.test/about)")); + } + + /** + * A host-less site reached under two names serves each its own links; the request origin is deliberately NOT + * folded, so each crawler's copy stays valid for the address it fetched and the validator does not advance on + * every alternate request. + */ + @Test + void theRequestOriginOfAHostlessSiteDoesNotMoveTheValidator() { + geo(Map.of()); + SiteView hostless = new SiteView("acme", "Acme", EN, List.of(EN, ES), null); + catalog.entry("acme", Entries.page(ABOUT, hostless)); + RouteResponse first = endpoint.handle(req(hostless, Map.of(), "http://one.test")); + tick(5); + RouteResponse second = endpoint.handle(req(hostless, Map.of(), "http://two.test")); + assertTrue(body(second).contains("(http://two.test/about)")); + assertEquals(first.headers().get("Last-Modified"), second.headers().get("Last-Modified")); + } + + @Test + void editingTheSummaryDoesNotMoveTheSitemapsValidator() { + geo(Map.of("geo.summary", "One.")); + catalog.entry("acme", Entries.page(ABOUT, site)); + SitemapEndpoint sitemap = new SitemapEndpoint(catalog, settings); + RouteRequest sitemapReq = new RouteRequest(site, EN, "GET", "/sitemap.xml", Map.of(), Map.of(), new byte[0], + Map.of(), null, ""); + String sitemapValidator = sitemap.handle(sitemapReq).headers().get("Last-Modified"); + endpoint.handle(req(site, Map.of(), "")); + tick(5); + geo(Map.of("geo.summary", "Two.")); + endpoint.handle(req(site, Map.of(), "")); + assertEquals(sitemapValidator, sitemap.handle(sitemapReq).headers().get("Last-Modified"), + "the sitemap does not print the summary"); + } +} diff --git a/plugins/discoverability/src/test/java/mx/quest/discover/PageTypeCheckTest.java b/plugins/discoverability/src/test/java/mx/quest/discover/PageTypeCheckTest.java new file mode 100644 index 0000000..9cfaf7c --- /dev/null +++ b/plugins/discoverability/src/test/java/mx/quest/discover/PageTypeCheckTest.java @@ -0,0 +1,111 @@ +package mx.quest.discover; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Locale; +import java.util.Map; +import mx.quest.runway.spi.testkit.FakePluginSettings; +import mx.quest.runway.spi.model.Finding; +import mx.quest.runway.spi.model.PageMeta; +import mx.quest.runway.spi.model.PageView; +import mx.quest.runway.spi.model.Severity; +import mx.quest.runway.spi.model.SiteView; +import org.junit.jupiter.api.Test; + +/** The page editor's structured-data line says what the page is and where that comes from. */ +class PageTypeCheckTest { + + private final FakePluginSettings config = TestSettings.declared(); + private final PageTypeCheck check = new PageTypeCheck(config, DiscoverabilityConfig.schemaTypes(), null); + + private static final Locale ES = Locale.forLanguageTag("es"); + + private List inspect(String path, Map cfg) { + return inspect(path, cfg, false, List.of(Locale.ENGLISH)); + } + + private List inspect(String path, Map cfg, boolean noindex, List languages) { + config.site("acme", cfg); + SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, languages, "https://acme.test"); + PageMeta page = new PageMeta(path.substring(1), "T", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, + noindex); + return check.inspect(new PageView(site, page, Locale.ENGLISH, "https://acme.test" + path, "

x

")); + } + + @Test + void theDefaultIsNamedAsTheSitesDefaultPageType() { + List f = inspect("/about", Map.of()); + assertEquals(1, f.size()); + assertEquals(Severity.INFO, f.get(0).severity()); + assertEquals("Structured data: this page is a WebPage, the site's Default page type.", f.get(0).message()); + } + + @Test + void aPerPageTypeNamesItsPatternAndWhatElseItAdds() { + List f = inspect("/pricing", Map.of("content.schema", + "/pri*:\n - type: FAQPage\n faq: []\n - type: Service\n name: S\n")); + assertEquals("Structured data: this page is a FAQPage, set by Per-page types (pattern /pri*). " + + "Per-page types also add: Service.", f.get(0).message()); + } + + @Test + void anUnknownTypeAndASecondPageTypeAreWarnings() { + List f = inspect("/x", Map.of("content.schema", + "/x:\n - type: AboutPage\n - type: ContactPage\n - type: Typo\n")); + assertEquals(3, f.size(), f.toString()); + assertTrue(f.stream().anyMatch(x -> x.severity() == Severity.WARNING && x.message().contains("Typo")), f.toString()); + assertTrue(f.stream().anyMatch(x -> x.severity() == Severity.WARNING && x.message().contains("ContactPage is ignored")), + f.toString()); + } + + /** The head emits nothing on a noindex page, before anything else; the line says so, whatever else is set. */ + @Test + void aNoindexPageIsSaidToCarryNoStructuredData() { + List f = inspect("/faq", Map.of("content.schema", "/faq:\n - type: FAQPage\n - type: Typo\n"), + true, List.of(Locale.ENGLISH)); + assertEquals(1, f.size(), f.toString()); + assertEquals(Severity.INFO, f.get(0).severity()); + assertEquals("Structured data: this page is excluded from search engines (noindex), so it carries no " + + "structured data.", f.get(0).message()); + assertEquals(1, inspect("/x", Map.of("jsonld.enabled", false), true, List.of(Locale.ENGLISH)).size()); + assertTrue(inspect("/x", Map.of("jsonld.enabled", false), true, List.of(Locale.ENGLISH)).get(0).message() + .contains("noindex"), "noindex is checked first, as the head does"); + } + + @Test + void anFaqPageWithNoCompleteQuestionIsAWarning() { + List f = inspect("/faq", Map.of("content.schema", + "/faq:\n type: FAQPage\n faq:\n - { question: Q, answer: A }\n")); + assertEquals(2, f.size(), f.toString()); + assertEquals(Severity.WARNING, f.get(1).severity()); + assertEquals(PageTypeCheck.CODE_GAP, f.get(1).code()); + assertEquals("FAQPage has no question with both q: and a:, so the page is an FAQPage with no questions.", + f.get(1).message()); + assertEquals(1, inspect("/faq", Map.of("content.schema", + "/faq:\n type: FAQPage\n faq:\n - { q: Q, a: A }\n")).size(), "a complete pair is enough"); + List list = inspect("/c", Map.of("content.schema", + "/c:\n - type: AboutPage\n - type: ItemList\n items:\n - { name: A }\n")); + assertTrue(list.stream().anyMatch(x -> x.severity() == Severity.WARNING + && x.message().equals("ItemList has no item with a url:, so no list is published.")), list.toString()); + } + + @Test + void aTranslatedPageIsToldTheDefaultLanguagesEntryDoesNotReachIt() { + Map cfg = Map.of("content.schema", "/faq:\n type: FAQPage\n faq:\n - { q: Q, a: A }\n"); + List f = inspect("/es/faq", cfg, false, List.of(Locale.ENGLISH, ES)); + assertEquals(2, f.size(), f.toString()); + assertEquals("Structured data: this page is a WebPage, the site's Default page type.", f.get(0).message()); + assertEquals(Severity.INFO, f.get(1).severity()); + assertEquals("Per-page types: /faq describes the default language's page, not this one; a page in another " + + "language is matched only by its own path. To describe this page, add /es/faq.", f.get(1).message()); + assertEquals(1, inspect("/faq", cfg, false, List.of(Locale.ENGLISH, ES)).size(), "the default language's page"); + } + + @Test + void switchedOffSaysSo() { + List f = inspect("/x", Map.of("jsonld.enabled", false)); + assertTrue(f.get(0).message().startsWith("Structured data is switched off"), f.toString()); + } +} diff --git a/plugins/discoverability/src/test/java/mx/quest/discover/PageTypesTest.java b/plugins/discoverability/src/test/java/mx/quest/discover/PageTypesTest.java new file mode 100644 index 0000000..76fdcbb --- /dev/null +++ b/plugins/discoverability/src/test/java/mx/quest/discover/PageTypesTest.java @@ -0,0 +1,176 @@ +package mx.quest.discover; + +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 java.util.List; +import java.util.Locale; +import java.util.Map; +import mx.quest.runway.spi.testkit.FakePluginSettings; +import mx.quest.runway.spi.model.HeadContext; +import mx.quest.runway.spi.model.PageMeta; +import mx.quest.runway.spi.model.SiteView; +import org.junit.jupiter.api.Test; + +/** + * A page type declared in Per-page types replaces the site's Default page type on the page's own node; + * every other type adds an entity. The head and the editor ask {@link PageTypes} the same question. + */ +class PageTypesTest { + + private static final Locale ES = Locale.forLanguageTag("es"); + private static final SiteView SITE = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH, ES), + "https://acme.test"); + private static final Map TYPES = DiscoverabilityConfig.schemaTypes(); + + private final FakePluginSettings config = TestSettings.declared(); + private final StructuredDataHead head = new StructuredDataHead(config, TYPES); + + private String render(String path, String title, Map cfg) { + config.site("acme", cfg); + PageMeta page = new PageMeta(path.substring(1), title, "d", List.of(Locale.ENGLISH), Locale.ENGLISH, true, + false); + String canonical = "https://acme.test" + path; + return head.render(new HeadContext(SITE, page, Locale.ENGLISH, canonical, canonical, List.of(), false, false)); + } + + private static int count(String haystack, String needle) { + int n = 0; + for (int i = haystack.indexOf(needle); i >= 0; i = haystack.indexOf(needle, i + needle.length())) { + n++; + } + return n; + } + + @Test + void withoutAPageTypeThePageHasTheSiteDefault() { + PageTypes.Description d = PageTypes.describe(Map.of(), "/about", TYPES); + assertEquals("WebPage", d.type()); + assertEquals(PageTypes.Source.DEFAULT, d.source()); + assertEquals("Article", PageTypes.describe(Map.of("jsonld.type", "Article"), "/x", TYPES).type()); + } + + @Test + void anArticleEntryIsThePagesOwnTypeNotASecondArticle() { + String out = render("/news/one", "One", Map.of("jsonld.type", "Article", + "content.schema", "/news/*:\n type: BlogPosting\n author: Ed\n")); + assertEquals(1, count(out, "\"@type\":\"BlogPosting\""), out); + assertEquals(0, count(out, "\"@type\":\"Article\""), "no second article beside the page: " + out); + assertTrue(out.contains("\"@id\":\"https://acme.test/news/one#webpage\""), out); + assertTrue(out.contains("\"headline\":\"One\"") && out.contains("\"name\":\"Ed\""), out); + assertFalse(out.contains("mainEntityOfPage"), "nothing points back at itself: " + out); + } + + @Test + void anFaqEntryMakesThePageAnFaqPageWithItsQuestions() { + String out = render("/faq", "FAQ", Map.of("content.schema", + "/faq:\n type: FAQPage\n faq:\n - { q: \"Why?\", a: \"Because.\" }\n")); + assertEquals(1, count(out, "\"@type\":\"FAQPage\""), out); + assertEquals(0, count(out, "\"@type\":\"WebPage\""), out); + assertTrue(out.contains("\"mainEntity\":[{\"@type\":\"Question\""), out); + } + + @Test + void aCollectionPageIsThePageAndItsListIsItsMainEntity() { + String out = render("/coffees", "Coffees", Map.of("content.schema", + "/coffees:\n type: CollectionPage\n items:\n - { name: A, url: /a }\n")); + assertTrue(out.contains("\"@type\":\"CollectionPage\",\"@id\":\"https://acme.test/coffees#webpage\""), out); + assertTrue(out.contains("\"mainEntity\":{\"@id\":\"https://acme.test/coffees#itemlist\"}"), out); + assertEquals(1, count(out, "\"@type\":\"ItemList\""), out); + // ItemList alone still only adds the list. + String list = render("/coffees", "Coffees", Map.of("content.schema", + "/coffees:\n type: ItemList\n items:\n - { name: A, url: /a }\n")); + assertTrue(list.contains("\"@type\":\"WebPage\""), list); + } + + @Test + void aSimplePageTypeOnlyNamesThePage() { + String out = render("/contact", "Contact", Map.of("jsonld.type", "Article", + "content.schema", "/contact:\n type: ContactPage\n")); + assertTrue(out.contains("\"@type\":\"ContactPage\""), out); + assertTrue(out.contains("\"name\":\"Contact\""), "a non-article page keeps its name: " + out); + assertEquals(0, count(out, "\"@type\":\"Article\""), out); + } + + @Test + void otherTypesStillAddEntitiesBesideThePageType() { + PageTypes.Description d = PageTypes.describe(Map.of("content.schema", + "/pricing:\n - type: FAQPage\n faq: []\n - type: Service\n name: S\n - type: Nope\n" + + " - type: AboutPage\n"), "/pricing", TYPES); + assertEquals("FAQPage", d.type()); + assertEquals(PageTypes.Source.SCHEMA, d.source()); + assertEquals("/pricing", d.pattern()); + assertEquals(List.of("Service"), d.addedTypes()); + assertEquals(List.of("Nope"), d.unknown()); + assertEquals(List.of("AboutPage"), d.extraPageTypes(), "a page has one type; the second is reported"); + } + + /** An entry's text is in one language, so a translated page is matched only by its own path. */ + @Test + void aPageBehindALanguagePrefixIsNotMatchedByTheDefaultLanguagesKey() { + Map cfg = Map.of("content.schema", "/faq:\n type: FAQPage\n faq:\n" + + " - { q: \"Do you ship abroad?\", a: \"Yes.\" }\n/blog/*:\n type: BlogPosting\n" + + "/coffees/*:\n type: Product\n name: Ethiopia Guji\n breadcrumb: { name: Coffees, url: /coffees }\n"); + PageTypes.Description d = PageTypes.describe(cfg, "/es/faq", TYPES); + assertEquals("WebPage", d.type()); + assertEquals(PageTypes.Source.DEFAULT, d.source()); + assertNull(d.pattern(), "/faq does not reach /es/faq"); + assertEquals("WebPage", PageTypes.describe(cfg, "/es/blog/post", TYPES).type()); + assertNull(PageTypes.entry(cfg, "/es/coffees/guji")); + + String faq = render("/es/faq", "Preguntas frecuentes", cfg); + assertFalse(faq.contains("FAQPage") || faq.contains("Do you ship abroad?"), "no English questions: " + faq); + String product = render("/es/coffees/guji", "Guji", cfg); + assertFalse(product.contains("Ethiopia Guji") || product.contains("\"Product\""), product); + assertFalse(product.contains("\"name\":\"Coffees\""), "no English breadcrumb parent: " + product); + // The default language's pages are unchanged. + assertTrue(render("/faq", "FAQ", cfg).contains("Do you ship abroad?")); + } + + @Test + void aKeyWrittenForTheTranslatedPathApplies() { + Map cfg = Map.of("content.schema", "/faq:\n type: FAQPage\n faq:\n" + + " - { q: \"Do you ship abroad?\", a: \"Yes.\" }\n/es/faq:\n type: FAQPage\n faq:\n" + + " - { q: \"¿Envían al extranjero?\", a: \"Sí.\" }\n/es/blog/*:\n type: BlogPosting\n"); + PageTypes.Description d = PageTypes.describe(cfg, "/es/faq", TYPES); + assertEquals("FAQPage", d.type()); + assertEquals("/es/faq", d.pattern()); + String out = render("/es/faq", "Preguntas frecuentes", cfg); + assertTrue(out.contains("¿Envían al extranjero?"), out); + assertFalse(out.contains("Do you ship abroad?"), out); + assertEquals("BlogPosting", PageTypes.describe(cfg, "/es/blog/hola", TYPES).type()); + // A catch-all reaches every language's page, as it always did. + assertEquals("AboutPage", PageTypes.describe(Map.of("content.schema", "/*:\n type: AboutPage\n"), + "/es/x", TYPES).type()); + } + + @Test + void theEditorIsToldWhichDefaultLanguageEntryDoesNotReachATranslatedPage() { + Map cfg = Map.of("content.schema", "/faq:\n type: FAQPage\n/blog/*:\n type: BlogPosting\n" + + "/:\n type: WebPage\n/team:\n type: AboutPage\n/es/team:\n type: AboutPage\n"); + assertEquals(new PageTypes.OtherLanguageEntry("/faq", "/es/faq"), PageTypes.otherLanguageEntry(cfg, "/es/faq", SITE)); + assertEquals(new PageTypes.OtherLanguageEntry("/blog/*", "/es/blog/*"), + PageTypes.otherLanguageEntry(cfg, "/es/blog/x", SITE)); + assertEquals(new PageTypes.OtherLanguageEntry("/", "/es"), PageTypes.otherLanguageEntry(cfg, "/es", SITE)); + assertNull(PageTypes.otherLanguageEntry(cfg, "/es/team", SITE), "it has its own key"); + assertNull(PageTypes.otherLanguageEntry(cfg, "/faq", SITE), "a default-language page has no prefix"); + assertNull(PageTypes.otherLanguageEntry(cfg, "/en/faq", SITE), "the default language is never a prefix"); + assertNull(PageTypes.otherLanguageEntry(cfg, "/fr/faq", SITE), "fr is not a language of this site"); + assertNull(PageTypes.otherLanguageEntry(cfg, "/es/acerca", SITE), "nothing matches /acerca either"); + Map catchAll = Map.of("content.schema", "/*:\n type: WebPage\n/es/*:\n type: WebPage\n" + + "/about:\n type: AboutPage\n"); + assertNull(PageTypes.otherLanguageEntry(catchAll, "/es/x", SITE), "/es/* is at least as specific as /*"); + assertEquals(new PageTypes.OtherLanguageEntry("/about", "/es/about"), + PageTypes.otherLanguageEntry(catchAll, "/es/about", SITE), "/es/* is less specific than /about"); + } + + @Test + void aBlockWithoutATypeIsNotReportedAsUnknown() { + PageTypes.Description d = PageTypes.describe(Map.of("content.schema", + "/p:\n - breadcrumb: { name: Shop, url: /shop }\n - type: Product\n name: P\n"), "/p", TYPES); + assertTrue(d.unknown().isEmpty(), d.unknown().toString()); + assertEquals(List.of("Product"), d.addedTypes()); + } +} diff --git a/plugins/discoverability/src/test/java/mx/quest/discover/RobotsTxtEndpointTest.java b/plugins/discoverability/src/test/java/mx/quest/discover/RobotsTxtEndpointTest.java new file mode 100644 index 0000000..31f9cd7 --- /dev/null +++ b/plugins/discoverability/src/test/java/mx/quest/discover/RobotsTxtEndpointTest.java @@ -0,0 +1,341 @@ +package mx.quest.discover; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Locale; +import java.util.Map; +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.service.PluginSettings; +import org.junit.jupiter.api.Test; + +/** + * The plugin-owned {@code /robots.txt}: a general allow-all group + the {@code Sitemap:} line, with a + * configurable AI/LLM-crawler policy (per-site {@code robots.ai-policy} over the app-level {@code robots.ai-default}), + * tenant extra Disallow paths, and a full-body custom override. + */ +class RobotsTxtEndpointTest { + + private static final Locale EN = Locale.ENGLISH; + private static final SiteView SITE = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test"); + + private static PluginSettings config(Map cfg) { + return TestSettings.declared().site("acme", cfg); + } + + private static DiscoverabilityProperties props(String aiDefault) { + DiscoverabilityProperties p = new DiscoverabilityProperties(); + p.getRobots().setAiDefault(aiDefault); + return p; + } + + private static RouteRequest req(SiteView site, Map headers) { + return req(site, headers, ""); + } + + /** A request as the kernel builds it: the trusted origin, no forwarded headers. */ + private static RouteRequest req(SiteView site, Map headers, String origin) { + return new RouteRequest(site, EN, "GET", "/robots.txt", Map.of(), headers, new byte[0], Map.of(), null, + origin); + } + + private static String bodyOf(Map cfg, String aiDefault, SiteView site, Map headers) { + return bodyOf(cfg, aiDefault, req(site, headers)); + } + + private static String bodyOf(Map cfg, String aiDefault, RouteRequest req) { + RouteResponse r = new RobotsTxtEndpoint(config(cfg), props(aiDefault)).handle(req); + assertEquals(200, r.status()); + return new String(r.body(), StandardCharsets.UTF_8); + } + + @Test + void defaultAllowsEveryoneAndPointsAtTheSitemap() { + String out = bodyOf(Map.of(), "allow", SITE, Map.of()); + assertTrue(out.contains("User-agent: *"), out); + assertTrue(out.contains("Allow: /"), out); + assertTrue(out.contains("Sitemap: https://acme.test/sitemap.xml"), out); + // The AI/LLM posture is stated EXPLICITLY: a named group is emitted even on allow, with Allow — not + // Disallow — so nothing is actually blocked. + assertTrue(out.contains("User-agent: GPTBot"), "explicit AI-crawler group even on allow: " + out); + assertFalse(out.contains("Disallow: /"), "allow posture disallows nothing: " + out); + } + + @Test + void perSiteDisallowEmitsAiCrawlerGroups() { + String out = bodyOf(Map.of("robots.ai-policy", "disallow"), "allow", SITE, Map.of()); + assertTrue(out.contains("User-agent: GPTBot"), out); + assertTrue(out.contains("User-agent: ClaudeBot"), out); + assertTrue(out.contains("User-agent: Google-Extended"), out); + assertTrue(out.contains("Disallow: /"), out); + assertTrue(out.contains("User-agent: *"), "classic crawlers are still allowed"); + } + + @Test + void inheritsAppLevelDisallowDefault() { + String out = bodyOf(Map.of(), "disallow", SITE, Map.of()); // policy defaults to inherit + assertTrue(out.contains("User-agent: GPTBot"), "inherit → app default disallow: " + out); + } + + @Test + void perSiteAllowOverridesAppLevelDisallowDefault() { + String out = bodyOf(Map.of("robots.ai-policy", "allow"), "disallow", SITE, Map.of()); + // Per-site allow wins over the app default: the named group is still present (explicit posture) but as + // Allow, never Disallow: /. + assertTrue(out.contains("User-agent: GPTBot"), out); + assertFalse(out.contains("Disallow: /"), "per-site allow wins over the app default: " + out); + } + + @Test + void allowedAiGroupMirrorsTenantExtraDisallows() { + // On the allow posture the named AI group MIRRORS the general group's exclusions, so a most-specific + // robots.txt match cannot let AI crawlers bypass the tenant's own Disallow paths. /private thus appears + // twice: once under the AI group, once under the * group. + String out = bodyOf(Map.of("robots.extra-disallow", List.of("/private")), "allow", SITE, Map.of()); + long count = out.lines().filter(l -> l.equals("Disallow: /private")).count(); + assertEquals(2, count, "AI group mirrors the tenant exclusion: " + out); + } + + @Test + void omitsSitemapLineWhenSitemapDisabled() { + String out = bodyOf(Map.of("sitemap.enabled", false), "allow", SITE, Map.of()); + assertFalse(out.contains("Sitemap:"), out); + assertTrue(out.contains("Allow: /"), "still serves the allow group"); + } + + @Test + void emitsTenantExtraDisallowPathsNormalized() { + String out = bodyOf(Map.of("robots.extra-disallow", List.of("/private", "search")), "allow", SITE, Map.of()); + assertTrue(out.contains("Disallow: /private"), out); + assertTrue(out.contains("Disallow: /search"), "a bare path is normalized to /search: " + out); + } + + @Test + void customBodyReplacesEverythingVerbatim() { + String out = bodyOf(Map.of("robots.custom", "User-agent: *\nDisallow: /"), "allow", SITE, Map.of()); + assertEquals("User-agent: *\nDisallow: /\n", out); + assertFalse(out.contains("Sitemap:"), "the custom body is verbatim — no generated additions"); + } + + @Test + void takesTheSitemapOriginFromTheTrustedRequestOriginWhenBaseUrlUnset() { + SiteView noBase = new SiteView("acme", "Acme", EN, List.of(EN), null); + String out = bodyOf(Map.of(), "allow", req(noBase, Map.of("Host", "acme.test"), "http://acme.test:8080")); + assertTrue(out.contains("Sitemap: http://acme.test:8080/sitemap.xml"), "the origin as the kernel gated it, " + + "scheme and port included — never a guessed https from the Host header: " + out); + } + + @Test + void theConfiguredBaseUrlWinsOverTheRequestOrigin() { + String out = bodyOf(Map.of(), "allow", req(SITE, Map.of(), "http://internal:8080")); + assertTrue(out.contains("Sitemap: https://acme.test/sitemap.xml"), out); + } + + @Test + void noBaseUrlAndNoOriginMeansNoSitemapLineRatherThanARelativeOne() { + SiteView noBase = new SiteView("acme", "Acme", EN, List.of(EN), null); + String out = bodyOf(Map.of(), "allow", req(noBase, Map.of("Host", "acme.test"), "")); + assertFalse(out.contains("Sitemap:"), "a Host header alone is no longer trusted: " + out); + } + + /** + * The exact regression the SEO/GEO compliance audit found in 1.3.0: {@code ClaudeBot} was listed but + * {@code Claude-User} and {@code Claude-SearchBot} were not, so a site set to {@code disallow} was still + * reachable by two of the three Anthropic agents — an opt-out the owner believed was complete and was not. + * + *

Asserted per-vendor across all three CLASSES the article distinguishes (training / live retrieval / + * user-triggered fetch), because the failure mode is one missing name, not a missing feature — a test that + * only checked "some AI agent is present" would have passed against the bug. + */ + @Test + void everyAgentClassIsCoveredForEachMajorVendor() { + String out = bodyOf(Map.of("robots.ai-policy", "disallow"), "allow", SITE, Map.of()); + for (String agent : List.of( + "GPTBot", "OAI-SearchBot", "ChatGPT-User", // OpenAI: train / retrieve / user + "ClaudeBot", "Claude-SearchBot", "Claude-User", // Anthropic: train / retrieve / user + "PerplexityBot", "Perplexity-User", // Perplexity: retrieve / user + "Google-Extended", "Applebot-Extended")) { // training opt-outs, NOT the search bots + assertTrue(out.contains("User-agent: " + agent + "\n"), "missing agent: " + agent); + } + // The training opt-out must never take the SEARCH crawler with it — that would deindex the site. + assertFalse(out.contains("User-agent: Googlebot\n"), "Googlebot must never be in the AI opt-out group"); + assertFalse(out.contains("User-agent: Applebot\n"), "Applebot must never be in the AI opt-out group"); + } + + /** + * The operator escape hatch: the built-in list is a compile-time constant that goes stale silently, so + * {@code robots.ai-agents-extra} must be able to cover a newly announced agent without a plugin release. + * + *

Also pins the injection guard. An operator-supplied name lands in a {@code User-agent:} line, so a value + * carrying CR/LF or a colon could forge extra robots directives into every tenant's file — the same class of + * hole already closed for tenant exclusion paths. + */ + @Test + void operatorAddedAgentsAreAppendedDedupedAndSanitised() { + DiscoverabilityProperties p = props("allow"); + p.getRobots().setAiAgentsExtra(List.of( + "BrandNewBot", // the point of the feature + "gptbot", // already built in, different case → must not duplicate + "Evil\nUser-agent: *\nDisallow: /", // injection attempt via CR/LF + " Spaced Bot ")); // whitespace stripped + RouteResponse r = new RobotsTxtEndpoint(config(Map.of("robots.ai-policy", "disallow")), p) + .handle(req(SITE, Map.of())); + String out = new String(r.body(), StandardCharsets.UTF_8); + + assertTrue(out.contains("User-agent: BrandNewBot\n"), "operator addition must be emitted"); + assertEquals(1, out.split("(?i)User-agent: GPTBot\n", -1).length - 1, "must not duplicate a built-in"); + assertTrue(out.contains("User-agent: SpacedBot\n"), "whitespace stripped: " + out); + // The injected directive must not survive as its own line. + assertFalse(out.contains("\nDisallow: /\nUser-agent: *"), "CR/LF injection must be neutralised"); + assertTrue(out.contains("User-agent: EvilUser-agent:*Disallow:/\n") + || out.contains("User-agent: EvilUser-agent"), + "the payload is flattened into one inert token: " + out); + } + + // ---- the three AI classes are separately governable ----------------------------------------------- + + /** The group a named agent falls in: the lines from its {@code User-agent:} to the next blank line. */ + private static String groupContaining(String robots, String agent) { + for (String group : robots.split("\n\n")) { + if (group.contains("User-agent: " + agent + "\n") || group.endsWith("User-agent: " + agent)) { + return group; + } + } + return ""; + } + + /** + * The case the split exists for: decline training, stay citable. + * + *

Before this a site had one AI switch, so the only way to refuse training was to refuse the answer + * engines too — which removes the site from generated answers, the opposite of what a site optimising for + * them wants. The three classes carry opposite consequences and now carry opposite settings. + */ + @Test + void aSiteCanDeclineTrainingWhileStayingCitable() { + String out = bodyOf(Map.of("robots.ai-training", "disallow", "robots.ai-retrieval", "allow"), + "allow", SITE, Map.of()); + + assertTrue(groupContaining(out, "GPTBot").contains("Disallow: /"), out); + assertTrue(groupContaining(out, "ClaudeBot").contains("Disallow: /"), out); + assertTrue(groupContaining(out, "OAI-SearchBot").contains("Allow: /"), out); + assertTrue(groupContaining(out, "Claude-SearchBot").contains("Allow: /"), out); + } + + /** A user-triggered fetch is its own decision: someone asked for this page. */ + @Test + void theUserTriggeredClassIsGovernedSeparately() { + String out = bodyOf(Map.of("robots.ai-policy", "disallow", "robots.ai-user", "allow"), + "allow", SITE, Map.of()); + + assertTrue(groupContaining(out, "ChatGPT-User").contains("Allow: /"), out); + assertTrue(groupContaining(out, "Claude-User").contains("Allow: /"), out); + assertTrue(groupContaining(out, "GPTBot").contains("Disallow: /"), "training still declined: " + out); + } + + /** + * A site that sets no per-class override gets exactly the file it got before classes existed. + * + *

Byte-for-byte, agent order included. Splitting a site that expressed no such preference into three + * identical groups would churn every crawler's copy of a file to say precisely the same thing. + */ + @Test + void aSiteWithNoPerClassOverrideGetsTheIdenticalSingleGroup() { + String withoutClasses = bodyOf(Map.of("robots.ai-policy", "disallow"), "allow", SITE, Map.of()); + String allInherit = bodyOf(Map.of("robots.ai-policy", "disallow", "robots.ai-training", "inherit", + "robots.ai-retrieval", "inherit", "robots.ai-user", "inherit"), "allow", SITE, Map.of()); + + assertEquals(withoutClasses, allInherit); + assertEquals(1, withoutClasses.split("Disallow: /\n", -1).length - 1, + "one AI group, not three: " + withoutClasses); + } + + /** Three overrides that happen to agree also collapse to one group — the test is the OUTPUT, not the keys. */ + @Test + void perClassOverridesThatAgreeStillCollapseToOneGroup() { + String out = bodyOf(Map.of("robots.ai-training", "disallow", "robots.ai-retrieval", "disallow", + "robots.ai-user", "disallow"), "allow", SITE, Map.of()); + + assertEquals(bodyOf(Map.of("robots.ai-policy", "disallow"), "allow", SITE, Map.of()), out); + } + + /** A per-class override beats the site policy; an unset class still inherits it. */ + @Test + void aClassOverrideBeatsTheSitePolicyAndAnUnsetClassInheritsIt() { + String out = bodyOf(Map.of("robots.ai-policy", "allow", "robots.ai-training", "disallow"), + "disallow", SITE, Map.of()); + + assertTrue(groupContaining(out, "GPTBot").contains("Disallow: /"), "the override wins: " + out); + assertTrue(groupContaining(out, "OAI-SearchBot").contains("Allow: /"), + "an unset class follows the SITE policy, not the app default: " + out); + } + + /** + * An operator-added agent with no declared class follows the site's overall policy. + * + *

Exactly what it did before classes existed. Guessing a class for a name the plugin does not recognise + * would apply a policy the operator never chose — and would do it silently. + */ + @Test + void anUnclassifiedOperatorAgentFollowsTheOverallPolicy() { + DiscoverabilityProperties p = props("allow"); + p.getRobots().setAiAgentsExtra(List.of("BrandNewBot")); + String out = new String(new RobotsTxtEndpoint( + config(Map.of("robots.ai-policy", "disallow", "robots.ai-user", "allow")), p) + .handle(req(SITE, Map.of())).body(), StandardCharsets.UTF_8); + + assertTrue(groupContaining(out, "BrandNewBot").contains("Disallow: /"), out); + assertTrue(groupContaining(out, "Claude-User").contains("Allow: /"), out); + } + + /** …and an operator can classify a newly-announced agent the day it is announced. */ + @Test + void anOperatorCanDeclareTheClassOfANewAgent() { + DiscoverabilityProperties p = props("allow"); + p.getRobots().setAiAgentsExtra(List.of("retrieval=BrandNewSearchBot")); + String out = new String(new RobotsTxtEndpoint( + config(Map.of("robots.ai-training", "disallow", "robots.ai-retrieval", "allow")), p) + .handle(req(SITE, Map.of())).body(), StandardCharsets.UTF_8); + + assertTrue(out.contains("User-agent: BrandNewSearchBot"), out); + assertTrue(groupContaining(out, "BrandNewSearchBot").contains("Allow: /"), + "declared retrieval, so it follows the retrieval policy: " + out); + assertFalse(out.contains("retrieval=BrandNewSearchBot"), "the prefix must not leak into the file"); + } + + /** + * A misspelt class still lists the agent, and the prefix is not an injection vector. + * + *

The alternative — folding the bad prefix into the name — yields a user-agent token that matches + * nothing, so the operator believes they covered an agent they did not. That is the silent failure the + * whole extra-agents list exists to prevent, so a typo is reported and the agent is honoured under the + * site's overall policy. + */ + @Test + void aMisspeltClassStillListsTheAgentAndCannotInject() { + DiscoverabilityProperties p = props("allow"); + p.getRobots().setAiAgentsExtra(List.of("nonsense=EvilBot", "x\nDisallow: /secret\nUser-agent: Y")); + String out = new String(new RobotsTxtEndpoint(config(Map.of()), p) + .handle(req(SITE, Map.of())).body(), StandardCharsets.UTF_8); + + assertTrue(out.contains("User-agent: EvilBot"), "the agent the operator named is listed: " + out); + assertFalse(out.contains("nonsense"), "the bad prefix must not become part of the name: " + out); + assertFalse(out.contains("Disallow: /secret"), "CR/LF injection stays closed: " + out); + } + + /** Every built-in agent has a class, or the split silently sends it to the catch-all group. */ + @Test + void everyBuiltInAgentIsClassified() { + for (String agent : RobotsTxtEndpoint.AI_CRAWLERS) { + assertTrue(RobotsTxtEndpoint.AI_CLASSES.containsKey(agent), + agent + " has no class — it would quietly fall under the overall policy instead"); + } + assertEquals(RobotsTxtEndpoint.AI_CRAWLERS.size(), RobotsTxtEndpoint.AI_CLASSES.size(), + "a class map entry naming an agent that is not in the list does nothing and will rot"); + } +} diff --git a/plugins/discoverability/src/test/java/mx/quest/discover/SchemaProblemsTest.java b/plugins/discoverability/src/test/java/mx/quest/discover/SchemaProblemsTest.java new file mode 100644 index 0000000..9cf10f0 --- /dev/null +++ b/plugins/discoverability/src/test/java/mx/quest/discover/SchemaProblemsTest.java @@ -0,0 +1,72 @@ +package mx.quest.discover; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Map; +import mx.quest.runway.spi.testkit.FakePluginSettings; +import org.junit.jupiter.api.Test; + +/** Mistakes in Per-page types never break a page, so the settings screen lists them instead. */ +class SchemaProblemsTest { + + private final FakePluginSettings config = TestSettings.declared(); + private final DiscoverAdminModel model = new DiscoverAdminModel(config, null); + + private List problems(String schema) { + config.site("acme", Map.of("content.schema", schema)); + return model.schemaProblems("acme"); + } + + @Test + void aCleanOrBlankSchemaHasNone() { + assertEquals(List.of(), problems("")); + assertEquals(List.of(), problems("/faq:\n type: FAQPage\n faq:\n - { q: Q, a: A }\n" + + "/shop/*:\n - type: Product\n name: P\n/p:\n type: Product\n")); + } + + /** A block that applies but publishes nothing of its own is listed; a product's name defaults to the title. */ + @Test + void aBlockThatPublishesNothingOfItsOwnIsListed() { + List p = problems("/faq:\n type: FAQPage\n faq: []\n/help:\n type: FAQPage\n faq:\n" + + " - { question: Q, answer: A }\n/c:\n type: CollectionPage\n items:\n - { name: A }\n" + + "/l:\n - type: AboutPage\n - type: ItemList\n/two:\n - type: AboutPage\n - type: FAQPage\n"); + assertEquals(List.of( + "/faq: FAQPage has no question with both q: and a:, so the page is an FAQPage with no questions.", + "/help: FAQPage has no question with both q: and a:, so the page is an FAQPage with no questions.", + "/c: CollectionPage has no item with a url:, so no list is published.", + "/l: ItemList has no item with a url:, so no list is published.", + "/two: more than one page type; only the first applies."), p); + } + + /** Google requires a mainEntity on both, which a type with no keys cannot give; they are not offered. */ + @Test + void qaPageAndProfilePageAreNotTypes() { + assertEquals(List.of("/qa: QAPage is not a type this plugin knows; ignored.", + "/me: ProfilePage is not a type this plugin knows; ignored."), + problems("/qa:\n type: QAPage\n/me:\n type: ProfilePage\n")); + } + + @Test + void unreadableYamlIsOneProblemNamingTheError() { + List p = problems("/faq: [unclosed\n"); + assertEquals(1, p.size(), p.toString()); + assertTrue(p.get(0).startsWith("Per-page types cannot be read"), p.toString()); + assertEquals(1, problems("- just\n- a list\n").size(), "a list root is not a pattern map"); + } + + @Test + void eachMistakeIsNamedWithItsPattern() { + List p = problems("about:\n type: AboutPage\n/a*b:\n type: WebPage\n/x:\n type: Prodcut\n" + + "/y:\n - type: AboutPage\n - type: ContactPage\n/z: just text\n"); + assertTrue(p.contains("about: a pattern starts with / and matches page paths."), p.toString()); + assertTrue(p.contains("/a*b: * works only at the end of a pattern; here it is matched as a character."), + p.toString()); + assertTrue(p.contains("/x: Prodcut is not a type this plugin knows; ignored."), p.toString()); + assertTrue(p.contains("/y: more than one page type; only the first applies."), p.toString()); + assertTrue(p.contains("/z: the value must be a type block (type: ...) or a list of them; ignored."), + p.toString()); + assertEquals(5, p.size(), p.toString()); + } +} diff --git a/plugins/discoverability/src/test/java/mx/quest/discover/SettingsDescriptorTest.java b/plugins/discoverability/src/test/java/mx/quest/discover/SettingsDescriptorTest.java new file mode 100644 index 0000000..36a8f74 --- /dev/null +++ b/plugins/discoverability/src/test/java/mx/quest/discover/SettingsDescriptorTest.java @@ -0,0 +1,172 @@ +package mx.quest.discover; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.Reader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.TreeSet; +import org.junit.jupiter.api.Test; + +/** + * Keeps the settings form's layout honest. The kernel deliberately tolerates a broken presentation key — + * an unknown group, a {@code showWhen} on a missing switch, a dangling {@code inheritsFrom}, an unresolved + * message key — by quietly rendering the plain field, so a typo here would never fail anything at runtime: the + * tenant would simply lose the section, the hiding or the help line. This test is where such a typo fails. + * + *

Reads {@code plugin.yml} as plain YAML (the plugin links only the SPI, so the kernel's descriptor parser is not + * on the default test classpath); the {@code host-it} profile additionally parses it with the kernel's own + * {@code PluginDescriptor} ({@code HostDescriptorTest}). + */ +class SettingsDescriptorTest { + + /** The plugin project root — the working directory when the module's tests run. */ + private static final Path ROOT = Path.of(System.getProperty("user.dir")); + + /** One setting definition as the YAML holds it. */ + private record Def(String key, String type, String group, String help, String label, String helpAnchor, + String showWhen, String inheritsFrom, String requiresPlatform, String range) { + + static Def of(Map raw) { + return new Def(str(raw, "key"), str(raw, "type"), str(raw, "group"), str(raw, "help"), str(raw, "label"), + str(raw, "helpAnchor"), str(raw, "showWhen"), str(raw, "inheritsFrom"), + str(raw, "requiresPlatform"), str(raw, "range")); + } + + private static String str(Map raw, String key) { + Object value = raw.get(key); + return value == null ? null : String.valueOf(value); + } + } + + private static Map descriptor() { + return TestSettings.descriptor(); + } + + @SuppressWarnings("unchecked") + private static List defs(String section) { + List out = new ArrayList<>(); + Object list = descriptor().get(section); + if (list != null) { + for (Map raw : (List>) list) { + out.add(Def.of(raw)); + } + } + return out; + } + + @SuppressWarnings("unchecked") + private static List> groups() { + return (List>) descriptor().get("settingGroups"); + } + + private static Properties bundle(String name) throws IOException { + Properties props = new Properties(); + try (Reader reader = Files.newBufferedReader(ROOT.resolve("i18n").resolve(name), StandardCharsets.UTF_8)) { + props.load(reader); + } + return props; + } + + private static Map byKey(List schema) { + Map map = new HashMap<>(); + schema.forEach(def -> map.put(def.key(), def)); + return map; + } + + private static List all() { + List all = new ArrayList<>(defs("settings")); + all.addAll(defs("siteSettings")); + return all; + } + + @Test + void everyFieldIsInADeclaredSectionAndEverySectionIsUsed() { + Set groups = new TreeSet<>(); + groups().forEach(g -> groups.add(String.valueOf(g.get("id")))); + Set used = new TreeSet<>(); + for (Def def : all()) { + assertTrue(groups.contains(def.group()), def.key() + " names an undeclared group '" + def.group() + "'"); + used.add(def.group()); + } + assertEquals(groups, used, "a declared section with no fields would never show"); + assertEquals(6, groups.size(), "the six sections of the 1.6.0 layout"); + } + + @Test + void everyDependencyPointsAtARealSwitch() { + for (List schema : List.of(defs("settings"), defs("siteSettings"))) { + Map keys = byKey(schema); + for (Def def : schema) { + if (def.showWhen() != null) { + Def gate = keys.get(def.showWhen()); + assertTrue(gate != null && "boolean".equals(gate.type()), + def.key() + ": showWhen must name a boolean in the same schema, got " + def.showWhen()); + } + if (def.inheritsFrom() != null) { + String ref = def.inheritsFrom(); + Def source = ref.startsWith("app:") + ? byKey(defs("settings")).get(ref.substring(4)) : keys.get(ref); + assertTrue(source != null, def.key() + ": inheritsFrom names nothing: " + ref); + assertTrue(def.range().contains("inherit"), def.key() + ": inheritsFrom without an inherit choice"); + } + } + } + for (Def def : defs("siteSettings")) { + if (def.requiresPlatform() != null) { + Def platform = byKey(defs("settings")).get(def.requiresPlatform()); + assertTrue(platform != null && "boolean".equals(platform.type()), + def.key() + ": requiresPlatform must name an app-level boolean"); + } + } + assertEquals("app:robots.ai-default", byKey(defs("siteSettings")).get("robots.ai-policy").inheritsFrom(), + "the AI policy still inherits the platform default"); + assertEquals("indexnow.enabled", byKey(defs("siteSettings")).get("indexnow.enabled").requiresPlatform()); + } + + @Test + void everyFieldHasAHelpLineAndEveryKeyResolvesInEnglishAndSpanish() throws IOException { + List keys = new ArrayList<>(); + for (Def def : all()) { + assertNotNull(def.help(), def.key() + " has no help line"); + keys.add(def.label()); + keys.add(def.help()); + } + for (Map g : groups()) { + keys.add(String.valueOf(g.get("label"))); + keys.add(String.valueOf(g.get("help"))); + } + Properties en = bundle("messages.properties"); + Properties es = bundle("messages_es.properties"); + for (String key : keys) { + assertTrue(en.containsKey(key), "missing in messages.properties: " + key); + assertTrue(es.containsKey(key), "missing in messages_es.properties: " + key); + } + assertEquals(new TreeSet<>(en.stringPropertyNames()), new TreeSet<>(es.stringPropertyNames()), + "the English and Spanish bundles carry the same keys"); + } + + @Test + void everyLearnMoreLinkLandsOnASectionOfTheHelpPage() throws IOException { + assertEquals("/__plugin/discoverability/static/discoverability-help.html", descriptor().get("helpUrl")); + String page = Files.readString(ROOT.resolve("static").resolve("discoverability-help.html")); + List anchors = new ArrayList<>(); + groups().forEach(g -> anchors.add(g.get("helpAnchor") == null ? null : String.valueOf(g.get("helpAnchor")))); + all().forEach(def -> anchors.add(def.helpAnchor())); + for (String anchor : anchors) { + if (anchor != null) { + assertTrue(page.contains("id=\"" + anchor + "\""), "the help page has no #" + anchor); + } + } + } +} diff --git a/plugins/discoverability/src/test/java/mx/quest/discover/SitemapEndpointTest.java b/plugins/discoverability/src/test/java/mx/quest/discover/SitemapEndpointTest.java new file mode 100644 index 0000000..5530632 --- /dev/null +++ b/plugins/discoverability/src/test/java/mx/quest/discover/SitemapEndpointTest.java @@ -0,0 +1,416 @@ +package mx.quest.discover; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import mx.quest.runway.spi.model.CatalogEntry; +import mx.quest.runway.spi.model.ContentRef; +import mx.quest.runway.spi.model.RouteRequest; +import mx.quest.runway.spi.model.RouteResponse; +import mx.quest.runway.spi.model.SiteView; +import mx.quest.runway.spi.testkit.FakeContentCatalog; +import mx.quest.runway.spi.testkit.FakePluginSettings; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * /sitemap.xml over the host's {@code ContentCatalogView}: the whole published content surface — pages AND plugin + * content — with the hreflang alternates and {@code x-default} the host computed, {@code } from + * {@code updatedAt}, noindex and canonicalised-elsewhere items left out, the index/shards past 10,000 URLs, and the + * conditional GET. Disabled ⇒ 404; base from the trusted origin when the site has none. + * + *

The listing itself (published only, safe and unreserved paths, a throwing source contributing nothing) and the + * URL computation are the host's, tested in the kernel; the host-it profile runs this endpoint over the real kernel + * catalog ({@code HostCatalogParityTest}), including the head-vs-sitemap agreement. + */ +class SitemapEndpointTest { + + private static final Locale EN = Locale.ENGLISH; + private static final Locale ES = Locale.forLanguageTag("es"); + private static final Instant UPDATED = Instant.parse("2026-07-17T10:00:00Z"); + private static final SiteView SITE = new SiteView("acme", "Acme", EN, List.of(EN, ES), "https://acme.test"); + + @BeforeEach + void freshValidators() { + CrawlConditional.reset(); // per-site validator state is static — isolate from sibling tests + } + + /** The endpoint over a listing of {@code refs} (as pages) for {@link #SITE}'s locales, sitemap on. */ + private static SitemapEndpoint endpoint(SiteView site, ContentRef... refs) { + FakeContentCatalog catalog = new FakeContentCatalog().site("acme"); + for (ContentRef ref : refs) { + catalog.entry("acme", Entries.page(ref, site)); + } + return new SitemapEndpoint(catalog, TestSettings.declared()); + } + + private static SitemapEndpoint endpoint(ContentRef... refs) { + return endpoint(SITE, refs); + } + + private static final ContentRef ABOUT = ContentRef.of("about", "/about", Map.of(), List.of(EN, ES), + Map.of("en", "About", "es", "Acerca"), Map.of("en", "About page"), "__site__/acme/about", UPDATED); + private static final ContentRef ENTRY = ContentRef.of("my-post", "/blog/my-post", + Map.of("es", "/blog/mi-entrada"), List.of(EN, ES), Map.of("en", "My post"), Map.of(), + "__plugin__/blog/entry", UPDATED); + + /** Published, but the site tells robots not to index it — must not be advertised. */ + private static final ContentRef NOINDEXED = new ContentRef("hidden", "/hidden", Map.of(), List.of(EN), + Map.of("en", "Hidden"), Map.of(), null, "__site__/acme/hidden", true, UPDATED, true, null, null, + Map.of()); + /** Published and indexable, but declares a DIFFERENT canonical — it is not the authoritative URL. */ + private static final ContentRef DUPLICATE = new ContentRef("dupe", "/dupe", Map.of(), List.of(EN), + Map.of("en", "Dupe"), Map.of(), null, "__site__/acme/dupe", true, UPDATED, false, + "https://acme.test/about", null, Map.of()); + /** Published with a SELF-referential canonical — the ordinary case, which must still be listed. */ + private static final ContentRef SELF_CANONICAL = new ContentRef("self", "/self", Map.of(), List.of(EN), + Map.of("en", "Self"), Map.of(), null, "__site__/acme/self", true, UPDATED, false, + "https://acme.test/self", null, Map.of()); + + private static RouteRequest req(SiteView site, Map headers) { + return req(site, headers, "/sitemap.xml"); + } + + private static RouteRequest req(SiteView site, Map headers, String path) { + return new RouteRequest(site, EN, "GET", path, Map.of(), headers, new byte[0], Map.of(), null, ""); + } + + /** {@code n} trivial published pages — the fixture for the sharding tests. */ + private static ContentRef[] pages(int n) { + ContentRef[] many = new ContentRef[n]; + for (int i = 0; i < n; i++) { + many[i] = new ContentRef("p" + i, "/p" + i, Map.of(), List.of(EN), Map.of("en", "P" + i), Map.of(), + null, "__site__/acme/p" + i, true, UPDATED, false, null, null, Map.of()); + } + return many; + } + + private static String body(RouteResponse r) { + return new String(r.body(), StandardCharsets.UTF_8); + } + + @Test + void servesTheWholeContentSurfaceWithHreflangAndLastmod() { + FakeContentCatalog catalog = new FakeContentCatalog() + .entry("acme", Entries.page(ABOUT, SITE)) + .entry("acme", Entries.of("blog", ENTRY, SITE)); + RouteResponse r = new SitemapEndpoint(catalog, TestSettings.declared()).handle(req(SITE, Map.of())); + + assertEquals(200, r.status()); + assertEquals("application/xml; charset=utf-8", r.headers().get("Content-Type")); + String xml = body(r); + // Page-like items, both locales, the default unprefixed. + assertTrue(xml.contains("https://acme.test/about"), "default locale is unprefixed"); + assertTrue(xml.contains("https://acme.test/es/about"), "other locale is /-prefixed"); + assertTrue(xml.contains("hreflang=\"en\"") && xml.contains("hreflang=\"es\"")); + assertTrue(xml.contains("hreflang=\"x-default\"")); + // PLUGIN content is a first-class sitemap citizen — with its LOCALIZED slug. + assertTrue(xml.contains("https://acme.test/blog/my-post"), "virtual entry listed"); + assertTrue(xml.contains("https://acme.test/es/blog/mi-entrada"), "its localized slug too"); + assertTrue(xml.contains("" + UPDATED + ""), "lastmod emitted from updatedAt"); + } + + /** + * The exact document — every byte — for a small bilingual site. 2.0.0 reads its URLs from the host's listing + * instead of computing them; this pins the document so that move cannot change what a crawler receives. + */ + @Test + void theDocumentIsByteForByteWhatOnePointSixServed() { + FakeContentCatalog catalog = new FakeContentCatalog() + .entry("acme", Entries.of("blog", ENTRY, SITE)) + .entry("acme", Entries.page(ABOUT, SITE)); + String xml = body(new SitemapEndpoint(catalog, TestSettings.declared()).handle(req(SITE, Map.of()))); + String about = """ + + + + """; + String post = """ + + + + """; + String lastmod = " 2026-07-17T10:00:00Z\n"; + assertEquals("\n" + + "\n" + + " \n https://acme.test/about\n" + lastmod + about + " \n" + + " \n https://acme.test/blog/my-post\n" + lastmod + post + " \n" + + " \n https://acme.test/es/about\n" + lastmod + about + " \n" + + " \n https://acme.test/es/blog/mi-entrada\n" + lastmod + post + " \n" + + "\n", xml); + } + + @Test + void conditionalGetRevalidatesWith304AndTheHeadersMatch() { + SitemapEndpoint endpoint = endpoint(ABOUT); + + RouteResponse fresh = endpoint.handle(req(SITE, Map.of())); + assertEquals(200, fresh.status()); + String lastModified = fresh.headers().get("Last-Modified"); + assertTrue(lastModified != null && !lastModified.isBlank(), "the 200 carries Last-Modified"); + assertEquals("no-cache", fresh.headers().get("Cache-Control"), "cache-but-revalidate posture"); + + RouteResponse revalidated = endpoint.handle(req(SITE, Map.of("If-Modified-Since", lastModified))); + assertEquals(304, revalidated.status(), "an unchanged sitemap revalidates without re-serializing"); + assertEquals(0, revalidated.body().length, "the 304 carries no body"); + assertEquals(lastModified, revalidated.headers().get("Last-Modified"), "same validator"); + + RouteResponse older = endpoint.handle(req(SITE, + Map.of("If-Modified-Since", "Mon, 01 Jan 2001 00:00:00 GMT"))); + assertEquals(200, older.status(), "an outdated copy gets the full document again"); + } + + @Test + void disabledReturns404() { + FakePluginSettings off = TestSettings.declared().site("acme", Map.of("sitemap.enabled", false)); + RouteResponse r = new SitemapEndpoint(new FakeContentCatalog().entry("acme", Entries.page(ABOUT, SITE)), off) + .handle(req(SITE, Map.of())); + assertEquals(404, r.status()); + assertEquals("no-store", r.headers().get("Cache-Control")); + } + + @Test + void enabledByDefault() { + assertEquals(200, endpoint(ABOUT).handle(req(SITE, Map.of())).status(), "sitemap.enabled defaults on"); + } + + /** + * Without a configured base URL the absolute URLs use the request's TRUSTED origin (scheme, host and port as + * the kernel's trusted-proxy gate left them). 1.x read the raw Host header and guessed {@code https}. + */ + @Test + void takesTheBaseFromTheTrustedOriginWhenBaseUrlUnset() { + SiteView noBase = new SiteView("acme", "Acme", EN, List.of(EN, ES), null); + RouteRequest request = new RouteRequest(noBase, EN, "GET", "/sitemap.xml", Map.of(), + Map.of("Host", "spoofed.test"), new byte[0], Map.of(), null, "http://acme.test:8080"); + String xml = body(endpoint(noBase, ABOUT).handle(request)); + assertTrue(xml.contains("http://acme.test:8080/about"), xml); + assertFalse(xml.contains("spoofed") || xml.contains("https://"), "never the Host header, never a guess"); + } + + @Test + void aTrailingSlashOnTheConfiguredBaseIsDropped() { + SiteView slash = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test/"); + String xml = body(endpoint(slash, ABOUT).handle(req(slash, Map.of()))); + assertTrue(xml.contains("https://acme.test/about"), xml); + } + + /** + * A sitemap is a list of URLs the site RECOMMENDS for indexing, so listing a page it separately tells robots + * not to index contradicts itself — sitemaps.org treats such a file as a quality signal against the site. + * + *

Filtered in the plugin rather than in {@code ContentCatalog} on purpose: the router, the search indexer + * and llms.txt all legitimately need the full published set, so narrowing the catalog would break them. + */ + @Test + void noindexContentIsPublishedButNeverAdvertised() { + SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test"); + String xml = body(endpoint(site, ABOUT, NOINDEXED).handle(req(site, Map.of()))); + + assertTrue(xml.contains("https://acme.test/about"), "indexable content still listed"); + assertFalse(xml.contains("/hidden"), "noindex content must not appear in the sitemap"); + } + + /** + * An item declaring a canonical elsewhere has said it is not the authoritative URL; advertising it would put + * a self-declared non-canonical address in the sitemap. A canonical equal to the item's OWN url is the normal + * self-referential case and must not be swept up by the same rule — that is the half a naive check breaks. + */ + @Test + void anItemCanonicalisedElsewhereIsOmittedButASelfCanonicalOneIsKept() { + SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test"); + String xml = body(endpoint(site, ABOUT, DUPLICATE, SELF_CANONICAL).handle(req(site, Map.of()))); + + assertFalse(xml.contains("/dupe"), "an item canonicalised elsewhere is not the authoritative URL"); + assertTrue(xml.contains("https://acme.test/self"), "a SELF-referential canonical stays listed"); + assertTrue(xml.contains("https://acme.test/about"), "an item with no canonical stays listed"); + } + + /** + * A ROOT-RELATIVE canonical names an address on this site and is resolved against the base before comparing, as + * the kernel resolves it for the {@code }. 1.x compared the raw {@code /self} with the absolute URLs, so a + * page whose canonical was its own path was dropped from the sitemap. + */ + @Test + void aRootRelativeSelfCanonicalIsKeptAndARootRelativeElsewhereOneIsOmitted() { + SiteView site = new SiteView("acme", "Acme", EN, List.of(EN, ES), "https://acme.test"); + ContentRef self = new ContentRef("self", "/self", Map.of(), List.of(EN, ES), Map.of("en", "Self"), Map.of(), + null, "__site__/acme/self", true, UPDATED, false, "/self", null, Map.of()); + ContentRef elsewhere = new ContentRef("copy", "/copy", Map.of(), List.of(EN), Map.of("en", "Copy"), Map.of(), + null, "__site__/acme/copy", true, UPDATED, false, "/self", null, Map.of()); + String xml = body(endpoint(site, self, elsewhere).handle(req(site, Map.of()))); + + assertTrue(xml.contains("https://acme.test/self"), xml); + assertTrue(xml.contains("https://acme.test/es/self"), "every locale of a self-canonical item"); + assertFalse(xml.contains("/copy"), "a root-relative canonical naming ANOTHER page still points elsewhere"); + } + + /** + * An item that exists only in a non-default locale: its one address and its x-default are the host's (the + * Spanish URL), never the unprefixed default path, which the site does not serve. + */ + @Test + void aNonDefaultLocaleOnlyItemUsesTheHostsAddressesForLocAndXDefault() { + ContentRef solo = ContentRef.of("solo", "/solo", Map.of("es", "/solo-es"), List.of(ES), Map.of("es", "Solo"), + Map.of(), "__site__/acme/solo", UPDATED); + String xml = body(endpoint(solo).handle(req(SITE, Map.of()))); + assertTrue(xml.contains("https://acme.test/es/solo-es"), xml); + assertTrue(xml.contains("hreflang=\"x-default\" href=\"https://acme.test/es/solo-es\""), xml); + assertFalse(xml.contains("https://acme.test/solo\""), "the unprefixed default path does not serve: " + xml); + assertFalse(xml.contains("hreflang=\"en\""), "no alternate for a locale the item does not exist in"); + } + + /** A canonical naming one of the item's OTHER locales' addresses is still self-referential. */ + @Test + void aCanonicalNamingAnotherLocaleOfTheSameItemIsSelf() { + ContentRef ref = new ContentRef("about", "/about", Map.of(), List.of(EN, ES), Map.of("en", "About"), Map.of(), + null, "__site__/acme/about", true, UPDATED, false, "https://acme.test/es/about", null, Map.of()); + String xml = body(endpoint(ref).handle(req(SITE, Map.of()))); + assertTrue(xml.contains("https://acme.test/about"), xml); + } + + // ---- sitemap index ------------------------------------------------------------------------------- + + /** + * A small site keeps a single {@code } — no index, no second round trip. + * + *

This is the shape almost every tenant has, and splitting a 40-URL site across an index would cost a + * crawler two fetches to learn nothing. + */ + @Test + void asmallSiteIsStillASinglePlainUrlset() { + SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test"); + String xml = body(endpoint(site, pages(40)).handle(req(site, Map.of()))); + + assertTrue(xml.contains("", -1).length - 1); + } + + /** …and its shard paths 404 rather than serving the same document at a second address. */ + @Test + void aSmallSiteAnswers404OnTheShardPaths() { + SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test"); + + RouteResponse response = endpoint(site, pages(40)).handle(req(site, Map.of(), "/sitemap-1.xml")); + + assertEquals(404, response.status(), + "two URLs serving one document is the duplicate-content shape this plugin exists to avoid"); + } + + /** + * Past one shard's worth, {@code /sitemap.xml} becomes an index naming exactly the shards that exist. + * + *

25,000 URLs is three shards of 10,000 — the third holding 5,000 — so the count catches both an + * off-by-one in the ceiling division and an index that advertises a shard with nothing in it. + */ + @Test + void aLargeSiteGetsAnIndexNamingExactlyTheShardsThatExist() { + SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test"); + String xml = body(endpoint(site, pages(25_000)).handle(req(site, Map.of()))); + + assertTrue(xml.contains("", -1).length - 1, "25,000 URLs is 3 shards, not 2 and not 4"); + assertTrue(xml.contains("https://acme.test/sitemap-1.xml"), xml); + assertTrue(xml.contains("https://acme.test/sitemap-3.xml"), xml); + assertFalse(xml.contains("/sitemap-4.xml"), "an empty shard must never be advertised"); + } + + /** Each shard carries its own slice, full shards first, and the last one holds the remainder. */ + @Test + void eachShardCarriesItsOwnSliceAndTheLastHoldsTheRemainder() { + SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test"); + SitemapEndpoint endpoint = endpoint(site, pages(25_000)); + + String first = body(endpoint.handle(req(site, Map.of(), "/sitemap-1.xml"))); + String last = body(endpoint.handle(req(site, Map.of(), "/sitemap-3.xml"))); + + assertEquals(10_000, first.split("", -1).length - 1); + assertEquals(5_000, last.split("", -1).length - 1); + assertTrue(first.contains("Asserted as a set rather than by counting, because a boundary bug that drops one URL and duplicates + * another leaves the totals right. + */ + @Test + void theShardsPartitionTheUrlSetWithNoGapOrOverlap() { + SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test"); + SitemapEndpoint endpoint = endpoint(site, pages(25_000)); + + List all = new java.util.ArrayList<>(); + for (int shard = 1; shard <= 3; shard++) { + all.addAll(locs(body(endpoint.handle(req(site, Map.of(), "/sitemap-" + shard + ".xml"))))); + } + + assertEquals(25_000, all.size(), "no URL is served twice"); + assertEquals(25_000, new java.util.HashSet<>(all).size(), "…and none is served twice under two names"); + assertTrue(all.contains("https://acme.test/p0") && all.contains("https://acme.test/p24999"), + "the first and last items both survive the split"); + } + + /** + * Shard membership is a function of the CONTENT, not of source-registration order. + * + *

The host's listing is grouped by source in an order it does not promise, which says nothing across + * restarts or across the nodes of a cluster. If shard boundaries followed it, two nodes behind one load + * balancer would serve different content for the same shard number, and a crawler alternating + * between them would watch URLs appear and vanish with nothing in the response to explain it. + */ + @Test + void shardMembershipDoesNotDependOnSourceOrder() { + SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test"); + ContentRef[] refs = pages(25_000); + ContentRef[] reversed = new ContentRef[refs.length]; + for (int i = 0; i < refs.length; i++) { + reversed[i] = refs[refs.length - 1 - i]; + } + + String oneWay = body(endpoint(site, refs).handle(req(site, Map.of(), "/sitemap-2.xml"))); + String other = body(endpoint(site, reversed).handle(req(site, Map.of(), "/sitemap-2.xml"))); + + assertEquals(oneWay, other, "the same shard number must mean the same URLs on every node"); + } + + /** A shard number past the end 404s — nothing links to it, so the only way there is to type it. */ + @Test + void aShardBeyondTheEndIs404() { + SiteView site = new SiteView("acme", "Acme", EN, List.of(EN), "https://acme.test"); + SitemapEndpoint endpoint = endpoint(site, pages(25_000)); + + assertEquals(404, endpoint.handle(req(site, Map.of(), "/sitemap-4.xml")).status()); + assertEquals(200, endpoint.handle(req(site, Map.of(), "/sitemap-3.xml")).status()); + } + + /** Every shard route is declared, because the host matches routes by exact path — no patterns. */ + @Test + void theIndexAndEveryShardAreDeclaredRoutes() { + List paths = endpoint().routes().stream() + .map(mx.quest.runway.spi.model.Route::pathPattern).toList(); + + assertTrue(paths.contains("/sitemap.xml")); + assertTrue(paths.contains("/sitemap-1.xml")); + assertTrue(paths.contains("/sitemap-20.xml")); + assertFalse(paths.contains("/sitemap-21.xml"), "the ceiling is real and must be visible in the routes"); + } + + /** The {@code } values of a sitemap document. */ + private static List locs(String xml) { + List found = new java.util.ArrayList<>(); + java.util.regex.Matcher m = java.util.regex.Pattern.compile("([^<]+)").matcher(xml); + while (m.find()) { + found.add(m.group(1)); + } + return found; + } +} diff --git a/plugins/discoverability/src/test/java/mx/quest/discover/StructuredDataHeadTest.java b/plugins/discoverability/src/test/java/mx/quest/discover/StructuredDataHeadTest.java new file mode 100644 index 0000000..0069a11 --- /dev/null +++ b/plugins/discoverability/src/test/java/mx/quest/discover/StructuredDataHeadTest.java @@ -0,0 +1,712 @@ +package mx.quest.discover; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.Instant; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import mx.quest.runway.spi.testkit.FakePluginSettings; +import mx.quest.runway.spi.model.HeadContext; +import mx.quest.runway.spi.model.Provenance; +import mx.quest.runway.spi.model.PageMeta; +import mx.quest.runway.spi.model.SiteView; +import org.junit.jupiter.api.Test; + +/** SEO+ structured-data head: emits the WebSite/WebPage(/Organization) graph, and nothing when it shouldn't. */ +class StructuredDataHeadTest { + + private final FakePluginSettings config = TestSettings.declared(); + private final StructuredDataHead head = new StructuredDataHead(config, Map.of()); + private final StructuredDataHead typed = new StructuredDataHead(config, Map.ofEntries( + Map.entry("FAQPage", new FaqPageSchema()), + Map.entry("Product", new ProductSchema()), + Map.entry("Article", new ArticleSchema()), + Map.entry("BlogPosting", new ArticleSchema()), + Map.entry("LocalBusiness", new LocalBusinessSchema()), + Map.entry("CafeOrCoffeeShop", new LocalBusinessSchema()), + Map.entry("Service", new ServiceSchema()), + Map.entry("ProfessionalService", new ServiceSchema()), + Map.entry("Person", new PersonSchema()), + Map.entry("ItemList", new CollectionSchema()), + Map.entry("CollectionPage", new CollectionSchema()))); + + private static HeadContext pageAt(String path, String title) { + SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test"); + PageMeta page = new PageMeta(path.substring(1), title, "", + List.of(Locale.ENGLISH), Locale.ENGLISH, true, false); + String canonical = "https://acme.test" + path; + return new HeadContext(site, page, Locale.ENGLISH, canonical, canonical, List.of(), false, false); + } + + private void cfg(Map map) { + config.site("acme", map); + } + + private HeadContext ctx(boolean preview, boolean noindex) { + SiteView site = new SiteView("acme", "Acme Corp", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test"); + PageMeta page = new PageMeta("about", "About Acme", "We build things.", + List.of(Locale.ENGLISH), Locale.ENGLISH, true, noindex); + return new HeadContext(site, page, Locale.ENGLISH, "https://acme.test/about", + "https://acme.test/about", List.of(), preview, noindex); + } + + @Test + void emitsWebSiteAndWebPageByDefault() { + cfg(Map.of()); // all defaults → jsonld.enabled true + String out = head.render(ctx(false, false)); + assertTrue(out.contains("application/ld+json")); + assertTrue(out.contains("\"@type\":\"WebSite\"")); + assertTrue(out.contains("\"@type\":\"WebPage\"")); + assertTrue(out.contains("https://acme.test/about"), "the WebPage is anchored on the canonical"); + assertTrue(out.contains("About Acme")); + assertTrue(out.contains("\"isPartOf\""), "the WebPage references the WebSite"); + } + + @Test + void emitsOrganizationWithSameAsWhenConfigured() { + cfg(Map.of("org.name", "Acme Corp", "org.logo", "https://acme.test/logo.png", + "org.sameas", List.of("https://social.example/acme", "https://network.example/acme"))); + String out = head.render(ctx(false, false)); + assertTrue(out.contains("\"@type\":\"Organization\"")); + assertTrue(out.contains("Acme Corp")); + assertTrue(out.contains("logo.png")); + assertTrue(out.contains("social.example/acme") && out.contains("network.example/acme"), "sameAs profiles emitted"); + assertTrue(out.contains("\"publisher\""), "the WebPage names the Organization as publisher"); + } + + @Test + void resolvesARootRelativeOrgLogoToAbsolute() { + cfg(Map.of("org.name", "Acme", "org.logo", "/static/img/logo.svg")); + String out = head.render(ctx(false, false)); + assertTrue(out.contains("\"logo\":\"https://acme.test/static/img/logo.svg\""), + "a root-relative org.logo resolves against the site base: " + out); + } + + @Test + void emitsArticleHeadlineWhenTypeIsArticle() { + cfg(Map.of("jsonld.type", "Article")); + String out = head.render(ctx(false, false)); + assertTrue(out.contains("\"@type\":\"Article\"")); + assertTrue(out.contains("\"headline\":\"About Acme\""), "Article uses headline, not name"); + } + + @Test + void emitsNothingOnNoindexPreviewOrWhenDisabled() { + cfg(Map.of()); + assertEquals("", head.render(ctx(false, true)), "no structured data on a noindex page"); + assertEquals("", head.render(ctx(true, false)), "no structured data on a preview render"); + cfg(Map.of("jsonld.enabled", false)); + assertEquals("", head.render(ctx(false, false)), "disabled by the tenant"); + } + + @Test + void breadcrumbsAppearForAChildPageAndNotTheHome() { + cfg(Map.of()); + assertTrue(head.render(ctx(false, false)).contains("\"@type\":\"BreadcrumbList\""), "child page has a trail"); + + SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test"); + PageMeta home = new PageMeta("index", "Home", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false); + HeadContext homeCtx = new HeadContext(site, home, Locale.ENGLISH, "https://acme.test/", + "https://acme.test/", List.of(), false, false); + assertFalse(head.render(homeCtx).contains("BreadcrumbList"), "the home page needs no breadcrumb"); + } + + // --- GEO signals, now folded into the single @graph (was AnswerSchemaHead) -------------------------- + + @Test + void foldsGeoSignalsIntoTheSameNodesWhenEnabled() { + cfg(Map.of("geo.enabled", true, "search.url", "/search")); + String out = head.render(ctx(false, false)); + assertEquals(1, countOccurrences(out, "application/ld+json"), "exactly one ld+json block: " + out); + // WebSite/WebPage each defined exactly once, carrying the GEO signals inline (not a second block by @id) + assertEquals(1, countOccurrences(out, "\"@type\":\"WebSite\""), out); + assertEquals(1, countOccurrences(out, "\"@type\":\"WebPage\""), out); + assertTrue(out.contains("\"potentialAction\"") && out.contains("SearchAction"), out); + assertTrue(out.contains("\"speakable\"") && out.contains("SpeakableSpecification"), out); + assertTrue(out.contains("{search_term_string}"), out); + } + + @Test + void speakableDefaultsToRealSelectorsNotPhantomArticle() { + cfg(Map.of("geo.enabled", true)); + String out = head.render(ctx(false, false)); + assertTrue(out.contains("SpeakableSpecification"), out); + assertTrue(out.contains("\"h1\"") && out.contains("\"main\""), out); + assertFalse(out.contains("\"article\""), "the default no longer emits the phantom 'article' selector: " + out); + } + + @Test + void geoSignalsAbsentWhenGeoDisabled() { + cfg(Map.of()); // geo.enabled default false + String out = head.render(ctx(false, false)); + assertTrue(out.contains("\"@type\":\"WebSite\""), "the SEO graph still emits"); + assertFalse(out.contains("speakable"), "no GEO speakable when geo disabled"); + assertFalse(out.contains("SearchAction"), "no GEO SearchAction when geo disabled"); + } + + @Test + void mapsCurlyQueryPlaceholderToSchemaVariable() { + cfg(Map.of("geo.enabled", true, "search.url", "/find?q={query}")); + String out = head.render(ctx(false, false)); + assertTrue(out.contains("q={search_term_string}"), out); + assertFalse(out.contains("{query}"), "the {query} placeholder is rewritten"); + } + + // --- SoftwareApplication (item 4): homepage-only, @id-linked --------------------------------------- + + private HeadContext homeCtx(String canonical) { + SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test"); + PageMeta home = new PageMeta("index", "Home", "The home page.", + List.of(Locale.ENGLISH), Locale.ENGLISH, true, false); + return new HeadContext(site, home, Locale.ENGLISH, canonical, canonical, List.of(), false, false); + } + + @Test + void emitsSoftwareApplicationOnTheHomepageOnly() { + cfg(Map.of("software.enabled", true, "software.name", "Acme App", "software.category", "WebApplication", + "software.price", "0", "org.name", "Acme Corp")); + assertFalse(head.render(ctx(false, false)).contains("SoftwareApplication"), + "not emitted on an interior page"); + String out = head.render(homeCtx("https://acme.test/")); + assertTrue(out.contains("\"@type\":\"SoftwareApplication\""), out); + assertTrue(out.contains("acme.test/#software"), "carries a stable @id: " + out); + assertTrue(out.contains("Acme App"), out); + assertTrue(out.contains("\"@type\":\"Offer\"") && out.contains("\"price\":\"0\""), "free offer: " + out); + assertTrue(out.contains("\"publisher\""), "references the Organization as publisher"); + assertEquals(1, countOccurrences(out, "\"@type\":\"SoftwareApplication\""), "emitted exactly once: " + out); + } + + @Test + void softwareApplicationAlsoFiresOnALocalizedHome() { + cfg(Map.of("software.enabled", true, "software.name", "Acme App")); + SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, + List.of(Locale.ENGLISH, Locale.forLanguageTag("es")), "https://acme.test"); + PageMeta page = new PageMeta("index", "Inicio", "", + List.of(Locale.ENGLISH), Locale.forLanguageTag("es"), true, false); + HeadContext esHome = new HeadContext(site, page, Locale.forLanguageTag("es"), "https://acme.test/es", + "https://acme.test/", List.of(), false, false); + assertTrue(head.render(esHome).contains("SoftwareApplication"), "the localized home /es carries the entity"); + } + + @Test + void aCrossDomainCanonicalOverrideDoesNotLeakSoftwareApplication() { + // A per-page canonical pointing at ANOTHER host must not be mistaken for the home (which would leak the + // homepage-only SoftwareApplication) — the pathOf() prefix guard returns a non-"/" path so isHome is false. + cfg(Map.of("software.enabled", true, "software.name", "Acme App")); + SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test"); + PageMeta page = new PageMeta("syndicated", "Syndicated", "", + List.of(Locale.ENGLISH), Locale.ENGLISH, true, false); + HeadContext ctx = new HeadContext(site, page, Locale.ENGLISH, "https://ex.test/x", + "https://ex.test/x", List.of(), false, false); + String out = head.render(ctx); + assertFalse(out.contains("SoftwareApplication"), "no homepage entity on a cross-domain canonical: " + out); + assertTrue(out.contains("\"@type\":\"WebPage\""), "the WebPage node still emits: " + out); + } + + @Test + void noSoftwareApplicationWhenDisabled() { + cfg(Map.of("software.name", "Acme App")); // software.enabled defaults false + assertFalse(head.render(homeCtx("https://acme.test/")).contains("SoftwareApplication")); + } + + // --- type-aware structured data (item 5): FAQPage from content.schema, path-matched ----------------- + + @Test + void emitsFaqPageForAPathDeclaredInContentSchema() { + String schema = "/faq:\n type: FAQPage\n faq:\n" + + " - { q: \"Is this real?\", a: \"No, it is a demo.\" }\n" + + " - { q: \"Where based?\", a: \"Portland.\" }\n"; + cfg(Map.of("content.schema", schema)); + SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test"); + PageMeta page = new PageMeta("faq", "FAQ", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false); + HeadContext faqCtx = new HeadContext(site, page, Locale.ENGLISH, "https://acme.test/faq", + "https://acme.test/faq", List.of(), false, false); + + String out = typed.render(faqCtx); + assertTrue(out.contains("\"@type\":\"FAQPage\""), out); + assertTrue(out.contains("\"@type\":\"Question\"") && out.contains("\"@type\":\"Answer\""), out); + assertTrue(out.contains("Is this real?") && out.contains("No, it is a demo."), out); + assertTrue(out.contains("acme.test/faq#webpage"), "FAQPage is mainEntityOfPage-linked to the WebPage: " + out); + // still ONE ld+json block — the typed node joins the same @graph + assertEquals(1, countOccurrences(out, "application/ld+json"), out); + } + + @Test + void noTypedNodesWhenPathDoesNotMatchOrTypeUnregistered() { + cfg(Map.of("content.schema", "/faq:\n type: FAQPage\n faq:\n - { q: \"Q\", a: \"A\" }\n")); + // ctx() is /about — no content.schema entry matches → no FAQPage + assertFalse(typed.render(ctx(false, false)).contains("FAQPage"), "path /about matches no pattern"); + } + + @Test + void emitsProductWithOfferForASectionPrefixPattern() { + cfg(Map.of("content.schema", + "/coffee-*:\n type: Product\n price: \"22.00\"\n currency: USD\n availability: InStock\n", + "org.name", "Roasters")); + String out = typed.render(pageAt("/coffee-guji", "Ethiopia Guji")); + assertTrue(out.contains("\"@type\":\"Product\""), out); + assertTrue(out.contains("\"@type\":\"Offer\"") && out.contains("\"price\":\"22.00\""), out); + assertTrue(out.contains("schema.org/InStock"), "availability expanded to a URL: " + out); + assertTrue(out.contains("\"brand\""), "brand references the Organization"); + } + + @Test + void emitsOneLocalBusinessNodePerLocation() { + String schema = "/cafes:\n type: CafeOrCoffeeShop\n locations:\n" + + " - { name: \"Roastery\", street: \"14 Lamplight Lane\", locality: Portland, region: OR, postalCode: \"97201\" }\n" + + " - { name: \"Downtown\", street: \"88 Meridian St\", locality: Portland, region: OR }\n"; + cfg(Map.of("content.schema", schema)); + String out = typed.render(pageAt("/cafes", "Cafes")); + assertEquals(2, countOccurrences(out, "\"@type\":\"CafeOrCoffeeShop\""), "one node per location: " + out); + assertTrue(out.contains("Roastery") && out.contains("Downtown"), out); + assertTrue(out.contains("\"@type\":\"PostalAddress\"") && out.contains("14 Lamplight Lane"), out); + } + + @Test + void emitsAPersonPerTeamMember() { + String schema = "/team:\n type: Person\n people:\n" + + " - { name: \"Theo Vance\", jobTitle: \"Head Roaster\" }\n" + + " - { name: \"Mara Okafor\", jobTitle: \"Cafe Director\" }\n"; + cfg(Map.of("content.schema", schema, "org.name", "Nocturne")); + String out = typed.render(pageAt("/team", "Team")); + assertEquals(2, countOccurrences(out, "\"@type\":\"Person\""), out); + assertTrue(out.contains("Theo Vance") && out.contains("Mara Okafor"), out); + assertTrue(out.contains("\"worksFor\""), "worksFor references the Organization"); + } + + // --- ItemList on a collection page ------------------------------------------------------------------ + + @Test + void emitsAnItemListForACollectionPage() { + String schema = "/coffees:\n type: ItemList\n items:\n" + + " - { name: \"Ethiopia Guji\", url: \"/coffee-ethiopia-guji\" }\n" + + " - { name: \"Colombia Huila\", url: \"/coffee-colombia-huila\" }\n"; + cfg(Map.of("content.schema", schema)); + String out = typed.render(pageAt("/coffees", "Our Coffees")); + assertTrue(out.contains("\"@type\":\"ItemList\""), out); + // The two members appear as positioned ListItems inside itemListElement (the page's breadcrumb also uses + // ListItem, so assert on the member payloads rather than a raw ListItem count). + assertTrue(out.contains("Ethiopia Guji") && out.contains("Colombia Huila"), out); + assertTrue(out.contains("https://acme.test/coffee-ethiopia-guji") + && out.contains("https://acme.test/coffee-colombia-huila"), + "root-relative member urls are absolutized against the base: " + out); + assertTrue(out.contains("acme.test/coffees#itemlist"), "the ItemList carries a stable @id: " + out); + assertTrue(out.contains("\"mainEntityOfPage\""), "the ItemList is linked to the page: " + out); + } + + @Test + void collectionPageAliasAlsoEmitsAnItemList() { + cfg(Map.of("content.schema", "/index:\n type: CollectionPage\n items:\n - { name: A, url: /a }\n")); + assertTrue(typed.render(pageAt("/index", "Index")).contains("\"@type\":\"ItemList\""), + "CollectionPage is an alias for the ItemList emitter"); + } + + // --- several type-blocks on one path ---------------------------------------------------------------- + + @Test + void emitsEveryTypeBlockWhenAPathDeclaresAList() { + // A pricing page that is BOTH an FAQPage AND a Service — the list form yields both nodes in one @graph. + String schema = "/pricing:\n" + + " - type: FAQPage\n faq:\n - { q: \"Why ranges?\", a: \"Scope drives cost.\" }\n" + + " - { q: \"Discounts?\", a: \"For non-profits.\" }\n" + + " - type: Service\n name: \"Advisory Sprint\"\n offers:\n" + + " - { name: \"Sprint\", price: \"18000\", currency: USD }\n"; + cfg(Map.of("content.schema", schema, "org.name", "Northbeam")); + String out = typed.render(pageAt("/pricing", "Pricing")); + assertTrue(out.contains("\"@type\":\"FAQPage\""), "first block emitted: " + out); + assertTrue(out.contains("\"@type\":\"Service\""), "second block emitted: " + out); + assertTrue(out.contains("Why ranges?") && out.contains("Advisory Sprint"), out); + assertTrue(out.contains("\"@type\":\"Offer\"") && out.contains("\"price\":\"18000\""), + "the priced tier is a machine-readable Offer: " + out); + assertEquals(1, countOccurrences(out, "application/ld+json"), "still one ld+json block: " + out); + } + + @Test + void aRecurringServiceOfferBecomesAUnitPriceSpecification() { + String schema = "/pricing:\n type: Service\n name: \"Northbeam\"\n offers:\n" + + " - { name: \"Growth Retainer\", price: \"32000\", currency: USD, unit: month }\n"; + cfg(Map.of("content.schema", schema)); + String out = typed.render(pageAt("/pricing", "Pricing")); + assertTrue(out.contains("\"@type\":\"UnitPriceSpecification\""), "a per-unit price is a spec: " + out); + assertTrue(out.contains("\"unitText\":\"month\"") && out.contains("\"price\":\"32000\""), out); + } + + // --- breadcrumb @id link + collection parent level -------------------------------------------------- + + @Test + void webPageLinksToTheBreadcrumbById() { + cfg(Map.of()); + String out = head.render(ctx(false, false)); // /about — a child page + assertTrue(out.contains("acme.test/about#breadcrumb"), "the BreadcrumbList has a stable @id: " + out); + assertTrue(out.contains("\"breadcrumb\":{\"@id\":\"https://acme.test/about#breadcrumb\"}"), + "the WebPage points at the BreadcrumbList by @id: " + out); + } + + @Test + void insertsTheDeclaredCollectionParentAsAMiddleBreadcrumbLevel() { + // A product detail page declares its parent collection — the trail reads Home → Coffees → Guji. + String schema = "/coffee-*:\n type: Product\n price: \"22.00\"\n currency: USD\n" + + " breadcrumb: { name: \"Coffees\", url: \"/coffees\" }\n"; + cfg(Map.of("content.schema", schema)); + String out = typed.render(pageAt("/coffee-guji", "Ethiopia Guji")); + assertTrue(out.contains("\"@type\":\"BreadcrumbList\""), out); + assertEquals(3, countOccurrences(out, "\"@type\":\"ListItem\""), "Home + Coffees + the page = 3 levels: " + out); + assertTrue(out.contains("Coffees") && out.contains("https://acme.test/coffees"), + "the parent collection is a middle level: " + out); + assertTrue(out.contains("\"position\":1") && out.contains("\"position\":2") && out.contains("\"position\":3"), + "positions run 1..3: " + out); + } + + // --- LocalBusiness @id + page link ------------------------------------------------------------------ + + @Test + void localBusinessNodesCarryAnIdAndLinkToThePage() { + String schema = "/cafes:\n type: CafeOrCoffeeShop\n locations:\n" + + " - { name: \"Roastery\", locality: Portland }\n" + + " - { name: \"Downtown\", locality: Portland }\n"; + cfg(Map.of("content.schema", schema)); + String out = typed.render(pageAt("/cafes", "Cafes")); + assertTrue(out.contains("acme.test/cafes#business-1") && out.contains("acme.test/cafes#business-2"), + "each location gets a distinct @id: " + out); + assertEquals(2, countOccurrences(out, "\"mainEntityOfPage\""), "each business is linked to the page: " + out); + } + + private static int countOccurrences(String haystack, String needle) { + int count = 0; + int from = 0; + int at; + while ((at = haystack.indexOf(needle, from)) >= 0) { + count++; + from = at + needle.length(); + } + return count; + } + + /** + * The defect this fixed: {@code datePublished} and {@code author} could ONLY come from the shared + * {@code content.schema} block, which matches by {@code *}-prefix. A blog is therefore covered by one + * {@code /blog/*} entry for EVERY post, so a site could assert only one date and one author across all of + * them — false of nearly every page it appeared on, which is exactly what structured-data policy prohibits. + * Per-item provenance must win so each entry states its own truth. + */ + @Test + void perItemProvenanceWinsOverTheSharedContentSchemaBlock() { + cfg(Map.of("content.schema", "/blog/*:\n type: BlogPosting\n" + + " author: Shared Fallback Author\n datePublished: 2020-01-01\n")); + + SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test"); + PageMeta page = new PageMeta("blog:post-1", "Real Post", "", List.of(Locale.ENGLISH), Locale.ENGLISH, + true, false, "blog", + new Provenance("Ada Lovelace", Instant.parse("2026-03-04T00:00:00Z"), + Instant.parse("2026-05-06T12:34:56Z"))); + HeadContext ctx = new HeadContext(site, page, Locale.ENGLISH, "https://acme.test/blog/post-1", + "https://acme.test/blog/post-1", List.of(), false, false); + + String out = typed.render(ctx); + assertTrue(out.contains("\"name\":\"Ada Lovelace\""), "the item's own author must win: " + out); + assertFalse(out.contains("Shared Fallback Author"), "the shared block must not override the item"); + assertTrue(out.contains("\"datePublished\":\"2026-03-04\""), "the item's own date must win: " + out); + assertFalse(out.contains("2020-01-01"), "the shared date must not be asserted on this post"); + // dateModified comes from the host-derived updatedAt, rendered at DAY precision (not second). + assertTrue(out.contains("\"dateModified\":\"2026-05-06\""), out); + } + + /** With no per-item provenance the configured values still apply — existing sites keep working unchanged. */ + @Test + void theSharedBlockStillAppliesWhenTheItemHasNoProvenance() { + cfg(Map.of("content.schema", "/about:\n type: Article\n" + + " author: Editorial Team\n datePublished: 2024-02-03\n")); + + String out = typed.render(pageAt("/about", "About Acme")); + assertTrue(out.contains("\"name\":\"Editorial Team\""), out); + assertTrue(out.contains("\"datePublished\":\"2024-02-03\""), out); + } + + /** + * The emitted JSON-LD must be byte-reproducible, so the same inputs always render the same bytes. + * + *

This is a regression guard with a real history. {@code SearchAction.target} was built with + * {@code Map.of(...)}, and {@code java.util.Map.of} randomizes iteration order per JVM instance + * ({@code ImmutableCollections.SALT}) — so the key order was stable within one run and flipped on roughly + * every other restart. An operator diffing live homepages across an upgrade found it and reasonably + * concluded it was a one-off change between builds; it was not, it was every restart, indefinitely. + * + *

Semantically harmless — the graphs are equal key-sorted — but it made rendered output + * non-reproducible, and the page's strong ETag folds metadata and templates rather than the body, so the + * validator did not change when the bytes did. + * + *

Asserted on the exact ordered substring rather than by parsing, because parsing would compare the + * graphs and pass under exactly the defect this exists to catch. + */ + @Test + void theSearchActionTargetHasADeterministicKeyOrder() { + cfg(Map.of("geo.enabled", true, "search.url", "/search?q={query}")); + String out = head.render(ctx(false, false)); + + assertTrue(out.contains("\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":"), + () -> "SearchAction.target must serialize @type first, deterministically; got:\n" + out); + } + + /** Same inputs, same bytes — the general property, asserted over repeated renders. */ + @Test + void repeatedRendersOfTheSameInputProduceIdenticalBytes() { + cfg(Map.of("geo.enabled", true, "search.url", "/search?q={query}")); + String first = head.render(ctx(false, false)); + for (int i = 0; i < 20; i++) { + assertEquals(first, head.render(ctx(false, false)), "structured data must be byte-reproducible"); + } + } + + /** + * A DETERMINISTIC guard that no serialized JSON-LD node is built with a multi-entry {@code Map.of(...)}. + * + *

Why a source check and not just the behavioural test above

+ * The behavioural test is the right description of intent, but it is a weak guard on its own, + * because the defect it guards is probabilistic: {@code Map.of} picks one of the two orders per JVM + * instance, so a reintroduction passes roughly half the time — and Maven reuses forked JVMs, so it can + * pass for many consecutive runs. Measured: reverting the fix and re-running six times produced five + * passes and one failure. A guard that reports green five times out of six is not a guard. + * + *

So this asserts the property at the only place it is reliably observable: the source. A single-entry + * {@code Map.of("@id", …)} is fine — one key cannot be misordered — and an empty {@code Map.of()} is fine. + * Only two-or-more entries can vary, and those must use an insertion-ordered map. + * + *

If this fails: build the node with {@code Ld.node(...)} or a {@link java.util.LinkedHashMap}. The + * requirement is byte-reproducible output, not any particular key order. + */ + @Test + void noSerializedNodeIsBuiltWithAMultiEntryMapOf() throws Exception { + for (String file : SCANNED_SOURCES) { + java.nio.file.Path path = java.nio.file.Path.of("src/main/java/mx/quest/discover", file); + if (!java.nio.file.Files.exists(path)) { + continue; + } + String source = stripCommentsAndStrings(java.nio.file.Files.readString(path)); + int at = 0; + while ((at = source.indexOf("Map.of(", at)) >= 0) { + int entries = topLevelArgumentsFrom(source, at + "Map.of(".length()); + int offending = at; + assertTrue(entries <= 2, () -> file + " builds a multi-entry Map.of near offset " + offending + + ", whose iteration order is randomized PER JVM INSTANCE and would make emitted " + + "JSON-LD non-reproducible across restarts. Use Ld.node(...) or a LinkedHashMap."); + at += "Map.of(".length(); + } + } + } + + /** The sources whose output is serialized into JSON-LD, and so must be byte-reproducible. */ + private static final java.util.List SCANNED_SOURCES = java.util.List.of( + "StructuredDataHead.java", "Ld.java", "ArticleSchema.java", "ProductSchema.java", + "LocalBusinessSchema.java", "FaqPageSchema.java", "PersonSchema.java", "ServiceSchema.java", + "CollectionSchema.java"); + + /** + * Blanks comments and string literals, preserving offsets and newlines. + * + *

Done before scanning rather than per line, because the previous version read the file LINE BY LINE + * and therefore only ever saw the single-line form of {@code Map.of(...)}. A call whose arguments wrap + * onto following lines — the natural formatting for three or more entries under a 120-column limit, which + * is precisely the case at risk — left one comma or none on the opening line and sailed through. The + * guard was reliable only for the shape the defect was least likely to take. + * + *

Blanking rather than deleting keeps every offset intact, so the failure message can point at a real + * position in the file. Strings are blanked so a {@code Map.of} mentioned inside one, or a comma inside a + * string argument, cannot be miscounted. + */ + private static String stripCommentsAndStrings(String source) { + StringBuilder out = new StringBuilder(source.length()); + int i = 0; + while (i < source.length()) { + char c = source.charAt(i); + if (c == '/' && i + 1 < source.length() && source.charAt(i + 1) == '/') { + while (i < source.length() && source.charAt(i) != '\n') { + out.append(' '); + i++; + } + } else if (c == '/' && i + 1 < source.length() && source.charAt(i + 1) == '*') { + while (i < source.length() && !(source.charAt(i) == '*' && i + 1 < source.length() + && source.charAt(i + 1) == '/')) { + out.append(source.charAt(i) == '\n' ? '\n' : ' '); + i++; + } + for (int k = 0; k < 2 && i < source.length(); k++, i++) { + out.append(' '); + } + } else if (c == '"' || c == '\'') { + char quote = c; + out.append(' '); + i++; + while (i < source.length() && source.charAt(i) != quote) { + if (source.charAt(i) == '\\') { + out.append(' '); + i++; + } + if (i < source.length()) { + out.append(source.charAt(i) == '\n' ? '\n' : ' '); + i++; + } + } + if (i < source.length()) { + out.append(' '); + i++; + } + } else { + out.append(c); + i++; + } + } + return out.toString(); + } + + /** How many top-level arguments the call opening at {@code from} has (0 when it is empty). */ + private static int topLevelArgumentsFrom(String source, int from) { + int depth = 0; + int commas = 0; + boolean any = false; + for (int i = from; i < source.length(); i++) { + char c = source.charAt(i); + if (c == '(' || c == '[' || c == '{') { + depth++; + } else if (c == ')' || c == ']' || c == '}') { + if (depth == 0) { + return any ? commas + 1 : 0; + } + depth--; + } else if (c == ',' && depth == 0) { + commas++; + } + if (!Character.isWhitespace(c)) { + any = true; + } + } + return any ? commas + 1 : 0; + } + + /** + * The guard can actually fail — proven against synthetic sources rather than hoped for. + * + *

A source-level scan that silently matches nothing is indistinguishable from a codebase that is + * clean, and this one WAS partly that: it could not see a wrapped call. So the scanner's two halves are + * exercised directly, including the multi-line form it used to miss. + */ + @Test + void theMapOfScannerCatchesBothTheSingleLineAndTheWrappedForm() { + String singleLine = "var x = Map.of(\"a\", 1, \"b\", 2);"; + String wrapped = "var x = Map.of(\n \"a\", 1,\n \"b\", 2,\n \"c\", 3);"; + String safe = "var x = Map.of(\"only\", 1);"; + String inAComment = "// Map.of(\"a\", 1, \"b\", 2) is what NOT to do"; + String inAString = "var s = \"Map.of(a, 1, b, 2)\";"; + + assertEquals(4, argumentsOfFirstMapOf(singleLine), "two entries = four arguments"); + assertEquals(6, argumentsOfFirstMapOf(wrapped), "the wrapped form is the one it used to miss"); + assertEquals(2, argumentsOfFirstMapOf(safe), "a single entry is fine"); + assertEquals(-1, argumentsOfFirstMapOf(inAComment), "prose explaining the rule is not a violation"); + assertEquals(-1, argumentsOfFirstMapOf(inAString), "nor is a string that happens to contain it"); + } + + /** Arguments of the first {@code Map.of(} in {@code source} after stripping, or {@code -1} if none. */ + private static int argumentsOfFirstMapOf(String source) { + String stripped = stripCommentsAndStrings(source); + int at = stripped.indexOf("Map.of("); + return at < 0 ? -1 : topLevelArgumentsFrom(stripped, at + "Map.of(".length()); + } + + /** + * The declared head input names the very file this contributor reads. + * + *

{@code headInputs} is answered without any storage layout, so the path is a literal — and a literal + * that does not match what the kernel reads folds a stable "absent" marker forever. The validator then + * looks correct while covering nothing, and the symptom is a stale social card or organisation name on + * every cached client, weeks later, with nothing pointing back here. + * + *

The kernel pins the other half of the convention ({@code /plugins/.yml}); this pins that + * the id in the path is the id this contributor actually looks up its settings under, so renaming the + * plugin cannot leave the declaration behind. + */ + @Test + void theDeclaredHeadInputIsThisPluginsOwnSettingsFile() { + assertEquals(List.of("plugins/" + StructuredDataHead.PLUGIN_ID + ".yml"), head.headInputs("acme")); + assertEquals(List.of("plugins/discoverability.yml"), head.headInputs("acme"), + "the kernel reads /plugins/.yml — see SitePluginConfigServiceTest"); + } + + // --- a host-less site: absolute URLs from HeadContext.origin() (SPI 1.0.0, discoverability 2.1.0) ------------ + + /** A host-less site (no base URL, no host name — the platform's catch-all default): its canonical is relative. */ + private static HeadContext hostless(String path, String title, String origin) { + SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), ""); + PageMeta page = new PageMeta(path.substring(1), title, "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, + false); + return new HeadContext(site, page, Locale.ENGLISH, path, path, List.of(), false, false, null, null, origin); + } + + @Test + void aHostlessSitesGraphIsAbsoluteAgainstTheTrustedOrigin() { + cfg(Map.of("org.name", "Acme", "org.logo", "/static/logo.svg")); + String out = head.render(hostless("/about", "About", "http://10.0.0.5:8080")); + assertTrue(out.contains("\"@id\":\"http://10.0.0.5:8080/#website\""), out); + assertTrue(out.contains("\"url\":\"http://10.0.0.5:8080/\""), "WebSite/Organization url: " + out); + assertTrue(out.contains("\"@id\":\"http://10.0.0.5:8080/about#webpage\""), out); + assertTrue(out.contains("\"url\":\"http://10.0.0.5:8080/about\""), out); + assertTrue(out.contains("\"logo\":\"http://10.0.0.5:8080/static/logo.svg\""), out); + assertTrue(out.contains("\"@type\":\"BreadcrumbList\""), "a host-less deep page now has its trail: " + out); + assertTrue(out.contains("\"item\":\"http://10.0.0.5:8080/\""), out); + assertFalse(out.contains("\":\"/"), "no root-relative URL or @id is left: " + out); + } + + @Test + void aHostlessSiteGainsItsSearchActionWithAnAbsoluteTemplate() { + cfg(Map.of("geo.enabled", true, "search.url", "/search?q={query}")); + String out = head.render(hostless("/about", "About", "https://example.test")); + assertTrue(out.contains("\"urlTemplate\":\"https://example.test/search?q={search_term_string}\""), out); + } + + @Test + void theHostlessHomeIsRecognisedAndCarriesNoTrail() { + cfg(Map.of("software.enabled", true)); + String out = head.render(hostless("/", "Home", "https://example.test")); + assertTrue(out.contains("\"@type\":\"SoftwareApplication\""), "the home is still the home: " + out); + assertTrue(out.contains("\"@id\":\"https://example.test/#webpage\""), out); + assertFalse(out.contains("BreadcrumbList"), out); + } + + /** A context with no origin (the constructor without one, or no request) renders exactly as 2.0.0 did. */ + @Test + void withoutAnOriginAHostlessGraphStaysRootRelativeAsBefore() { + cfg(Map.of("geo.enabled", true, "search.url", "/search")); + String out = head.render(hostless("/about", "About", "")); + assertTrue(out.contains("\"@id\":\"/about#webpage\""), out); + assertTrue(out.contains("\"@id\":\"/#website\""), out); + assertFalse(out.contains("SearchAction"), "no base, no SearchAction — as 2.0.0: " + out); + assertFalse(out.contains("BreadcrumbList"), out); + } + + /** The site's base URL wins over the request origin: a site with a host never takes the address it was reached at. */ + @Test + void aConfiguredBaseUrlWinsOverTheOrigin() { + cfg(Map.of()); + SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), "https://acme.test"); + PageMeta page = new PageMeta("about", "About", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false); + HeadContext ctx = new HeadContext(site, page, Locale.ENGLISH, "https://acme.test/about", + "https://acme.test/about", List.of(), false, false, null, null, "http://10.0.0.5:8080"); + String out = head.render(ctx); + assertTrue(out.contains("https://acme.test/#website"), out); + assertFalse(out.contains("10.0.0.5"), out); + HeadContext noOrigin = new HeadContext(site, page, Locale.ENGLISH, "https://acme.test/about", + "https://acme.test/about", List.of(), false, false); + assertEquals(head.render(noOrigin), out, "byte-identical to the origin-less render of the same page"); + } + + /** A cross-domain canonical override is absolute already and passes through untouched. */ + @Test + void anAbsoluteCanonicalIsNeverRebased() { + assertEquals("https://other.test/x", StructuredDataHead.absolute("https://other.test/x", "http://a.test")); + assertEquals("//cdn.test/x", StructuredDataHead.absolute("//cdn.test/x", "http://a.test"), + "a protocol-relative URL already names a host"); + assertEquals("/x", StructuredDataHead.absolute("/x", ""), "no base known: left as it is"); + assertEquals("http://a.test/x", StructuredDataHead.absolute("/x", "http://a.test")); + } +} diff --git a/plugins/discoverability/src/test/java/mx/quest/discover/TestSettings.java b/plugins/discoverability/src/test/java/mx/quest/discover/TestSettings.java new file mode 100644 index 0000000..b9e5839 --- /dev/null +++ b/plugins/discoverability/src/test/java/mx/quest/discover/TestSettings.java @@ -0,0 +1,58 @@ +package mx.quest.discover; + +import java.io.IOException; +import java.io.Reader; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import mx.quest.runway.spi.testkit.FakePluginSettings; +import org.yaml.snakeyaml.Yaml; + +/** + * Test settings shaped the way the kernel's {@code PluginSettings} hands them to the plugin: the {@code default:}s + * this plugin's descriptor declares, overlaid by what a test stores for a site. + * + *

Every unit test builds its settings here rather than from an empty map, so each assertion also proves that the + * declared defaults change nothing a tenant sees (1.x read only the stored values and applied its code fallbacks; + * since 2.0.0 the host applies the declared defaults first). + */ +final class TestSettings { + + private TestSettings() { + } + + /** A fake {@code PluginSettings} carrying the descriptor's declared per-site defaults and no stored value. */ + static FakePluginSettings declared() { + return new FakePluginSettings().defaults(declaredDefaults()); + } + + /** A fake with NO declared defaults — what the plugin would see if the host stopped applying them. */ + static FakePluginSettings bare() { + return new FakePluginSettings(); + } + + /** The {@code default:} of every {@code siteSettings} key that declares one (secret-typed keys never). */ + @SuppressWarnings("unchecked") + static Map declaredDefaults() { + Map defaults = new LinkedHashMap<>(); + for (Map def : (List>) descriptor().get("siteSettings")) { + if (def.containsKey("default") && def.get("default") != null && !"secret".equals(def.get("type"))) { + defaults.put(String.valueOf(def.get("key")), def.get("default")); + } + } + return defaults; + } + + @SuppressWarnings("unchecked") + static Map descriptor() { + try (Reader in = Files.newBufferedReader(Path.of("plugin.yml"), StandardCharsets.UTF_8)) { + return (Map) new Yaml().load(in); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/plugins/discoverability/static/discoverability-help.html b/plugins/discoverability/static/discoverability-help.html new file mode 100644 index 0000000..a0e128c --- /dev/null +++ b/plugins/discoverability/static/discoverability-help.html @@ -0,0 +1,351 @@ + + + + + + + Discoverability — help + + + +

Discoverability — SEO+ & GEO

+

This plugin makes your site legible to search engines and AI answer engines. + It adds the layer the platform's built-in SEO deliberately leaves out — it never duplicates a tag the kernel + already emits (canonical, hreflang, robots, Open Graph and Twitter cards are already + produced for free).

+ +

What it adds

+ + + + + + + +
SurfaceWhat & where
Structured dataschema.org JSON-LD (WebSite / WebPage + or Article / Organization / BreadcrumbList) injected into every + indexable page's <head>.
Sitemap/sitemap.xml — every published, indexable page with its + hreflang alternates. Pages you mark Exclude from search engines (noindex), and pages whose + canonical URL points elsewhere, are left out on purpose: a sitemap + recommends pages for indexing, so listing one you told robots to skip contradicts itself.
Crawler rules/robots.txt — tells crawlers what they may fetch. Set the + AI-crawler policy below to allow or refuse AI/answer engines, and list any paths to keep + crawlers away from. Refusing AI crawlers never removes you from ordinary web search: the AI opt-out names + the AI agents only (for example Google-Extended, never Googlebot).
GEO · llms.txt/llms.txt — a compact, machine-friendly index of your + pages for LLM / answer engines (opt-in). Honest note: this is a community proposal, not a + standard. No major engine documents reading it, and Google states explicitly that no AI-specific file is + needed to appear in its AI features. It is cheap to publish and harmless; treat it as an optional extra, + not as something your visibility depends on.
GEO · answer schemaA SearchAction (site search) and Speakable hints + that enrich the structured-data graph for AI extraction (opt-in).
+ +

Configure it

+

Everything below is per site, on this plugin's settings page (the site console's Settings menu, + Discoverability (SEO+ & GEO)), and reaches your pages, robots.txt, the sitemap and + /llms.txt at once. The page is in + the same sections as this help; each field carries a one-line explanation, and the Learn more links + land here. Fields that only matter when a switch is on are hidden while it is off (their values are kept).

+

Who can change them. The settings page, and the Discoverability card on the + dashboard, need the permission Manage discoverability (SEO & GEO) + (discoverability|settings). No role holds it until it is granted, so out of the box only the site's + superadmin and administrators have it. Grant it to a role or a user on the site's Permissions + screen.

+

What it takes from the site itself. The site's name is the + WebSite name on every page, the heading of /llms.txt, the name of a local business + that gives none, and the homepage product's name when neither a product name nor an organization name is set. + The site's address (its base URL, else https:// plus its first host name; for a + site with neither, the address the page was requested at) starts every full URL this plugin builds from a path + on the site. The site's languages: each page is described in the + language it is served in, and /llms.txt lists each page once, in the site's default language + (a page that does not exist in it is listed at its own address).

+ +

Structured data for search engines

+

schema.org JSON-LD in every page's <head>: the site (WebSite), + the page (WebPage, or Article for blogs and news), its BreadcrumbList, and + the Organization that publishes it. It is on by default and is the switch everything structured + depends on — the organization, the homepage product, the per-page types and GEO's search action and speakable + hints all disappear while it is off. A page marked Exclude from search engines (noindex) gets no + structured data at all, and is left out of /llms.txt as well as the sitemap. A preview gets no + structured data either.

+
    +
  • Default page type — what every page is described as unless + Per-page types gives it a page type of its own, which then replaces this one + on that page. WebPage (the default) or Article. An Article page + carries the page title as its headline instead of its name; its author, dates + and images come only from an Article, BlogPosting or NewsArticle + block in Per-page types. The form offers only these two; + in a hand-edited settings file, anything but exactly Article means WebPage.
  • +
  • Breadcrumb trail — on by default. Every page except the home page (/), and except a page whose + canonical URL points to another site, gets a trail: Home, then the parent a Per-page types breadcrumb names (if any), then the + page, named by its title (or by its path when the title is blank). The first step is always the English + word Home, whatever the page's language, and links to the site's root. The home page of another + language (/es) is not /, so it gets a two-step trail.
  • +
  • Organization name / logo / profiles — identify the site as an entity (knowledge-graph + signals, shared by search and AI). Leave the name blank to publish no organization. The logo may be a + path on the site (/img/logo.png); it is turned into a full URL for you.
  • +
+ +

Per-page types (content.schema)

+

A small YAML document keyed by URL path that declares what particular pages are, so search engines can show + them (and, for some types, show rich results). Each page also has a line in the page editor's quality panel that + says what it is described as and where that comes from, and the box below this form lists any mistake in this + field. A mistake never stops the form from saving and never breaks a page: unreadable YAML gives no page a + per-page type, and an unknown type is skipped, so check that box after you save. Per-page types need structured + data on, and do nothing on a page marked noindex.

+ +

How a page is matched

+
    +
  • A key is a path pattern starting with /: /pricing matches that page, and a + * at the end matches every path that starts with what comes before it + (/blog/*). It is a plain text prefix: /blog/* does not match /blog + itself (give that page its own key), and /blog* also matches /blogroll; + /* matches every page. An exact path wins over a prefix; among prefixes the longest wins. Only + that one entry applies: an exact entry and a prefix entry are never combined. A * anywhere else + is an ordinary character.
  • +
  • A page is matched by its own URL path (its canonical URL, so a page whose canonical is overridden is matched + by the override). A page whose canonical URL points to another site has no path on this site, so no + pattern that starts with / matches it. A page in another language is matched by its own path + too: /pricing does not reach /es/pricing, because what an entry says (questions, + names, a breadcrumb parent) is written in one language. Give the translated page its own key + (/es/pricing, or /es/* for all of them) with the text in its language; a key such + as /* matches every language's pages. The page editor tells a translated page when the + default language's entry does not reach it.
  • +
  • The value is one type block (type: … plus that type's keys) or a list of blocks when one page + is several things at once. Types and keys are case-sensitive, spelled exactly as below: faqpage + or Price is not recognised.
  • +
  • Quote numbers you mean as text (prices, postal codes): price: "22.00". Unquoted, + 22.00 becomes 22.0.
  • +
  • Any block may add breadcrumb: { name: …, url: … }: the page's breadcrumb trail then shows that + parent between Home and the page. It needs both name and url; a path on the site is + made a full URL. When several blocks give one, the first complete one is used. A block may hold only a + breadcrumb, with no type.
  • +
+ +

Page types: what the page itself is

+

These replace the Default page type on the pages they match; a page has one, the + first listed.

+ + + + + + + + + + + + +
TypeKeys
Article, BlogPosting, NewsArticleheadline (default: the page title) · description (default: the page + description) · image (a list of image URLs; a path on the site is made a full URL) · + author (a name) · datePublished, dateModified + (YYYY-MM-DD; published as written, not checked). A page that knows its own author and dates + (a blog entry) uses those instead. A page with neither a title nor a headline gets none of + these.
FAQPagefaq: a list of { q: question, a: answer }. A pair missing q or + a is left out; with no complete pair the page is still an FAQPage, with no + questions, and the page editor and the box below the form say so.
CollectionPageitems: a list of { name, url }, published as the page's list (an + ItemList that is the page's main entity). An item without url is left out; a + path on the site is made a full URL. With no item that has a url, no list is published, + and the page editor and the box below the form say so.
WebPage, AboutPage, ContactPage, ItemPage, + SearchResultsPagenone: they only name what the page is. WebPage takes a page back to the plain type on a + site whose default is Article. There is no QAPage or + ProfilePage: Google requires each to name its main subject, which a type with no keys + cannot do. Questions you write on the page are an FAQPage.
+ +

Types that add something to the page

+ + + + + + + + + + + + + + +
TypeKeys
Productname (default: the page title) · description (default: the page + description) · image · sku · price (an offer is published only + with a price) · currency (default USD) · availability + (InStock, OutOfStock, PreOrder, … or a full schema.org URL; a word + is put after https://schema.org/, so spell it as schema.org does). The organization, when + named, is the brand. With neither a name nor a page title, no product is published.
Service, ProfessionalServicename (default: the page title) · description (default: the page + description) · serviceType · areaServed (a list) · offers: a + list of { name, price, currency, unit }; an offer without price is left out, + currency defaults to USD, and with unit (for example + month) the price is per that unit. The organization, when named, is the provider. With + neither a name nor a page title, no service is published.
LocalBusiness, CafeOrCoffeeShopname (default: the site name) · street · locality · + region · postalCode · country · telephone · + url · priceRange · latitude, longitude · + hours (a list, for example "Mo-Fr 08:00-17:00") · image. Or + locations: a list of those, one business per location (the keys beside + locations are then not used). url defaults to the page's address. The address is + published only with a street or a locality, the map position only with both + latitude and longitude. Even a block with nothing but its type publishes a + business, named after the site. Only these two type names work.
Personpeople: a list of { name, jobTitle, image, sameAs } + (sameAs: a list of profile URLs). For one person you can put those keys in the block itself, + without people. A person without a name is left out. The organization, when + named, is where they work.
ItemListitems: a list of { name, url }, without changing what the page is. An item + without url is left out; a path on the site is made a full URL. With none that has a + url, nothing is published, and the box below the form says so.
+ +
/pricing:                 # one page, two types
+  - type: FAQPage
+    faq:
+      - { q: "Why ranges?", a: "Scope drives cost." }
+  - type: Service
+    name: "Advisory Sprint"
+    offers:
+      - { name: "Sprint", price: "18000", currency: USD }
+/coffees:                 # a collection page
+  type: CollectionPage
+  items:
+    - { name: "Ethiopia Guji", url: "/coffee-ethiopia-guji" }
+/coffee-ethiopia-guji:    # a product, under its collection in the breadcrumb
+  type: Product
+  price: "22.00"
+  currency: USD
+  breadcrumb: { name: "Coffees", url: "/coffees" }
+/contact:
+  type: ContactPage
+/team:
+  type: Person
+  people: [{ name: "Dana Whitlock", jobTitle: "Founder" }]
+

If a page shows an FAQ (a <details>/<summary> block) that is not declared + here, the page editor's quality check points it out.

+ +

Sitemap and robots.txt

+

/sitemap.xml lists every published, indexable page with its language alternates, and + /robots.txt announces it. Pages marked Exclude from search engines (noindex), and pages + whose canonical URL points elsewhere, are left out on purpose: a sitemap + recommends pages for indexing. Paths crawlers should skip become Disallow: lines for + every crawler; AI crawlers you allow get the same lines, and AI crawlers you refuse are already kept off the + whole site. Write one path per line (or separate them with commas); a / is added in front when you + leave it out, and the path is otherwise written as you typed it. Each line is a prefix, as in every + robots.txt: /drafts also covers /drafts/old and /drafts-2024, + while /drafts/ covers only what is inside it. Crawlers that follow the robots.txt standard + (RFC 9309) also read * as any characters and a final $ as the end of the + address.

+

Custom robots.txt replaces the entire generated file — the + Sitemap: line and the AI-crawler rules included — with exactly what you type. It is for the rare site + that needs rules this page cannot express; if you use it, re-add the Sitemap: line yourself.

+ +

AI crawlers

+

Whether AI companies' crawlers may read the site. Refusing them never removes the site from ordinary web + search: the rules name AI agents only (for example Google-Extended, never Googlebot). + inherit follows the platform's default, and the settings page shows what that currently is.

+

Under Advanced you can decide per class of crawler, because the three classes have opposite + consequences:

+ + + + + + + +
ClassWhat it doesIf you refuse it
TrainingCollects text to train AI models.Costs the site nothing visible.
Answer enginesFetches pages to answer questions (ChatGPT search, Perplexity…).The site stops appearing in those answers.
Person-initiatedA visit someone asked an AI assistant to make.That visit fails.
+

A class left on inherit follows the site's policy above it.

+

The crawlers the rules name, by class:

+ + + + + +
ClassCrawlers
TrainingGPTBot, ClaudeBot, anthropic-ai, + Claude-Web, Google-Extended, CCBot, Bytespider, + Amazonbot, Applebot-Extended, Meta-ExternalAgent, + FacebookBot, cohere-ai, Diffbot, Omgilibot, + Timpibot
Answer enginesOAI-SearchBot, Claude-SearchBot, + PerplexityBot, YouBot
Person-initiatedChatGPT-User, Claude-User, + Perplexity-User
+

A crawler whose role is unclear is counted as training: that is what a site refusing AI crawlers most likely + means. New crawlers appear faster than plugin releases, so the platform operator can add names (Additional + AI crawler names: in the app console, open Plugins and press Settings on the + Discoverability row; a restart applies it). Each line (or comma-separated + entry) is one name, optionally with its class in front: training=NewBot, retrieval=…, + user=… (the class may be written in any case). Spaces, colons and = signs are removed + from the name. A name already listed, in any case, is ignored, so a built-in crawler cannot be moved to another + class. A name without a class follows each site's overall AI policy (or, on a site whose three classes all come out + the same, goes with them); so does one with a misspelt class, which is also logged as a warning.

+ +

AI answer engines (GEO)

+

Opt-in extras for AI assistants: /llms.txt (a compact index of the site, headed by your + site summary), speakable hints (the CSS selectors of the parts of a page worth + reading aloud or quoting) and a SearchAction from the site search URL. The last two + are structured data, so they also need structured data on.

+

Speakable parts: one CSS selector per line (or separate them with commas). Left blank, they are + h1 and main, the default.

+

The site search URL is the address of your results page, as a path or full URL (a value starting with + http is used as it is; anything else is a path on this site). Put {query} (or + {search_term_string}) where the search words go (/search?q={query}); without either, + ?q= is appended, or &q= when the address already has a ?. Blank + publishes no search action.

+

Honest note: llms.txt is a community proposal, not a standard. No major engine documents + reading it, and Google states that no AI-specific file is needed to appear in its AI features. It is cheap and + harmless; treat it as an optional extra.

+ +

Product on the homepage

+

For a site that presents a software product: a SoftwareApplication on the homepage only (and on + the home page of each other language, such as /es), published by the organization. It needs + structured data on. A blank name uses the organization's (or the site's), a blank description the homepage's, + a blank URL the homepage; a price of 0 means free, and a blank price publishes no offer. A blank + operating system means Web and a blank currency USD, the defaults; neither is checked, + so write them as schema.org expects (a currency as its three-letter code). The license, product and screenshot + URLs are published exactly as you write them: use full URLs (https://…), because a path such as + /license stays a path, which search engines do not accept.

+ +

Notify search engines of changes (IndexNow)

+

When a page is published, changed or removed, the site tells the engines that use IndexNow — Bing, Yandex, + Seznam, Naver and Yep. Google does not use IndexNow. It needs two switches: the platform + operator's (this server then makes outbound requests) and this site's. The settings page tells you when the + platform's is off.

+

The key is any random string of 8 to 128 letters, digits or dashes — the protocol's rule. It + is published at /indexnow-key.txt so the engines can check the site is yours. Nothing is sent + until a key is set.

+

IndexNow also needs the site's own address: a site with neither a base URL nor a host name (such as the + platform's catch-all default site) never sends anything, and nothing warns about it.

+

For the platform operator. Besides the switch, this plugin's platform + settings (app console, Plugins, Settings on the Discoverability row) hold the endpoint and four + limits. The form accepts only the ranges below; a value written by hand in the settings file + (external/plugin-settings/discoverability.yml) or in application.yml is not + range-checked, so keep to them. A restart applies any change.

+ + + + + + +
SettingDefaultRangeWhat it does
Seconds to gather changes605–3600Changes are collected for this long, then + each site's are sent in one submission. Set by hand, a value below 5 counts as 5 and one above 3600 as 3600.
Maximum URLs per submission10001–10000The rest of a batch is not sent (a + warning is logged); those pages are still crawled the ordinary way. Set by hand, a value below 1 counts as + 1.
Maximum URLs queued per site50001–100000Once a site has this many waiting, + further changes are dropped until the next submission (a warning is logged). Set by hand, a value below 1 + counts as 1.
Submission timeout (seconds)101–120How long to wait for the endpoint before a + submission is given up (it is not retried). Set by hand, a value below 1 counts as 1.
+ +

Verify it

+
    +
  • View any public page's source — look for <script type="application/ld+json">.
  • +
  • Open /sitemap.xml and /llms.txt (the latter only when GEO is enabled).
  • +
  • Open /robots.txt and read it: check the AI-crawler group matches the policy you chose, and + that any paths you excluded appear as Disallow: lines under User-agent: * and in + every AI group you allow (a refused AI group is a single Disallow: /, which already covers + them).
  • +
  • Paste a page URL into Google's Rich Results Test to see the structured data recognized.
  • +
+ +

Editing these settings affects your live site immediately (no restart). Only this site is + affected — every site configures its own discoverability. A few things are the platform operator's, apply to + every site and change only on a restart: the default AI-crawler policy that inherit follows, the + list of extra AI crawler names, and whether IndexNow is allowed at all.

+ + diff --git a/plugins/discoverability/templates/admin.html b/plugins/discoverability/templates/admin.html new file mode 100644 index 0000000..7820afd --- /dev/null +++ b/plugins/discoverability/templates/admin.html @@ -0,0 +1,36 @@ + +
+

Discoverability status

+
+
+
+
Structured data
+
on (WebPage)
+
+
+
Sitemap
+ +
+
+
GEO · llms.txt
+
off
+
+
+
Pages in sitemap
+
0
+
+
+
+
Per-page types check
+
No problems found.
+
  • problem
+
+

+ These surfaces enrich the head/response layer; the kernel already emits canonical, hreflang and robots.

+
+ +
diff --git a/plugins/discoverability/templates/admin.th.xml b/plugins/discoverability/templates/admin.th.xml new file mode 100644 index 0000000..af24ae2 --- /dev/null +++ b/plugins/discoverability/templates/admin.th.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/discoverability/templates/dashboard.html b/plugins/discoverability/templates/dashboard.html new file mode 100644 index 0000000..f518afb --- /dev/null +++ b/plugins/discoverability/templates/dashboard.html @@ -0,0 +1,18 @@ + +
+
+
+
+ +
+
Discoverability
+
+ 0 pages + · JSON-LD on + · GEO off +
+
+
+
+
diff --git a/plugins/discoverability/templates/dashboard.th.xml b/plugins/discoverability/templates/dashboard.th.xml new file mode 100644 index 0000000..edf4b67 --- /dev/null +++ b/plugins/discoverability/templates/dashboard.th.xml @@ -0,0 +1,10 @@ + + + + + + + + + diff --git a/plugins/search-lucene/scripts/verify-against-host.sh b/plugins/search-lucene/scripts/verify-against-host.sh index 5f2fd65..5e56ef5 100755 --- a/plugins/search-lucene/scripts/verify-against-host.sh +++ b/plugins/search-lucene/scripts/verify-against-host.sh @@ -46,7 +46,7 @@ MVN="${MVN:-mvn}" # Default host: the kernel at the root of the repository this plugin sits in (plugins//), 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" + if [ -f "$HERE/../../runway-app/pom.xml" ]; then HOST_TARGET="$HERE/../../runway-app/target" else HOST_TARGET="$HERE/../../runway/runway-app/target"; fi fi BASELINE_REF="${BASELINE_REF:-}" diff --git a/plugins/search/CHANGELOG.md b/plugins/search/CHANGELOG.md index 3285ced..611f435 100644 --- a/plugins/search/CHANGELOG.md +++ b/plugins/search/CHANGELOG.md @@ -2,6 +2,20 @@ All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/). +## [2.3.1] — 2026-10-21 + +### Added + +- **French for visitors.** `messages_fr.properties` carries the strings visitors see — the search box (placeholder + and button), the results heading, the result count, "no results" and the rate-limit notice — so a French page + shows them in French instead of falling back to English. The console's strings stay in English and Spanish, the + languages the console offers. A site's own `messages_fr.properties` still overrides any of them. + +### Upgrade + +Replace the plugin folder with this release's zip and restart. No setting or stored file changes; search-lucene +3.3.0 works with it unchanged. + ## [2.3.0] — 2026-10-21 First public release of `search`: on-site search with a search-box widget that renders results on an editable diff --git a/plugins/search/README.md b/plugins/search/README.md index 99271a4..694a583 100644 --- a/plugins/search/README.md +++ b/plugins/search/README.md @@ -37,7 +37,7 @@ export JAVA_HOME=/path/to/jdk-25 mvn -q verify # → target/runway-plugin-search.jar # target/search/ (cp -r into /plugins/ and restart) -# target/runway-plugin-search-2.3.0.zip (upload at /__app/plugins → install) +# target/runway-plugin-search-2.3.1.zip (upload at /__app/plugins → install) HOST_JAR=/path/to/runway/runway-app/target/runway-app--exec.jar \ JAVA_HOME=/path/to/jdk-25 scripts/verify-against-host.sh # boots the PACKAGED host and proves the contract live ``` diff --git a/plugins/search/i18n/messages_fr.properties b/plugins/search/i18n/messages_fr.properties new file mode 100644 index 0000000..ad899bc --- /dev/null +++ b/plugins/search/i18n/messages_fr.properties @@ -0,0 +1,9 @@ +# Runway Search plugin — French strings for what visitors see (the search box and the results). The console's +# strings stay in English and Spanish, the languages the console offers. + +search.box.placeholder=Rechercher… +search.box.submit=Rechercher +search.results.heading=Recherche +search.results.none=Aucun résultat pour +search.results.count=résultat(s) pour +search.rate.limited=Trop de recherches — veuillez réessayer dans un instant. diff --git a/plugins/search/plugin.yml b/plugins/search/plugin.yml index db2e1ae..bf8e91e 100644 --- a/plugins/search/plugin.yml +++ b/plugins/search/plugin.yml @@ -14,7 +14,7 @@ # ============================================================================= id: search name: Search -version: 2.3.0 +version: 2.3.1 # The @Configuration registered into the host context before refresh. Its package (mx.quest.search) lives # OUTSIDE mx.quest.runway so the host never double-scans it. Beans are wired EXPLICITLY (no @ComponentScan). diff --git a/plugins/search/pom.xml b/plugins/search/pom.xml index ae7488e..6863454 100644 --- a/plugins/search/pom.xml +++ b/plugins/search/pom.xml @@ -20,7 +20,7 @@ mx.quest runway-plugin-search - 2.3.0 + 2.3.1 jar Runway Search Plugin @@ -45,7 +45,7 @@ - 2026-10-21T17:23:00Z + 2026-10-21T19:31:00Z 1.0.0 diff --git a/plugins/search/scripts/verify-against-host.sh b/plugins/search/scripts/verify-against-host.sh index 3018fe7..01e1351 100755 --- a/plugins/search/scripts/verify-against-host.sh +++ b/plugins/search/scripts/verify-against-host.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # Build this plugin, drop it into a throwaway Runway deployment, boot the PACKAGED host in ACTIVE mode, and prove -# the search 2.1.1 contract end to end (SPI 0.6.0): +# this release's contract end to end: # - it loads with ZERO host-linkage and bean-name/surface warnings, and its app-level settings bind; # - the JSON API serves results anonymously; there is no plugin-owned /search page until one is installed; # - the three operator actions are CSRF-protected POSTs: a GET (a cross-site link or ) changes nothing even @@ -43,7 +43,7 @@ MVN="${MVN:-mvn}" # Default host: the kernel at the root of the repository this plugin sits in (plugins//), 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" + if [ -f "$HERE/../../runway-app/pom.xml" ]; then HOST_TARGET="$HERE/../../runway-app/target" else HOST_TARGET="$HERE/../../runway/runway-app/target"; fi fi @@ -114,9 +114,10 @@ make_site enforced enforced make_site reviewed reviewed sed -i 's/^ - "default"$/ - "default"\n - "enforced"\n - "reviewed"/' "$EXT/site-users.yml" # A bilingual page whose visible copy comes ONLY from the site's bundles (decoupled th:text): the template holds an -# empty element. Kernel 1.0.0-rc6+ indexes the page as rendered in each language; search 2.2.0+ searches each -# language's own documents (on 2.1.1 + rc5, "facultad" found nothing). +# empty element. The kernel indexes the page as rendered in each language, and search searches each language's +# own documents. French is a site language too, for the visitor strings the plugin ships in French. sed -i '/^locales:/a - "es"' "$SITES/default/site.yml" +sed -i '/^locales:/a - "fr"' "$SITES/default/site.yml" T="$SITES/default/templates" cat > "$T/faculty.html" <<'HTML' Faculty @@ -129,6 +130,13 @@ cat > "$T/faculty.th.xml" <<'XML' XML printf 'path: /faculty\nlocalizedPaths:\n es: /facultad\nlocales: [en, es]\ntitle:\n en: Faculty\n es: Profesores\n' > "$T/faculty.meta.yml" +# A page carrying the search box in French as well (a French site's results page), to prove the plugin's French +# visitor strings are used there rather than English. +cat > "$T/recherche.html" <<'HTML' +Recherche +
+HTML +printf 'path: /find\nlocalizedPaths:\n fr: /recherche\nlocales: [en, fr]\ntitle:\n en: Find\n fr: Recherche\n' > "$T/recherche.meta.yml" mkdir -p "$SITES/default/i18n" printf '\nverify.faculty=Our students learn from a faculty of researchers.\n' >> "$SITES/default/i18n/messages.properties" printf '\nverify.faculty=Nuestros alumnos aprenden con una facultad de excelencia.\n' >> "$SITES/default/i18n/messages_es.properties" @@ -179,8 +187,8 @@ fi curl -s -D "$SCRATCH/home.headers" "$BASE/" > "$SCRATCH/home.html" ck "every page carries the loader script, stamped with the nonce the kernel's CSP allows" \ "n=\$(grep -oE '