Commit 02bef8e4 authored by jan.koester's avatar jan.koester
Browse files

Serve /.well-known/ai-catalog.json (AI Catalog draft spec)

A validator flagged ai-catalog.json as invalid: /.well-known/ai-catalog.json
returned the HTML 404 page. blogi now generates it per
https://ai-catalog.io/spec/ (specVersion "1.0", host, entries):

- served under the blog prefix (/blog/.well-known/ai-catalog.json) and,
  since blogi also answers "/", at /.well-known/ai-catalog.json
- Content-Type application/ai-catalog+json (UTF-8 JSON via json-c)
- host.displayName = SITE_TITLE (fallback: domain), host.identifier = domain
- entries only for endpoints blogi really serves: sitemap.xml
  (application/xml) and llms.txt (text/plain, as served); identifiers
  urn:air:{domain}:{prefix or "site"}:{sitemap|llms-txt}; every entry
  has url (never data); URLs via Config::absoluteurl (no doubled /blog,
  no :443/:80)
- <link rel="ai-catalog" type="application/ai-catalog+json"> in the head
  next to the canonical link

Own choice, the spec sets none: Access-Control-Allow-Origin: * and
Cache-Control: public, max-age=3600.

Also installs siteurl.h (conf.h includes it since e34ba9d6, so out-of-tree
plugin builds against the installed headers needed it).

Adds tests/aicatalog_test (valid JSON, required fields, url xor data, no
unknown fields, no /blog/blog or default ports).

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent 6e3a750c
Loading
Loading
Loading
Loading
+3 −2
Changes for src/CMakeLists.txt: 3 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -7,6 +7,7 @@ add_library(blogidev STATIC
    session.cpp
    auth.cpp
    conf.cpp
    aicatalog.cpp
    plugin.cpp
    theme.cpp
    cookie.cpp
@@ -44,8 +45,8 @@ endif()

install(TARGETS blogidev DESTINATION lib/blogi)
install(FILES
    api.h auth.h blogi.h compress.h conf.h cookie.h
    i18n.h mail.h plugin.h seo.h session.h theme.h translations.h
    aicatalog.h api.h auth.h blogi.h compress.h conf.h cookie.h
    i18n.h mail.h plugin.h seo.h session.h siteurl.h theme.h translations.h
    DESTINATION include/blogi
)

src/aicatalog.cpp

0 → 100644
+81 −0
Changes for src/aicatalog.cpp: 81 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*******************************************************************************
 * Copyright (c) 2026, Jan Koester jan.koester@gmx.net
 * All rights reserved. See conf.h for the full license text (BSD-3-Clause).
 *******************************************************************************/

#include "aicatalog.h"

#include <json-c/json.h>

std::string blogi::aicatalog::domainOf(const std::string &siteUrl) {
    size_t start = siteUrl.find("://");
    start = start == std::string::npos ? 0 : start + 3;
    size_t end = siteUrl.find_first_of("/?#", start);
    std::string host = siteUrl.substr(start, end == std::string::npos ? std::string::npos : end - start);
    size_t at = host.rfind('@');
    if (at != std::string::npos) host.erase(0, at + 1);
    if (!host.empty() && host[0] == '[') {
        size_t close = host.find(']');
        host = host.substr(1, close == std::string::npos ? std::string::npos : close - 1);
    } else {
        size_t colon = host.rfind(':');
        if (colon != std::string::npos) host.erase(colon);
    }
    for (char &c : host) if (c >= 'A' && c <= 'Z') c = char(c - 'A' + 'a');
    return host;
}

std::string blogi::aicatalog::namespaceOf(const std::string &prefix) {
    std::string ns;
    for (char c : prefix) {
        if (c == '/') { if (!ns.empty() && ns.back() != '-') ns += '-'; continue; }
        if (c >= 'A' && c <= 'Z') c = char(c - 'A' + 'a');
        bool ok = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '.' || c == '_';
        ns += ok ? c : '-';
    }
    while (!ns.empty() && ns.front() == '-') ns.erase(0, 1);
    while (!ns.empty() && ns.back() == '-') ns.pop_back();
    return ns.empty() ? "site" : ns;
}

std::string blogi::aicatalog::build(const std::string &siteUrl, const std::string &prefix,
                                    const std::string &displayName,
                                    const std::vector<Entry> &entries) {
    const std::string domain = domainOf(siteUrl);
    const std::string ns = namespaceOf(prefix);

    json_object *root = json_object_new_object();
    json_object_object_add(root, "specVersion", json_object_new_string("1.0"));

    json_object *host = json_object_new_object();
    json_object_object_add(host, "displayName",
        json_object_new_string(displayName.empty() ? domain.c_str() : displayName.c_str()));
    if (!domain.empty())
        json_object_object_add(host, "identifier", json_object_new_string(domain.c_str()));
    json_object_object_add(root, "host", host);

    json_object *jentries = json_object_new_array();
    for (const auto &e : entries) {
        json_object *je = json_object_new_object();
        std::string id = "urn:air:" + domain + ":" + ns + ":" + e.name;
        json_object_object_add(je, "identifier", json_object_new_string(id.c_str()));
        json_object_object_add(je, "type", json_object_new_string(e.type.c_str()));
        json_object_object_add(je, "url", json_object_new_string(e.url.c_str()));
        if (!e.displayName.empty())
            json_object_object_add(je, "displayName", json_object_new_string(e.displayName.c_str()));
        if (!e.description.empty())
            json_object_object_add(je, "description", json_object_new_string(e.description.c_str()));
        if (!e.tags.empty()) {
            json_object *jt = json_object_new_array();
            for (const auto &t : e.tags) json_object_array_add(jt, json_object_new_string(t.c_str()));
            json_object_object_add(je, "tags", jt);
        }
        json_object_array_add(jentries, je);
    }
    json_object_object_add(root, "entries", jentries);

    std::string out = json_object_to_json_string_ext(root,
        JSON_C_TO_STRING_PRETTY | JSON_C_TO_STRING_SPACED | JSON_C_TO_STRING_NOSLASHESCAPE);
    json_object_put(root);
    return out;
}

src/aicatalog.h

0 → 100644
+44 −0
Changes for src/aicatalog.h: 44 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*******************************************************************************
 * Copyright (c) 2026, Jan Koester jan.koester@gmx.net
 * All rights reserved. See conf.h for the full license text (BSD-3-Clause).
 *******************************************************************************/

#pragma once

#include <string>
#include <vector>

namespace blogi {

    // /.well-known/ai-catalog.json per the AI Catalog draft
    // (https://ai-catalog.io/spec/): {specVersion, host?, entries[]}, served
    // as application/ai-catalog+json.
    namespace aicatalog {

        constexpr const char *ContentType = "application/ai-catalog+json";
        constexpr const char *WellKnownPath = ".well-known/ai-catalog.json";

        struct Entry {
            std::string name;        // last urn segment, e.g. "sitemap"
            std::string type;        // media type of the resource
            std::string url;         // absolute URL (this generator never emits `data`)
            std::string displayName;
            std::string description;
            std::vector<std::string> tags;
        };

        // Host name (no scheme/port/path) of an absolute URL, lower-cased;
        // the urn:air:{domain}:... identifier and host.identifier use it.
        std::string domainOf(const std::string &siteUrl);

        // urn:air namespace for a blog mounted at `prefix`: "/blog" -> "blog",
        // "" or "/" -> "site".
        std::string namespaceOf(const std::string &prefix);

        // Serializes the catalog. `displayName` falls back to the domain;
        // identifiers are urn:air:{domain}:{namespace}:{entry.name}.
        std::string build(const std::string &siteUrl, const std::string &prefix,
                          const std::string &displayName,
                          const std::vector<Entry> &entries);
    }
}
+43 −0
Changes for src/blogi.cpp: 43 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -83,6 +83,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "setup.h"
#endif
#include "conf.h"
#include "aicatalog.h"
#include "i18n.h"

#include "blogi.h"
@@ -3290,6 +3291,37 @@ void blogi::Blogi::llmsTxtRoot(libhttppp::HttpRequest &curreq, const int tid, co
    curres.send(curreq, out.str());
};

// /.well-known/ai-catalog.json (https://ai-catalog.io/spec/): lists the
// machine-readable endpoints blogi really serves -- sitemap.xml and
// llms.txt -- with absolute URLs built like canonical links.
void blogi::Blogi::aiCatalog(libhttppp::HttpRequest &curreq, const int tid, DomainContext &ctx)
{
    auto &PlgArgs = ctx.plgArgs;
    const blogi::Config &cfg = *PlgArgs->config;

    std::string siteTitle;
    try { getConfig(*PlgArgs->database[tid], "SITE_TITLE", siteTitle); } catch (...) {}
    for (char &c : siteTitle) if (c == '\r' || c == '\n' || c == '\t') c = ' ';

    std::vector<blogi::aicatalog::Entry> entries;
    entries.push_back({"sitemap", "application/xml", cfg.absoluteurl(ctx.buildurl("sitemap.xml")),
                       "Sitemap", "XML sitemap of all public pages and posts", {"sitemap"}});
    entries.push_back({"llms-txt", "text/plain", cfg.absoluteurl(ctx.buildurl("llms.txt")),
                       "llms.txt", "Markdown overview of the site for language models (https://llmstxt.org/)",
                       {"llms.txt"}});

    const std::string body = blogi::aicatalog::build(cfg.getsiteurl(), ctx.prefix, siteTitle, entries);

    libhttppp::HttpResponse resp;
    resp.setState(HTTP200);
    resp.setContentType(blogi::aicatalog::ContentType);
    // Own choice, the spec sets no caching/CORS rules: public discovery
    // document, readable cross-origin, re-fetched hourly.
    resp.setHeaderData("access-control-allow-origin")->push_back("*");
    resp.setHeaderData("cache-control")->push_back("public, max-age=3600");
    resp.send(curreq, body);
}

void blogi::Blogi::RequestEvent(libhttppp::HttpRequest &curreq, const int tid, ULONG_PTR args)
{
#ifndef _WIN32
@@ -3359,6 +3391,17 @@ void blogi::Blogi::RequestEvent(libhttppp::HttpRequest &curreq, const int tid, U
            std::cout << std::endl;
        int retries = 0;
    RETRY_REQUEST:
        {
            // under the blog prefix and, since blogi also answers "/", at the root
            std::string path = curreq.getRequestURL();
            path = path.substr(0, path.find_first_of("?#"));
            if (path == ctx->buildurl(blogi::aicatalog::WellKnownPath) ||
                path == std::string("/") + blogi::aicatalog::WellKnownPath)
            {
                aiCatalog(curreq, tid, *ctx);
                return;
            }
        }
        if (curreq.getRequestURL().rfind("robots.txt") != std::string::npos)
        {
            std::string robot = "user-agent: *\r\ndisallow: /blog/settings/";
+1 −0
Changes for src/blogi.h: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
@@ -78,6 +78,7 @@ namespace blogi {
        void searchPage(libhttppp::HttpRequest &curreq,const int tid,const std::string &sessionid,libhtmlpp::HtmlElement &index, DomainContext &ctx);
        void sitemapXML(libhttppp::HttpRequest& curreq, const int tid, const std::string &sessionid, DomainContext &ctx);
        void llmsTxtRoot(libhttppp::HttpRequest& curreq, const int tid, const std::string &sessionid, DomainContext &ctx);
        void aiCatalog(libhttppp::HttpRequest& curreq, const int tid, DomainContext &ctx);
        void RequestEvent(libhttppp::HttpRequest &curreq,const int tid,ULONG_PTR args);
        void ResponseEvent(libhttppp::HttpRequest &curreq,const int tid,ULONG_PTR args);
        void DisconnectEvent(libhttppp::HttpRequest &curreq,const int tid,ULONG_PTR args);
Loading