fromWireName(String wireName) {
+ return Arrays.stream(values()).filter(action -> action.wireName().equals(wireName)).findFirst();
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/ConfigurationLoader.java b/trailhand/src/main/java/de/cuioss/trailhand/config/ConfigurationLoader.java
new file mode 100644
index 0000000..8f100ff
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/config/ConfigurationLoader.java
@@ -0,0 +1,393 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.config;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
+import de.cuioss.tools.logging.CuiLogger;
+import org.jspecify.annotations.Nullable;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Duration;
+import java.time.Period;
+import java.time.format.DateTimeParseException;
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.UnaryOperator;
+import java.util.regex.Pattern;
+
+import static de.cuioss.trailhand.TrailhandLogMessages.ERROR;
+import static de.cuioss.trailhand.TrailhandLogMessages.INFO;
+
+/**
+ * Loads and validates {@code trailhand.yaml} (TRH-CONF-1, TRH-CONF-2).
+ *
+ * Placeholders are resolved from the environment first; then every rule runs and every violation is collected, so
+ * one run names them all. The bootstrap validates the keys the application uses so far ({@code repositories},
+ * {@code rights}, {@code oidc}, {@code web}, {@code fetch}); the validation against the bundled JSON Schema follows
+ * with the remaining keys.
+ */
+public class ConfigurationLoader {
+
+ private static final CuiLogger LOGGER = new CuiLogger(ConfigurationLoader.class);
+
+ /** The name of the policy file in the configuration directory. */
+ public static final String FILE_NAME = "trailhand.yaml";
+
+ private static final Pattern ALIAS = Pattern.compile("[a-z0-9-]+");
+ private static final Set CONFIDENTIALITY = Set.of("public-internal", "restricted", "strongly-restricted");
+ /** The reference forms that can be resolved; {@code vault:} joins with the Vault adapter. */
+ private static final List REFERENCE_FORMS = List.of("file:");
+ private static final String MUST_BE_MAPPING = "must be a mapping";
+ private static final String ALIAS_KEY = ".alias";
+ private static final String CREDENTIAL_KEY = ".credential-ref";
+
+ private final UnaryOperator environment;
+
+ /**
+ * @param environment the environment the placeholders are resolved from
+ */
+ public ConfigurationLoader(UnaryOperator environment) {
+ this.environment = environment;
+ }
+
+ /**
+ * @return a loader reading the process environment
+ */
+ public static ConfigurationLoader fromProcessEnvironment() {
+ return new ConfigurationLoader(System::getenv);
+ }
+
+ /**
+ * Loads {@code trailhand.yaml} from a directory and logs one ERROR record per violation.
+ *
+ * @param directory the configuration directory
+ * @return the configuration or the violations
+ */
+ public ConfigurationResult load(Path directory) {
+ var file = directory.resolve(FILE_NAME);
+ Object tree;
+ try {
+ if (!Files.isRegularFile(file)) {
+ return report(List.of(new Violation(FILE_NAME, "the file is missing")));
+ }
+ tree = new ObjectMapper(new YAMLFactory()).readValue(file.toFile(), Object.class);
+ } catch (IOException e) {
+ return report(List.of(new Violation(FILE_NAME, "the file is no valid YAML")));
+ }
+ return report(directory, validate(tree));
+ }
+
+ /**
+ * Validates a parsed tree, without logging.
+ *
+ * @param tree the YAML content as maps, lists and scalars
+ * @return the configuration or the violations
+ */
+ @SuppressWarnings("unchecked")
+ public ConfigurationResult validate(@Nullable Object tree) {
+ var violations = new ArrayList();
+ if (!(tree instanceof Map, ?>)) {
+ return new ConfigurationResult(null, List.of(new Violation(FILE_NAME, "the document is no mapping")));
+ }
+ var unresolved = new ArrayList();
+ var root = (Map) Placeholders.resolveTree(tree, environment, unresolved);
+ for (String name : unresolved) {
+ violations.add(new Violation("${" + name + "}", "the placeholder has no value and no default"));
+ }
+ var reader = new Reader(root, violations);
+ var repositories = reader.repositories();
+ var aliases = new HashSet();
+ repositories.forEach(repository -> aliases.add(repository.alias()));
+ var rights = reader.rights(aliases);
+ var oidc = reader.oidc();
+ var web = reader.web();
+ var fetch = reader.duration(reader.map(root, "fetch", false), "fetch.interval", "interval",
+ TrailhandConfiguration.DEFAULT_FETCH_INTERVAL);
+ if (!violations.isEmpty() || oidc == null || web == null) {
+ return new ConfigurationResult(null, violations);
+ }
+ return new ConfigurationResult(new TrailhandConfiguration(repositories, rights, oidc, web, fetch), List.of());
+ }
+
+ private static ConfigurationResult report(List violations) {
+ for (Violation violation : violations) {
+ LOGGER.error(ERROR.CONFIGURATION_VIOLATION, violation.key(), violation.rule());
+ }
+ return new ConfigurationResult(null, violations);
+ }
+
+ private ConfigurationResult report(Path directory, ConfigurationResult result) {
+ var configuration = result.configuration();
+ if (result.isValid() && configuration != null) {
+ LOGGER.info(INFO.CONFIGURATION_LOADED, directory, configuration.repositories().size());
+ return result;
+ }
+ return report(result.violations());
+ }
+
+ /** Reads typed values from the tree and records a violation for every problem. */
+ private static final class Reader {
+
+ private final Map root;
+ private final List violations;
+
+ Reader(Map root, List violations) {
+ this.root = root;
+ this.violations = violations;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Nullable
+ Map map(@Nullable Map parent, String key, boolean required) {
+ var value = parent == null ? null : parent.get(key);
+ if (value instanceof Map, ?> map) {
+ return (Map) map;
+ }
+ if (value != null || required) {
+ violations.add(new Violation(key, value == null ? "is required" : MUST_BE_MAPPING));
+ }
+ return null;
+ }
+
+ @Nullable
+ String text(@Nullable Map parent, String path, String key, boolean required) {
+ var value = parent == null ? null : parent.get(key);
+ if (value instanceof String text && !text.isBlank()) {
+ return text.trim();
+ }
+ if (value != null || required) {
+ violations.add(new Violation(path, value == null ? "is required" : "must be a non-empty string"));
+ }
+ return null;
+ }
+
+ Duration duration(@Nullable Map parent, String path, String key, Duration fallback) {
+ var text = text(parent, path, key, false);
+ if (text == null) {
+ return fallback;
+ }
+ try {
+ var duration = Duration.parse(text);
+ if (duration.isNegative() || duration.isZero()) {
+ violations.add(new Violation(path, "must be a positive ISO 8601 duration"));
+ return fallback;
+ }
+ return duration;
+ } catch (DateTimeParseException e) {
+ violations.add(new Violation(path, "must be an ISO 8601 duration such as PT5M"));
+ return fallback;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ List repositories() {
+ var value = root.get("repositories");
+ if (!(value instanceof List> list) || list.isEmpty()) {
+ violations.add(new Violation("repositories", "must be a non-empty list"));
+ return List.of();
+ }
+ var result = new ArrayList();
+ var seen = new HashSet();
+ for (int index = 0; index < list.size(); index++) {
+ var path = "repositories[" + index + "]";
+ if (!(list.get(index) instanceof Map, ?> entry)) {
+ violations.add(new Violation(path, MUST_BE_MAPPING));
+ continue;
+ }
+ var repository = repository((Map) entry, path, seen);
+ if (repository != null) {
+ result.add(repository);
+ }
+ }
+ return result;
+ }
+
+ @Nullable
+ private RepositorySettings repository(Map entry, String path, Set seen) {
+ int before = violations.size();
+ var alias = text(entry, path + ALIAS_KEY, "alias", true);
+ if (alias != null && !ALIAS.matcher(alias).matches()) {
+ violations.add(new Violation(path + ALIAS_KEY, "must match [a-z0-9-]+"));
+ } else if (alias != null && !seen.add(alias)) {
+ violations.add(new Violation(path + ALIAS_KEY, "is used by another repository"));
+ }
+ var remote = text(entry, path + ".remote", "remote", true);
+ if (remote != null && !remote.startsWith("https://") && !remote.startsWith("file:")) {
+ violations.add(new Violation(path + ".remote", "must be an https or a file: URL"));
+ }
+ var confidentiality = text(entry, path + ".confidentiality", "confidentiality", true);
+ if (confidentiality != null && !CONFIDENTIALITY.contains(confidentiality)) {
+ violations.add(new Violation(path + ".confidentiality",
+ "must be public-internal, restricted or strongly-restricted"));
+ }
+ var retention = retention(text(entry, path + ".retention", "retention", true), path + ".retention");
+ var credentialRef = text(entry, path + CREDENTIAL_KEY, "credential-ref", false);
+ if (remote != null && remote.startsWith("https://") && credentialRef == null) {
+ violations.add(new Violation(path + CREDENTIAL_KEY, "is required for an https remote"));
+ }
+ reference(credentialRef, path + CREDENTIAL_KEY);
+ if (violations.size() > before || alias == null || remote == null || confidentiality == null) {
+ return null;
+ }
+ return new RepositorySettings(alias, remote, confidentiality, retention, credentialRef);
+ }
+
+ @Nullable
+ private Period retention(@Nullable String text, String path) {
+ if (text == null || "unlimited".equals(text)) {
+ return null;
+ }
+ try {
+ return Period.parse(text);
+ } catch (DateTimeParseException e) {
+ violations.add(new Violation(path, "must be unlimited or an ISO 8601 period such as P10Y"));
+ return null;
+ }
+ }
+
+ private void reference(@Nullable String reference, String path) {
+ if (reference != null && REFERENCE_FORMS.stream().noneMatch(reference::startsWith)) {
+ violations.add(new Violation(path, reference.startsWith("vault:")
+ ? "vault: references are not supported yet (the Vault adapter is not built); use file:"
+ : "must be a reference: file:"));
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ Map> rights(Set aliases) {
+ var rights = map(root, "rights", true);
+ var result = new LinkedHashMap>();
+ if (rights == null) {
+ return result;
+ }
+ rights.forEach((group, value) -> {
+ var path = "rights." + group;
+ if (!(value instanceof List> list)) {
+ violations.add(new Violation(path, "must be a list"));
+ return;
+ }
+ var entries = new ArrayList();
+ for (int index = 0; index < list.size(); index++) {
+ var entryPath = path + "[" + index + "]";
+ if (!(list.get(index) instanceof Map, ?> entry)) {
+ violations.add(new Violation(entryPath, MUST_BE_MAPPING));
+ continue;
+ }
+ var right = right((Map) entry, entryPath, aliases);
+ if (right != null) {
+ entries.add(right);
+ }
+ }
+ result.put(group, entries);
+ });
+ return result;
+ }
+
+ @Nullable
+ private RightSettings right(Map entry, String path, Set aliases) {
+ var repository = text(entry, path + ".repository", "repository", true);
+ if (repository != null && !aliases.contains(repository)) {
+ violations.add(new Violation(path + ".repository", "names no configured repository"));
+ }
+ var actions = EnumSet.noneOf(Action.class);
+ if (!(entry.get("actions") instanceof List> list) || list.isEmpty()) {
+ violations.add(new Violation(path + ".actions", "must be a non-empty list"));
+ return null;
+ }
+ for (Object action : list) {
+ var parsed = action instanceof String name ? Action.fromWireName(name) : Optional.empty();
+ if (parsed.isEmpty()) {
+ violations.add(new Violation(path + ".actions",
+ "must hold read, edit, approve or administer-catalogs"));
+ } else {
+ actions.add(parsed.get());
+ }
+ }
+ return repository == null ? null : new RightSettings(repository, actions);
+ }
+
+ @Nullable
+ OidcSettings oidc() {
+ var oidc = map(root, "oidc", true);
+ if (oidc == null) {
+ return null;
+ }
+ var issuer = text(oidc, "oidc.issuer", "issuer", true);
+ if (issuer != null && httpsUri(issuer, false) == null) {
+ violations.add(new Violation("oidc.issuer", "must be an absolute https URI"));
+ }
+ var clientId = text(oidc, "oidc.client-id", "client-id", true);
+ var credential = text(oidc, "oidc.client-credential-ref", "client-credential-ref", true);
+ reference(credential, "oidc.client-credential-ref");
+ var groups = text(oidc, "oidc.groups-claim", "groups-claim", false);
+ if (issuer == null || clientId == null || credential == null) {
+ return null;
+ }
+ return new OidcSettings(issuer, clientId, credential,
+ groups == null ? OidcSettings.DEFAULT_GROUPS_CLAIM : groups);
+ }
+
+ @Nullable
+ WebSettings web() {
+ var web = map(root, "web", true);
+ if (web == null) {
+ return null;
+ }
+ var originText = text(web, "web.origin", "origin", true);
+ var origin = originText == null ? null : httpsUri(originText, true);
+ if (originText != null && origin == null) {
+ violations.add(new Violation("web.origin", "must be an https origin without path, query or fragment"));
+ }
+ var session = map(web, "session", false);
+ var idle = duration(session, "web.session.idle-timeout", "idle-timeout", WebSettings.DEFAULT_IDLE_TIMEOUT);
+ var max = duration(session, "web.session.max-lifetime", "max-lifetime", WebSettings.DEFAULT_MAX_LIFETIME);
+ if (idle.compareTo(max) > 0) {
+ violations.add(new Violation("web.session.idle-timeout", "must not exceed web.session.max-lifetime"));
+ }
+ return origin == null ? null : new WebSettings(origin, idle, max);
+ }
+
+ @Nullable
+ private static URI httpsUri(String text, boolean originOnly) {
+ try {
+ var uri = new URI(text);
+ // The scheme is case-insensitive (RFC 3986, section 3.1); WebSettings writes the origin in lower case.
+ if (!"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null || uri.getFragment() != null
+ || uri.getUserInfo() != null) {
+ return null;
+ }
+ if (originOnly && ((uri.getRawPath() != null && !uri.getRawPath().isEmpty()
+ && !"/".equals(uri.getRawPath())) || uri.getQuery() != null)) {
+ return null;
+ }
+ return uri;
+ } catch (URISyntaxException e) {
+ return null;
+ }
+ }
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/ConfigurationProducer.java b/trailhand/src/main/java/de/cuioss/trailhand/config/ConfigurationProducer.java
new file mode 100644
index 0000000..09b4908
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/config/ConfigurationProducer.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.config;
+
+import de.cuioss.tools.logging.CuiLogger;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.inject.Produces;
+import jakarta.inject.Singleton;
+import org.eclipse.microprofile.config.inject.ConfigProperty;
+
+import java.nio.file.Path;
+
+import static de.cuioss.trailhand.TrailhandLogMessages.ERROR;
+
+/**
+ * Loads {@code trailhand.yaml} from {@code trailhand.config.dir} once and provides it (TRH-CONF-1). An invalid
+ * configuration stops the boot: every violation was logged as one ERROR record, and the producer fails.
+ */
+@ApplicationScoped
+public class ConfigurationProducer {
+
+ private static final CuiLogger LOGGER = new CuiLogger(ConfigurationProducer.class);
+
+ private final Path directory;
+
+ /**
+ * @param directory the configuration directory, {@code trailhand.config.dir}
+ */
+ public ConfigurationProducer(@ConfigProperty(name = "trailhand.config.dir", defaultValue = "config") String directory) {
+ this.directory = Path.of(directory);
+ }
+
+ /**
+ * @return the validated configuration
+ * @throws InvalidConfigurationException if the configuration has a violation
+ */
+ @Produces
+ // @Singleton, not @ApplicationScoped: a record is final and cannot stand behind the client proxy of a normal scope.
+ @Singleton
+ public TrailhandConfiguration configuration() {
+ var result = ConfigurationLoader.fromProcessEnvironment().load(directory);
+ var configuration = result.configuration();
+ if (!result.isValid() || configuration == null) {
+ LOGGER.error(ERROR.BOOT_STOPPED, result.violations().size());
+ throw new InvalidConfigurationException(result.violations().size());
+ }
+ return configuration;
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/ConfigurationResult.java b/trailhand/src/main/java/de/cuioss/trailhand/config/ConfigurationResult.java
new file mode 100644
index 0000000..d22f3c7
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/config/ConfigurationResult.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.config;
+
+import org.jspecify.annotations.Nullable;
+
+import java.util.List;
+
+/**
+ * The result of loading {@code trailhand.yaml}: the configuration, or every violation.
+ *
+ * @param configuration the configuration; {@code null} when there is a violation
+ * @param violations the violations, empty for a valid configuration
+ */
+public record ConfigurationResult(@Nullable TrailhandConfiguration configuration, List violations) {
+
+ /**
+ * Copies the violations.
+ *
+ * @param configuration the configuration
+ * @param violations the violations
+ */
+ public ConfigurationResult {
+ violations = List.copyOf(violations);
+ }
+
+ /**
+ * @return whether the configuration is valid
+ */
+ public boolean isValid() {
+ return configuration != null && violations.isEmpty();
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/InvalidConfigurationException.java b/trailhand/src/main/java/de/cuioss/trailhand/config/InvalidConfigurationException.java
new file mode 100644
index 0000000..86bbbbd
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/config/InvalidConfigurationException.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.config;
+
+import java.io.Serial;
+
+/**
+ * Stops the boot on an invalid configuration (TRH-CONF-1). The violations themselves were logged one by one.
+ */
+public class InvalidConfigurationException extends IllegalStateException {
+
+ @Serial
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * @param violations the number of violations
+ */
+ public InvalidConfigurationException(int violations) {
+ super("Invalid configuration: " + violations + " violation(s), see the log records TRAILHAND-200");
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/OidcSettings.java b/trailhand/src/main/java/de/cuioss/trailhand/config/OidcSettings.java
new file mode 100644
index 0000000..6bc9d5f
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/config/OidcSettings.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.config;
+
+/**
+ * The web login through Token Sheriff (TRH-AUTH-1): {@code trailhand.yaml} → {@code oidc}.
+ *
+ * @param issuer the issuer of the identity provider, an absolute {@code https} URI
+ * @param clientId the client id of the confidential client
+ * @param clientCredentialRef the reference to the client secret
+ * @param groupsClaim the claim the groups are read from, default {@code groups}
+ */
+public record OidcSettings(String issuer, String clientId, String clientCredentialRef, String groupsClaim) {
+
+ /** The default of {@code groups-claim}. */
+ public static final String DEFAULT_GROUPS_CLAIM = "groups";
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/Placeholders.java b/trailhand/src/main/java/de/cuioss/trailhand/config/Placeholders.java
new file mode 100644
index 0000000..886ed11
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/config/Placeholders.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.config;
+
+import lombok.experimental.UtilityClass;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.UnaryOperator;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Resolves {@code ${NAME}} and {@code ${NAME:-default}} in string values from the environment, before validation
+ * (TRH-CONF-1). {@code NAME} is an environment variable name (letters, digits and underscores, not starting with a
+ * digit). Any other {@code ${...}}, a nested one in a default included, is reported like an unresolved placeholder, so
+ * it can never pass as a literal value.
+ */
+@UtilityClass
+public class Placeholders {
+
+ private static final Pattern PLACEHOLDER = Pattern.compile("\\$\\{([^}]*)}");
+ private static final Pattern NAME = Pattern.compile("[A-Za-z_]\\w*");
+ private static final String DEFAULT_SEPARATOR = ":-";
+
+ /**
+ * Resolves every placeholder of a string.
+ *
+ * @param value the string
+ * @param environment the environment
+ * @param unresolved receives the name of every placeholder without value and without default
+ * @return the resolved string
+ */
+ public static String resolve(String value, UnaryOperator environment, List unresolved) {
+ Matcher matcher = PLACEHOLDER.matcher(value);
+ var result = new StringBuilder();
+ while (matcher.find()) {
+ String body = matcher.group(1);
+ int separator = body.indexOf(DEFAULT_SEPARATOR);
+ String name = separator < 0 ? body : body.substring(0, separator);
+ String replacement = null;
+ // A nested ${...} in a default is not resolved; it is refused like an unresolved placeholder.
+ if (NAME.matcher(name).matches() && !body.contains("${")) {
+ replacement = environment.apply(name);
+ if (replacement == null && separator >= 0) {
+ replacement = body.substring(separator + DEFAULT_SEPARATOR.length());
+ }
+ }
+ if (replacement == null) {
+ unresolved.add(name);
+ replacement = "";
+ }
+ matcher.appendReplacement(result, Matcher.quoteReplacement(replacement));
+ }
+ matcher.appendTail(result);
+ return result.toString();
+ }
+
+ /**
+ * Resolves the placeholders of every string in a tree of maps and lists, as Jackson reads YAML.
+ *
+ * @param node a node of the tree
+ * @param environment the environment
+ * @param unresolved receives the names of placeholders without value and default
+ * @return the resolved node
+ */
+ @SuppressWarnings("unchecked")
+ public static Object resolveTree(Object node, UnaryOperator environment, List unresolved) {
+ return switch (node) {
+ case String text -> resolve(text, environment, unresolved);
+ case Map, ?> map -> {
+ var copy = new LinkedHashMap();
+ ((Map) map).forEach((key, value) -> copy.put(key,
+ value == null ? null : resolveTree(value, environment, unresolved)));
+ yield copy;
+ }
+ case List> list -> list.stream()
+ .map(entry -> entry == null ? null : resolveTree(entry, environment, unresolved)).toList();
+ default -> node;
+ };
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/RepositorySettings.java b/trailhand/src/main/java/de/cuioss/trailhand/config/RepositorySettings.java
new file mode 100644
index 0000000..7e98783
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/config/RepositorySettings.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.config;
+
+import org.jspecify.annotations.Nullable;
+
+import java.time.Period;
+
+/**
+ * One repository of {@code trailhand.yaml} (TRH-CONF-2).
+ *
+ * @param alias the stable alias, {@code [a-z0-9-]+}
+ * @param remote the remote: an {@code https} URL or a {@code file:} URL of a local bare repository
+ * @param confidentiality the confidentiality class: {@code public-internal}, {@code restricted} or
+ * {@code strongly-restricted}
+ * @param retention the retention period; {@code null} for {@code unlimited}
+ * @param credentialRef the reference to the credential of the technical user; {@code null} for a {@code file:}
+ * remote
+ */
+public record RepositorySettings(String alias, String remote, String confidentiality, @Nullable Period retention,
+@Nullable String credentialRef) {
+
+ /**
+ * @return whether the remote is a local bare repository
+ */
+ public boolean isLocal() {
+ return remote.startsWith("file:");
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/RightSettings.java b/trailhand/src/main/java/de/cuioss/trailhand/config/RightSettings.java
new file mode 100644
index 0000000..9df6148
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/config/RightSettings.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.config;
+
+import java.util.Set;
+
+/**
+ * One entry of {@code trailhand.yaml} → {@code rights}: what a group may do on a repository (TRH-AUTH-2).
+ *
+ * @param repository the alias of the repository
+ * @param actions the actions
+ */
+public record RightSettings(String repository, Set actions) {
+
+ /**
+ * Copies the actions.
+ *
+ * @param repository the alias
+ * @param actions the actions
+ */
+ public RightSettings {
+ actions = Set.copyOf(actions);
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/TokenSheriffConfigSourceFactory.java b/trailhand/src/main/java/de/cuioss/trailhand/config/TokenSheriffConfigSourceFactory.java
new file mode 100644
index 0000000..053de4b
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/config/TokenSheriffConfigSourceFactory.java
@@ -0,0 +1,166 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.config;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
+import io.smallrye.config.ConfigSourceContext;
+import io.smallrye.config.ConfigSourceFactory;
+import io.smallrye.config.common.MapBackedConfigSource;
+import org.eclipse.microprofile.config.spi.ConfigSource;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.function.UnaryOperator;
+
+/**
+ * Derives the configuration of Token Sheriff's client and validation extensions from {@code trailhand.yaml} →
+ * {@code oidc} and {@code web.origin}, so the operator maintains one policy file (TRH-CONF-1):
+ * {@code sheriff.client.*} (issuer, client id, client secret from its {@code file:} reference, redirect address, scopes)
+ * and the issuer {@code sheriff.token.issuers.trailhand.*} that validates the tokens of the login.
+ *
+ * The source has the ordinal {@value #ORDINAL}: above {@code application.properties}, below the environment. An
+ * invalid {@code trailhand.yaml} yields no values; the boot then stops in {@link ConfigurationProducer} with every
+ * violation logged. Transport settings that depend on the deployment (egress hosts, loopback) stay in the
+ * environment.
+ */
+public class TokenSheriffConfigSourceFactory implements ConfigSourceFactory {
+
+ /** The ordinal of the derived source. */
+ public static final int ORDINAL = 260;
+
+ /**
+ * The optional key of the JWKS address, for a deployment that reaches the provider under another origin than the
+ * issuer's (split horizon): it replaces the discovery of the keys through the issuer's well-known document.
+ */
+ public static final String JWKS_URL = "trailhand.oidc.jwks-url";
+
+ /** The name of the issuer configuration that validates the login's tokens. */
+ public static final String ISSUER_NAME = "trailhand";
+
+ @Override
+ public Iterable getConfigSources(ConfigSourceContext context) {
+ var dirValue = context.getValue("trailhand.config.dir");
+ var directory = Path.of(dirValue == null || dirValue.getValue() == null ? "config" : dirValue.getValue());
+ var keys = new LinkedHashMap<>(derive(directory, System::getenv));
+ var jwksUrl = context.getValue(JWKS_URL);
+ if (!keys.isEmpty() && jwksUrl != null && jwksUrl.getValue() != null && !jwksUrl.getValue().isBlank()) {
+ useJwksUrl(keys, jwksUrl.getValue().trim());
+ }
+ return List.of(new MapBackedConfigSource("trailhand.yaml (oidc)", keys, ORDINAL) {
+ });
+ }
+
+ @Override
+ public OptionalInt getPriority() {
+ return OptionalInt.of(ORDINAL);
+ }
+
+ /**
+ * @param directory the configuration directory
+ * @param environment the environment of the placeholders
+ * @return the derived keys; empty when {@code trailhand.yaml} is missing or invalid
+ */
+ static Map derive(Path directory, UnaryOperator environment) {
+ var file = directory.resolve(ConfigurationLoader.FILE_NAME);
+ if (!Files.isRegularFile(file)) {
+ return Map.of();
+ }
+ try {
+ var tree = new ObjectMapper(new YAMLFactory()).readValue(file.toFile(), Object.class);
+ var result = new ConfigurationLoader(environment).validate(tree);
+ var configuration = result.configuration();
+ if (!result.isValid() || configuration == null) {
+ return Map.of();
+ }
+ return derive(configuration);
+ } catch (IOException e) {
+ return Map.of();
+ }
+ }
+
+ /**
+ * @param configuration a valid configuration
+ * @return the derived keys
+ */
+ static Map derive(TrailhandConfiguration configuration) {
+ var oidc = configuration.oidc();
+ var keys = new LinkedHashMap();
+ keys.put("sheriff.client.issuer", oidc.issuer());
+ keys.put("sheriff.client.client-id", oidc.clientId());
+ readSecret(oidc.clientCredentialRef()).ifPresent(secret -> keys.put("sheriff.client.client-secret", secret));
+ keys.put("sheriff.client.redirect-uri",
+ configuration.web().originHeaderValue() + "/api/v1/auth/callback");
+ keys.put("sheriff.client.scopes", "openid,profile,email");
+ var issuer = "sheriff.token.issuers." + ISSUER_NAME + ".";
+ keys.put(issuer + "enabled", "true");
+ keys.put(issuer + "issuer-identifier", oidc.issuer());
+ keys.put(issuer + "jwks.http.well-known-url", stripSlash(oidc.issuer()) + "/.well-known/openid-configuration");
+ keys.put(issuer + "expected-client-id", oidc.clientId());
+ // Access and ID token are validated by this one issuer configuration: the ID token's audience is the client,
+ // an access token's audience is the resource the provider names; the client id (azp) is checked for both.
+ keys.put(issuer + "audience-validation-disabled", "true");
+ return keys;
+ }
+
+ /**
+ * @param keys the derived keys
+ * @param jwksUrl the JWKS address
+ */
+ static void useJwksUrl(Map keys, String jwksUrl) {
+ var issuer = "sheriff.token.issuers." + ISSUER_NAME + ".";
+ keys.remove(issuer + "jwks.http.well-known-url");
+ keys.put(issuer + "jwks.http.url", jwksUrl);
+ }
+
+ static String withoutTrailingLineBreak(String content) {
+ if (content.endsWith("\r\n")) {
+ return content.substring(0, content.length() - 2);
+ }
+ if (content.endsWith("\n") || content.endsWith("\r")) {
+ return content.substring(0, content.length() - 1);
+ }
+ return content;
+ }
+
+ private static String stripSlash(String issuer) {
+ return issuer.endsWith("/") ? issuer.substring(0, issuer.length() - 1) : issuer;
+ }
+
+ /**
+ * Resolves a {@code file:} reference, the only form the loader accepts until the Vault adapter is built.
+ *
+ * @param reference the reference
+ * @return the secret: the file's content without one trailing line break; every other character is kept
+ */
+ static Optional readSecret(String reference) {
+ if (!reference.startsWith("file:")) {
+ return Optional.empty();
+ }
+ try {
+ var content = Files.readString(Path.of(reference.substring("file:".length())));
+ return Optional.of(withoutTrailingLineBreak(content));
+ } catch (IOException e) {
+ return Optional.empty();
+ }
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/TrailhandConfiguration.java b/trailhand/src/main/java/de/cuioss/trailhand/config/TrailhandConfiguration.java
new file mode 100644
index 0000000..7ccf653
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/config/TrailhandConfiguration.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.config;
+
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The validated policy configuration of {@code trailhand.yaml} (TRH-CONF-1), as far as the application uses it.
+ *
+ * @param repositories the repositories in file order
+ * @param rights the rights per identity-provider group
+ * @param oidc the web login
+ * @param web the web app
+ * @param fetchInterval the interval of the periodic fetch, default 5 minutes
+ */
+public record TrailhandConfiguration(List repositories, Map> rights,
+OidcSettings oidc, WebSettings web, Duration fetchInterval) {
+
+ /** The default of {@code fetch.interval}. */
+ public static final Duration DEFAULT_FETCH_INTERVAL = Duration.ofMinutes(5);
+
+ /**
+ * Copies the collections.
+ *
+ * @param repositories the repositories
+ * @param rights the rights
+ * @param oidc the web login
+ * @param web the web app
+ * @param fetchInterval the fetch interval
+ */
+ public TrailhandConfiguration {
+ repositories = List.copyOf(repositories);
+ rights = Map.copyOf(rights);
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/Violation.java b/trailhand/src/main/java/de/cuioss/trailhand/config/Violation.java
new file mode 100644
index 0000000..b8c0474
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/config/Violation.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.config;
+
+/**
+ * One violation of the configuration: where and which rule (TRH-CONF-1).
+ *
+ * @param key the key, e.g. {@code repositories[1].alias}
+ * @param rule what is wrong, without the value (a value may be a secret's reference or a URL with user information)
+ */
+public record Violation(String key, String rule) {
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/WebSettings.java b/trailhand/src/main/java/de/cuioss/trailhand/config/WebSettings.java
new file mode 100644
index 0000000..c60689c
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/config/WebSettings.java
@@ -0,0 +1,149 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.config;
+
+import java.net.InetAddress;
+import java.net.URI;
+import java.net.UnknownHostException;
+import java.time.Duration;
+import java.util.Locale;
+import java.util.Optional;
+
+/**
+ * The web app: {@code trailhand.yaml} → {@code web} (TRH-AUTH-1, TRH-WEB-8).
+ *
+ * @param origin the application's own origin, an absolute {@code https} URI without path; the Origin check and
+ * the login callback address use it
+ * @param idleTimeout the idle time after which a session ends, default 30 minutes
+ * @param maxLifetime the absolute lifetime of a session, default 8 hours
+ */
+public record WebSettings(URI origin, Duration idleTimeout, Duration maxLifetime) {
+
+ private static final int HTTPS_PORT = 443;
+ private static final int HTTP_PORT = 80;
+ private static final int IPV4_BYTES = 4;
+ private static final int IPV6_BYTES = 16;
+ private static final int IPV6_PIECES = 8;
+
+ /** The default of {@code session.idle-timeout}. */
+ public static final Duration DEFAULT_IDLE_TIMEOUT = Duration.ofMinutes(30);
+
+ /** The default of {@code session.max-lifetime}. */
+ public static final Duration DEFAULT_MAX_LIFETIME = Duration.ofHours(8);
+
+ /**
+ * @return the origin as the browser sends it in the {@code Origin} header: scheme and host in lower case and the
+ * port only when it is not the default of the scheme (RFC 6454, section 6.1)
+ */
+ public String originHeaderValue() {
+ var scheme = origin.getScheme().toLowerCase(Locale.ROOT);
+ var defaultPort = "https".equals(scheme) ? HTTPS_PORT : HTTP_PORT;
+ var port = origin.getPort() == -1 || origin.getPort() == defaultPort ? "" : ":" + origin.getPort();
+ return scheme + "://" + browserHost(origin.getHost()) + port;
+ }
+
+ /**
+ * @param host the host of a URI: a name, an IPv4 address or a bracketed IPv6 literal
+ * @return the host as the browser serializes it: a name in lower case, an IPv6 literal in the form of the URL
+ * Standard's IPv6 serializer (section 3.6: lower-case hexadecimal without leading zeros, the first longest
+ * run of two or more zero pieces as {@code ::}, no embedded IPv4)
+ */
+ static String browserHost(String host) {
+ var lower = host.toLowerCase(Locale.ROOT);
+ if (!lower.startsWith("[") || !lower.endsWith("]")) {
+ return lower;
+ }
+ return ipv6Pieces(lower.substring(1, lower.length() - 1)).map(pieces -> "[" + ipv6Text(pieces) + "]")
+ .orElse(lower);
+ }
+
+ /**
+ * @param literal an IPv6 literal without brackets
+ * @return its eight pieces, or empty when it is no IPv6 literal
+ */
+ private static Optional ipv6Pieces(String literal) {
+ byte[] bytes;
+ try {
+ // A literal is only parsed, never looked up.
+ bytes = InetAddress.getByName(literal).getAddress();
+ } catch (UnknownHostException e) {
+ return Optional.empty();
+ }
+ if (bytes.length == IPV4_BYTES) {
+ // Java answers an IPv4-mapped literal (::ffff:a.b.c.d) with the IPv4 address; the browser keeps it IPv6.
+ var mapped = new byte[IPV6_BYTES];
+ mapped[10] = (byte) 0xff;
+ mapped[11] = (byte) 0xff;
+ System.arraycopy(bytes, 0, mapped, 12, IPV4_BYTES);
+ bytes = mapped;
+ }
+ var pieces = new int[IPV6_PIECES];
+ for (int index = 0; index < IPV6_PIECES; index++) {
+ pieces[index] = ((bytes[2 * index] & 0xff) << 8) | (bytes[2 * index + 1] & 0xff);
+ }
+ return Optional.of(pieces);
+ }
+
+ /**
+ * @param pieces the eight pieces of an IPv6 address
+ * @return the address as the URL Standard's IPv6 serializer writes it
+ */
+ private static String ipv6Text(int[] pieces) {
+ var compress = compressedPiece(pieces);
+ var text = new StringBuilder();
+ var index = 0;
+ while (index < IPV6_PIECES) {
+ if (index == compress) {
+ text.append(index == 0 ? "::" : ":");
+ index += zeroRun(pieces, index);
+ } else {
+ text.append(Integer.toHexString(pieces[index]));
+ if (index < IPV6_PIECES - 1) {
+ text.append(':');
+ }
+ index++;
+ }
+ }
+ return text.toString();
+ }
+
+ /**
+ * @param pieces the eight pieces of an IPv6 address
+ * @return the index of the first longest run of two or more zero pieces, or {@code -1}
+ */
+ private static int compressedPiece(int[] pieces) {
+ var longestIndex = -1;
+ var longestSize = 1;
+ var index = 0;
+ while (index < pieces.length) {
+ var size = zeroRun(pieces, index);
+ if (size > longestSize) {
+ longestIndex = index;
+ longestSize = size;
+ }
+ index += Math.max(size, 1);
+ }
+ return longestIndex;
+ }
+
+ private static int zeroRun(int[] pieces, int start) {
+ var size = 0;
+ while (start + size < pieces.length && pieces[start + size] == 0) {
+ size++;
+ }
+ return size;
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/config/package-info.java b/trailhand/src/main/java/de/cuioss/trailhand/config/package-info.java
new file mode 100644
index 0000000..b7de4ad
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/config/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/**
+ * Configuration model and boot validation rules (TRH-CONF-1, TRH-CONF-2); depends on nothing else of the application.
+ */
+@NullMarked
+package de.cuioss.trailhand.config;
+
+import org.jspecify.annotations.NullMarked;
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/package-info.java b/trailhand/src/main/java/de/cuioss/trailhand/package-info.java
new file mode 100644
index 0000000..26d67b3
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/**
+ * TrailHand: security documents as versioned Git documents (doc/specification/architecture-and-modules.adoc).
+ */
+@NullMarked
+package de.cuioss.trailhand;
+
+import org.jspecify.annotations.NullMarked;
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/LoginFlowProducer.java b/trailhand/src/main/java/de/cuioss/trailhand/security/LoginFlowProducer.java
new file mode 100644
index 0000000..b31cdad
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/security/LoginFlowProducer.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.security;
+
+import de.cuioss.sheriff.token.client.config.ClientConfiguration;
+import de.cuioss.sheriff.token.client.flow.AuthorizationCodeFlow;
+import de.cuioss.sheriff.token.client.flow.CallbackHandler;
+import de.cuioss.sheriff.token.client.flow.IssValidator;
+import de.cuioss.sheriff.token.client.flow.TokenEndpointClient;
+import de.cuioss.sheriff.token.client.token.IdTokenValidationBridge;
+import de.cuioss.sheriff.token.client.token.TokenValidationBridge;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.inject.Produces;
+import jakarta.inject.Named;
+
+/**
+ * Builds the authorization code flow of the web login from Token Sheriff's beans, with the
+ * {@link QueryResponseModeRequestBuilder} in place of the built-in request builder (TRH-AUTH-1). Without sender
+ * constraint: the tokens stay on the server.
+ */
+@ApplicationScoped
+public class LoginFlowProducer {
+
+ /** The qualifier of the web login's flow. */
+ public static final String WEB_LOGIN = "trailhand-web-login";
+
+ /**
+ * @param configuration the client configuration
+ * @param tokenEndpoint the token endpoint client
+ * @param accessTokenBridge the access-token validation
+ * @param idTokenBridge the ID-token validation
+ * @param issValidator the issuer check of the authorization response (RFC 9207)
+ * @return the flow
+ */
+ @Produces
+ @ApplicationScoped
+ @Named(WEB_LOGIN)
+ AuthorizationCodeFlow webLoginFlow(ClientConfiguration configuration, TokenEndpointClient tokenEndpoint,
+ TokenValidationBridge accessTokenBridge, IdTokenValidationBridge idTokenBridge, IssValidator issValidator) {
+ return new AuthorizationCodeFlow(configuration, tokenEndpoint, accessTokenBridge, idTokenBridge, issValidator,
+ new QueryResponseModeRequestBuilder(), new CallbackHandler(), null);
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/LoginIdentity.java b/trailhand/src/main/java/de/cuioss/trailhand/security/LoginIdentity.java
new file mode 100644
index 0000000..6988b63
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/security/LoginIdentity.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.security;
+
+import org.jspecify.annotations.Nullable;
+
+import java.time.Instant;
+import java.util.List;
+
+/**
+ * The identity values a completed login yields (TRH-AUTH-3: issuer, subject, authentication time and context).
+ *
+ * @param issuer {@code iss}
+ * @param subject {@code sub}
+ * @param name the display name
+ * @param groups the groups of the configured claim
+ * @param authTime {@code auth_time}, or {@code null}
+ * @param acr {@code acr}, or {@code null}
+ */
+public record LoginIdentity(String issuer, String subject, String name, List groups,
+@Nullable Instant authTime, @Nullable String acr) {
+
+ /**
+ * Copies the groups.
+ *
+ * @param issuer the issuer
+ * @param subject the subject
+ * @param name the name
+ * @param groups the groups
+ * @param authTime the authentication time
+ * @param acr the authentication context class
+ */
+ public LoginIdentity {
+ groups = List.copyOf(groups);
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/LoginService.java b/trailhand/src/main/java/de/cuioss/trailhand/security/LoginService.java
new file mode 100644
index 0000000..391ef70
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/security/LoginService.java
@@ -0,0 +1,350 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.security;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import de.cuioss.sheriff.token.client.auth.ClientAuthentication;
+import de.cuioss.sheriff.token.client.discovery.DiscoveryResolver;
+import de.cuioss.sheriff.token.client.discovery.ProviderMetadata;
+import de.cuioss.sheriff.token.client.flow.AuthorizationCodeFlow;
+import de.cuioss.sheriff.token.client.flow.CallbackParameters;
+import de.cuioss.sheriff.token.client.flow.ParClient;
+import de.cuioss.sheriff.token.client.lifecycle.RevocationClient;
+import de.cuioss.sheriff.token.client.lifecycle.StoredToken;
+import de.cuioss.sheriff.token.client.lifecycle.TokenLifecycleManager;
+import de.cuioss.sheriff.token.client.logout.EndSessionFlow;
+import de.cuioss.sheriff.token.client.logout.PostLogoutRedirectValidator;
+import de.cuioss.sheriff.token.commons.error.TokenSheriffException;
+import de.cuioss.sheriff.token.validation.domain.claim.ClaimValue;
+import de.cuioss.sheriff.token.validation.domain.token.IdTokenContent;
+import de.cuioss.tools.logging.CuiLogger;
+import de.cuioss.trailhand.config.TrailhandConfiguration;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Named;
+import org.jspecify.annotations.Nullable;
+
+import java.io.IOException;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static de.cuioss.trailhand.TrailhandLogMessages.INFO;
+import static de.cuioss.trailhand.TrailhandLogMessages.WARN;
+
+/**
+ * The web login of TRH-AUTH-1 on Token Sheriff's confidential client (ADR-0001): authorization code with PKCE
+ * {@code S256}, session-bound {@code state} and {@code nonce}, issuer check, and PAR (RFC 9126) when the provider
+ * offers it; tokens stay in Token Sheriff's token
+ * store under the session id, the browser gets only the session cookie. Logout revokes the held tokens and ends the
+ * session at the provider (RP-initiated).
+ */
+@ApplicationScoped
+public class LoginService {
+
+ private static final CuiLogger LOGGER = new CuiLogger(LoginService.class);
+ private static final ObjectMapper JSON = new ObjectMapper();
+
+ private final DiscoveryResolver discovery;
+ private final AuthorizationCodeFlow flow;
+ private final ParClient par;
+ private final ClientAuthentication clientAuthentication;
+ private final TokenLifecycleManager tokens;
+ private final RevocationClient revocation;
+ private final SessionStore sessions;
+ private final LoginTransactions transactions;
+ private final ReturnAddresses returnAddresses;
+ private final TrailhandConfiguration configuration;
+ private final AtomicReference<@Nullable ProviderMetadata> metadata = new AtomicReference<>();
+
+ /**
+ * @param discovery Token Sheriff's discovery
+ * @param flow the authorization code flow
+ * @param par the client of the pushed-authorization-request endpoint
+ * @param clientAuthentication the client authentication
+ * @param tokens the token store of the sessions
+ * @param revocation the revocation client
+ * @param sessions the sessions
+ * @param transactions the login transactions
+ * @param returnAddresses the return check
+ * @param configuration the configuration
+ */
+ @SuppressWarnings("java:S107") // the collaborators of the flow; grouping them would only hide them
+ public LoginService(DiscoveryResolver discovery, @Named(LoginFlowProducer.WEB_LOGIN) AuthorizationCodeFlow flow,
+ ParClient par, ClientAuthentication clientAuthentication, TokenLifecycleManager tokens, RevocationClient revocation,
+ SessionStore sessions, LoginTransactions transactions, ReturnAddresses returnAddresses,
+ TrailhandConfiguration configuration) {
+ this.discovery = discovery;
+ this.flow = flow;
+ this.par = par;
+ this.clientAuthentication = clientAuthentication;
+ this.tokens = tokens;
+ this.revocation = revocation;
+ this.sessions = sessions;
+ this.transactions = transactions;
+ this.returnAddresses = returnAddresses;
+ this.configuration = configuration;
+ }
+
+ /**
+ * The provider's metadata, read once: the resolver of Token Sheriff fetches on every call.
+ *
+ * @return the metadata
+ */
+ ProviderMetadata metadata() {
+ var current = metadata.get();
+ if (current == null) {
+ current = discovery.resolve();
+ metadata.set(current);
+ }
+ return current;
+ }
+
+ /**
+ * Starts a login. When the provider offers PAR, the authorization parameters are pushed to it and the browser
+ * goes to the provider with {@code client_id} and {@code request_uri} only.
+ *
+ * @param requestedReturn the {@code return} of the request
+ * @return the authorization address and the transaction reference for the cookie
+ * @throws TokenSheriffException if the provider cannot be reached or refuses the flow
+ * @throws TooManyLoginsException if {@value LoginTransactions#MAX_PENDING} logins are pending
+ */
+ public LoginStart start(@Nullable String requestedReturn) {
+ var metadataNow = metadata();
+ var redirect = flow.authorize(metadataNow);
+ var reference = transactions.begin(redirect.context(), returnAddresses.check(requestedReturn))
+ .orElseThrow(TooManyLoginsException::new);
+ var started = false;
+ try {
+ var start = new LoginStart(authorizationAddress(metadataNow, redirect.authorizationUrl()), reference);
+ started = true;
+ return start;
+ } finally {
+ if (!started) {
+ // The reference never reaches the browser: free its place at once instead of waiting for its expiry.
+ transactions.take(reference);
+ }
+ }
+ }
+
+ /**
+ * @param metadataNow the provider's metadata
+ * @param direct the authorization address with every parameter in its query
+ * @return the direct address, or with PAR the authorization endpoint with {@code client_id} and
+ * {@code request_uri}
+ */
+ String authorizationAddress(ProviderMetadata metadataNow, String direct) {
+ var endpoint = metadataNow.getPushedAuthorizationRequestEndpoint();
+ var queryStart = direct.indexOf('?');
+ if (endpoint.isEmpty() || queryStart < 0) {
+ return direct;
+ }
+ var parameters = queryParameters(direct.substring(queryStart + 1));
+ var clientId = parameters.get("client_id");
+ var requestUri = par.pushAuthorizationRequest(endpoint.get(), parameters, clientAuthentication).getRequestUri()
+ .orElseThrow(() -> new IllegalStateException("PAR answer without request_uri"));
+ return direct.substring(0, queryStart) + "?client_id=" + encode(clientId == null ? "" : clientId)
+ + "&request_uri=" + encode(requestUri);
+ }
+
+ static Map queryParameters(String query) {
+ var parameters = new LinkedHashMap();
+ for (String pair : query.split("&")) {
+ if (pair.isEmpty()) {
+ continue;
+ }
+ var separator = pair.indexOf('=');
+ var name = separator < 0 ? pair : pair.substring(0, separator);
+ var value = separator < 0 ? "" : pair.substring(separator + 1);
+ parameters.put(URLDecoder.decode(name, StandardCharsets.UTF_8),
+ URLDecoder.decode(value, StandardCharsets.UTF_8));
+ }
+ return parameters;
+ }
+
+ private static String encode(String value) {
+ return URLEncoder.encode(value, StandardCharsets.UTF_8);
+ }
+
+ /**
+ * Completes a login from the provider's answer.
+ *
+ * @param transactionReference the reference from the transaction cookie, or {@code null} when it is missing
+ * @param callbackQuery the raw query of the callback ({@code code}, {@code state}, {@code iss})
+ * @return the new session and the return address, or empty when the login cannot be completed
+ */
+ public Optional complete(@Nullable String transactionReference, String callbackQuery) {
+ if (transactionReference == null) {
+ LOGGER.warn(WARN.LOGIN_FAILED, "no login transaction cookie");
+ return Optional.empty();
+ }
+ var transaction = transactions.take(transactionReference);
+ if (transaction.isEmpty()) {
+ LOGGER.warn(WARN.LOGIN_FAILED, "unknown or expired login transaction");
+ return Optional.empty();
+ }
+ try {
+ var callback = CallbackParameters.parse(callbackQuery);
+ var result = flow.exchange(metadata(), transaction.get().context(), callback, clientAuthentication);
+ var identity = identity(result.idToken());
+ var session = sessions.open(identity);
+ tokens.store(session.id(), new StoredToken(result.accessToken().getRawToken(), result.refreshToken(),
+ result.idToken().getRawToken(), null, result.accessToken().getExpirationDateTime().toInstant(),
+ identity.subject()));
+ LOGGER.info(INFO.LOGIN_COMPLETED, identity.issuer());
+ return Optional.of(new LoginCompletion(session, transaction.get().returnAddress()));
+ } catch (TokenSheriffException | IllegalArgumentException | IllegalStateException e) {
+ LOGGER.warn(WARN.LOGIN_FAILED, e.getClass().getSimpleName());
+ return Optional.empty();
+ }
+ }
+
+ private LoginIdentity identity(IdTokenContent idToken) {
+ var subject = idToken.getSubject().orElseThrow(() -> new IllegalStateException("ID token without sub"));
+ var claims = idToken.getClaims();
+ var groups = groups(idToken.getRawToken(), configuration.oidc().groupsClaim());
+ var authTime = Optional.ofNullable(claims.get("auth_time")).map(ClaimValue::getOriginalString)
+ .flatMap(LoginService::epochSeconds).orElse(null);
+ var acr = Optional.ofNullable(claims.get("acr")).map(ClaimValue::getOriginalString).orElse(null);
+ var name = idToken.getDisplayName().orElse(subject);
+ return new LoginIdentity(idToken.getIssuer(), subject, name, groups, authTime, acr);
+ }
+
+ /**
+ * Reads the groups from the JSON payload of the validated ID token: an array yields its strings, a single string
+ * one group, anything else none. The claim is read as the provider wrote it, so a group name that contains a comma
+ * stays one group.
+ *
+ * @param rawToken the validated ID token (a JWS)
+ * @param claim the name of the group claim
+ * @return the groups, empty when the claim is missing or the token cannot be read
+ */
+ static List groups(String rawToken, String claim) {
+ var parts = rawToken.split("\\.");
+ if (parts.length != 3) {
+ return List.of();
+ }
+ try {
+ var value = JSON.readTree(Base64.getUrlDecoder().decode(parts[1])).get(claim);
+ return groups(value);
+ } catch (IOException | IllegalArgumentException e) {
+ LOGGER.warn(WARN.LOGIN_FAILED, "unreadable group claim");
+ return List.of();
+ }
+ }
+
+ private static List groups(@Nullable JsonNode value) {
+ if (value == null) {
+ return List.of();
+ }
+ if (value.isTextual()) {
+ return value.asText().isBlank() ? List.of() : List.of(value.asText());
+ }
+ var groups = new ArrayList();
+ if (value.isArray()) {
+ value.forEach(entry -> {
+ if (entry.isTextual() && !entry.asText().isBlank()) {
+ groups.add(entry.asText());
+ }
+ });
+ }
+ return List.copyOf(groups);
+ }
+
+ static Optional epochSeconds(@Nullable String text) {
+ try {
+ return text == null ? Optional.empty() : Optional.of(Instant.ofEpochSecond(Long.parseLong(text.trim())));
+ } catch (NumberFormatException e) {
+ return Optional.empty();
+ }
+ }
+
+ /**
+ * Ends a session: revokes the held tokens, then builds the RP-initiated logout address of the provider.
+ *
+ * @param sessionId the session id
+ * @return the address the browser navigates to: the provider's end-session address, or the own origin when the
+ * provider has none
+ */
+ public String logout(String sessionId) {
+ sessions.close(sessionId);
+ var held = tokens.revokeAndClear(sessionId);
+ var home = configuration.web().originHeaderValue() + "/";
+ if (held.isEmpty()) {
+ return home;
+ }
+ var metadataNow = metadata();
+ revoke(metadataNow, held.get().refreshToken(), "refresh_token");
+ revoke(metadataNow, held.get().accessToken(), "access_token");
+ var endSession = metadataNow.getEndSessionEndpoint();
+ var idToken = held.get().idToken();
+ if (endSession.isEmpty() || idToken == null) {
+ return home;
+ }
+ LOGGER.info(INFO.LOGOUT_COMPLETED);
+ return new EndSessionFlow(new PostLogoutRedirectValidator(Set.of(home)))
+ .buildLogoutRedirect(endSession.get(), idToken, home, SessionStore.randomToken());
+ }
+
+ private void revoke(ProviderMetadata metadataNow, @Nullable String token, String hint) {
+ var endpoint = metadataNow.getRevocationEndpoint();
+ if (token == null || endpoint.isEmpty()) {
+ return;
+ }
+ try {
+ revocation.revoke(endpoint.get(), token, hint, clientAuthentication);
+ } catch (TokenSheriffException e) {
+ LOGGER.warn(WARN.REVOCATION_FAILED, e.getClass().getSimpleName());
+ }
+ }
+
+ /**
+ * The start of a login.
+ *
+ * @param authorizationUrl where the browser goes
+ * @param transactionReference the value of the transaction cookie
+ */
+ public record LoginStart(String authorizationUrl, String transactionReference) {
+ }
+
+ /**
+ * A completed login.
+ *
+ * @param session the new session
+ * @param returnAddress the checked return address
+ */
+ public record LoginCompletion(UserSession session, String returnAddress) {
+ }
+
+ /** Thrown when the login cannot start because {@value LoginTransactions#MAX_PENDING} logins are pending. */
+ public static final class TooManyLoginsException extends RuntimeException {
+
+ private static final long serialVersionUID = 1L;
+
+ TooManyLoginsException() {
+ super("too many pending logins");
+ }
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/LoginTransactions.java b/trailhand/src/main/java/de/cuioss/trailhand/security/LoginTransactions.java
new file mode 100644
index 0000000..ec01d3a
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/security/LoginTransactions.java
@@ -0,0 +1,159 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.security;
+
+import de.cuioss.sheriff.token.client.flow.FlowContext;
+import jakarta.enterprise.context.ApplicationScoped;
+
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * The server-side login transactions (TRH-AUTH-1): {@code state}, {@code nonce} and PKCE verifier (Token Sheriff's
+ * {@link FlowContext}) and the checked {@code return}, under an opaque reference the transaction cookie carries.
+ * A transaction lives ten minutes and is taken once.
+ *
+ * The login is reachable without a session, so the store is bounded: at most {@value #MAX_PENDING} transactions are
+ * pending. Every transaction lives {@link #LIFETIME}, so the order of the starts is the order of expiry: a queue in
+ * that order lets each start drop the expired and the taken transactions at its head, without scanning the store.
+ */
+@ApplicationScoped
+public class LoginTransactions {
+
+ /** The lifetime of a transaction, also the {@code Max-Age} of its cookie. */
+ public static final Duration LIFETIME = Duration.ofMinutes(10);
+
+ /** The most transactions pending at once; a start beyond it is refused. */
+ public static final int MAX_PENDING = 10_000;
+
+ private final Map transactions = new ConcurrentHashMap<>();
+ /** The references in the order of their start, which is the order of their expiry. */
+ private final Queue byExpiry = new ConcurrentLinkedQueue<>();
+ private final AtomicInteger queued = new AtomicInteger();
+ private final AtomicBoolean compacting = new AtomicBoolean();
+ private final AtomicInteger pending = new AtomicInteger();
+ private final Clock clock;
+ private final int maxPending;
+
+ /** Creates the store with the system clock. */
+ public LoginTransactions() {
+ this(Clock.systemUTC(), MAX_PENDING);
+ }
+
+ /**
+ * @param clock the clock
+ * @param maxPending the most transactions pending at once
+ */
+ LoginTransactions(Clock clock, int maxPending) {
+ this.clock = clock;
+ this.maxPending = maxPending;
+ }
+
+ /**
+ * @param context the flow context of the authorization request
+ * @param returnAddress the checked return address
+ * @return the opaque reference for the transaction cookie, or empty when {@value #MAX_PENDING} logins are pending
+ */
+ public Optional begin(FlowContext context, String returnAddress) {
+ var now = clock.instant();
+ dropExpired(now);
+ if (pending.incrementAndGet() > maxPending) {
+ pending.decrementAndGet();
+ return Optional.empty();
+ }
+ var reference = SessionStore.randomToken();
+ // The expiry is taken and queued in one step, so the queue order is the expiry order across threads.
+ synchronized (byExpiry) {
+ transactions.put(reference, new Transaction(context, returnAddress, clock.instant().plus(LIFETIME)));
+ byExpiry.add(reference);
+ }
+ if (queued.incrementAndGet() > 2 * Math.max(maxPending, 1)) {
+ compact();
+ }
+ return Optional.of(reference);
+ }
+
+ /**
+ * Takes a transaction: it can be completed once.
+ *
+ * @param reference the reference from the cookie
+ * @return the live transaction, or empty
+ */
+ public Optional take(String reference) {
+ var transaction = transactions.remove(reference);
+ if (transaction == null) {
+ return Optional.empty();
+ }
+ pending.decrementAndGet();
+ return transaction.expires().isBefore(clock.instant()) ? Optional.empty() : Optional.of(transaction);
+ }
+
+ /**
+ * Drops the transactions at the head of the queue that are taken or expired; it stops at the first live one, so
+ * its cost is the number of transactions it drops.
+ *
+ * @param now the current time
+ */
+ private void dropExpired(Instant now) {
+ for (String head = byExpiry.peek(); head != null; head = byExpiry.peek()) {
+ var transaction = transactions.get(head);
+ if (transaction != null && !transaction.expires().isBefore(now)) {
+ return;
+ }
+ if (byExpiry.remove(head)) {
+ queued.decrementAndGet();
+ if (transaction != null && transactions.remove(head, transaction)) {
+ pending.decrementAndGet();
+ }
+ }
+ }
+ }
+
+ /**
+ * Drops the references of taken transactions from the queue. It runs when the queue holds twice the limit, which
+ * only starts that are taken again soon can cause; after it the queue holds at most the pending transactions, so
+ * its cost is spread over the starts that filled it.
+ */
+ private void compact() {
+ if (!compacting.compareAndSet(false, true)) {
+ return;
+ }
+ try {
+ byExpiry.removeIf(reference -> !transactions.containsKey(reference));
+ queued.set(byExpiry.size());
+ } finally {
+ compacting.set(false);
+ }
+ }
+
+ /**
+ * A pending login.
+ *
+ * @param context the flow context
+ * @param returnAddress the checked return address
+ * @param expires when the transaction ends
+ */
+ public record Transaction(FlowContext context, String returnAddress, Instant expires) {
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/QueryResponseModeRequestBuilder.java b/trailhand/src/main/java/de/cuioss/trailhand/security/QueryResponseModeRequestBuilder.java
new file mode 100644
index 0000000..057e16f
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/security/QueryResponseModeRequestBuilder.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.security;
+
+import de.cuioss.sheriff.token.client.config.ClientConfiguration;
+import de.cuioss.sheriff.token.client.discovery.ProviderMetadata;
+import de.cuioss.sheriff.token.client.flow.AuthorizationRequestBuilder;
+import de.cuioss.sheriff.token.client.flow.FlowContext;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * Drives the authorization request with {@code response_mode=query} instead of Token Sheriff's built-in
+ * {@code response_mode=form_post} (TRH-AUTH-1).
+ *
+ * With {@code form_post} the provider answers with a cross-site {@code POST} to the callback, with which a browser
+ * sends no {@code SameSite=Lax} cookie, so the login-transaction cookie would not arrive. With {@code query} the
+ * callback is a top-level {@code GET} navigation, which carries it. The cookie keeps {@code SameSite=Lax}; the
+ * alternative {@code SameSite=None} would weaken the binding the cookie exists for. The same decision and reasoning as
+ * API Sheriff's {@code QueryResponseModeAuthorizationRequestBuilder}.
+ *
+ * Accepted trade-off: the code travels in the callback's query string. It is bounded by PKCE (the code cannot be
+ * redeemed without the verifier, which stays on the server), by the single use of the code, by the login transaction
+ * with {@code state}, and by {@code Referrer-Policy: no-referrer} on every answer. The rewrite touches only
+ * {@code response_mode} and keeps every other parameter in its order and encoding.
+ */
+public class QueryResponseModeRequestBuilder extends AuthorizationRequestBuilder {
+
+ private static final String RESPONSE_MODE = "response_mode";
+ private static final String QUERY_PAIR = RESPONSE_MODE + "=query";
+
+ @Override
+ public String build(ClientConfiguration configuration, ProviderMetadata metadata, FlowContext context) {
+ return withQueryResponseMode(super.build(configuration, metadata, context));
+ }
+
+ /**
+ * @param authorizationUrl an authorization address
+ * @return the address with {@code response_mode=query}, added or replacing the existing value
+ */
+ static String withQueryResponseMode(String authorizationUrl) {
+ Objects.requireNonNull(authorizationUrl, "authorizationUrl");
+ int queryStart = authorizationUrl.indexOf('?');
+ if (queryStart < 0) {
+ return authorizationUrl + '?' + QUERY_PAIR;
+ }
+ var prefix = authorizationUrl.substring(0, queryStart + 1);
+ var query = authorizationUrl.substring(queryStart + 1);
+ if (query.isEmpty()) {
+ return prefix + QUERY_PAIR;
+ }
+ List pairs = new ArrayList<>();
+ boolean rewritten = false;
+ for (String pair : query.split("&", -1)) {
+ int separator = pair.indexOf('=');
+ var name = separator < 0 ? pair : pair.substring(0, separator);
+ if (RESPONSE_MODE.equals(name)) {
+ pairs.add(QUERY_PAIR);
+ rewritten = true;
+ } else {
+ pairs.add(pair);
+ }
+ }
+ if (!rewritten) {
+ pairs.add(QUERY_PAIR);
+ }
+ return prefix + String.join("&", pairs);
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/ReturnAddresses.java b/trailhand/src/main/java/de/cuioss/trailhand/security/ReturnAddresses.java
new file mode 100644
index 0000000..54443f5
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/security/ReturnAddresses.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.security;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import jakarta.enterprise.context.ApplicationScoped;
+import org.jspecify.annotations.Nullable;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * The check of the login's {@code return} (TRH-AUTH-1): a same-origin relative path that matches a canonical address
+ * of the web app (TRH-WEB-3); anything else becomes {@code /}. The addresses are the ones the web app routes with,
+ * {@code META-INF/trailhand/canonical-addresses.json} of the {@code web-app} JAR.
+ */
+@ApplicationScoped
+public class ReturnAddresses {
+
+ /** The resource holding the canonical addresses. */
+ public static final String RESOURCE = "META-INF/trailhand/canonical-addresses.json";
+
+ /** The address used for every refused value. */
+ public static final String DEFAULT = "/";
+
+ private static final Pattern PLACEHOLDER = Pattern.compile("\\{([a-z][a-z0-9]*)}");
+ private static final int MAX_LENGTH = 512;
+
+ private final List patterns;
+
+ /**
+ * Reads the canonical addresses from the class path.
+ */
+ public ReturnAddresses() {
+ this(readResource());
+ }
+
+ /**
+ * @param definition the content of {@code canonical-addresses.json}
+ */
+ ReturnAddresses(JsonNode definition) {
+ var segment = definition.path("segment").asText();
+ var params = definition.path("params");
+ var compiled = new ArrayList();
+ for (JsonNode address : definition.path("addresses")) {
+ Matcher matcher = PLACEHOLDER.matcher(address.path("pattern").asText());
+ var regex = new StringBuilder();
+ int last = 0;
+ var pattern = address.path("pattern").asText();
+ while (matcher.find()) {
+ regex.append(Pattern.quote(pattern.substring(last, matcher.start())));
+ var own = params.path(matcher.group(1));
+ regex.append('(').append(own.isMissingNode() ? segment : own.asText()).append(')');
+ last = matcher.end();
+ }
+ regex.append(Pattern.quote(pattern.substring(last)));
+ compiled.add(Pattern.compile(regex.toString()));
+ }
+ this.patterns = List.copyOf(compiled);
+ }
+
+ private static JsonNode readResource() {
+ try (InputStream in = ReturnAddresses.class.getClassLoader().getResourceAsStream(RESOURCE)) {
+ if (in == null) {
+ throw new IllegalStateException(RESOURCE + " is missing from the class path");
+ }
+ return new ObjectMapper().readTree(in);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ /**
+ * @param value the {@code return} of the login request, possibly {@code null}
+ * @return the value when it is a canonical address, otherwise {@code /}
+ */
+ public String check(@Nullable String value) {
+ if (value == null || value.isEmpty() || value.length() > MAX_LENGTH || !value.startsWith("/")
+ || value.startsWith("//") || value.contains("\\")) {
+ return DEFAULT;
+ }
+ int query = value.indexOf('?');
+ var path = query < 0 ? value : value.substring(0, query);
+ if (path.length() > 1 && path.endsWith("/")) {
+ path = path.substring(0, path.length() - 1);
+ }
+ for (Pattern pattern : patterns) {
+ if (pattern.matcher(path).matches()) {
+ return path;
+ }
+ }
+ return DEFAULT;
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/RightsMapper.java b/trailhand/src/main/java/de/cuioss/trailhand/security/RightsMapper.java
new file mode 100644
index 0000000..f0cb920
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/security/RightsMapper.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.security;
+
+import de.cuioss.trailhand.config.Action;
+import de.cuioss.trailhand.config.RightSettings;
+import de.cuioss.trailhand.config.TrailhandConfiguration;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+/**
+ * Derives the rights of a user from the identity-provider groups through {@code trailhand.yaml} → {@code rights}
+ * (TRH-AUTH-2). Deny by default: a group without mapping grants nothing, and nothing else grants a right.
+ */
+@ApplicationScoped
+public class RightsMapper {
+
+ private final Map> rights;
+
+ /**
+ * @param configuration the configuration
+ */
+ @Inject
+ public RightsMapper(TrailhandConfiguration configuration) {
+ this(configuration.rights());
+ }
+
+ /**
+ * @param rights the mapping group → rights
+ */
+ RightsMapper(Map> rights) {
+ this.rights = Map.copyOf(rights);
+ }
+
+ /**
+ * @param groups the user's groups
+ * @return the actions per repository alias, in alias order; repositories without a right are absent
+ */
+ public Map> rightsOf(Collection groups) {
+ var result = new TreeMap>();
+ for (String group : groups) {
+ for (RightSettings right : rights.getOrDefault(group, List.of())) {
+ result.computeIfAbsent(right.repository(), alias -> EnumSet.noneOf(Action.class))
+ .addAll(right.actions());
+ }
+ }
+ return result;
+ }
+
+ /**
+ * @param groups the user's groups
+ * @param repository the repository alias
+ * @param action the action
+ * @return whether one of the groups maps the action on the repository
+ */
+ public boolean permits(Collection groups, String repository, Action action) {
+ return rightsOf(groups).getOrDefault(repository, Set.of()).contains(action);
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/SessionJanitor.java b/trailhand/src/main/java/de/cuioss/trailhand/security/SessionJanitor.java
new file mode 100644
index 0000000..d34af50
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/security/SessionJanitor.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.security;
+
+import de.cuioss.sheriff.token.client.lifecycle.TokenLifecycleManager;
+import io.quarkus.runtime.ShutdownEvent;
+import io.quarkus.runtime.StartupEvent;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.event.Observes;
+import org.jspecify.annotations.Nullable;
+
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Removes expired sessions every minute and drops their tokens (TRH-AUTH-1: idle timeout and absolute lifetime).
+ */
+@ApplicationScoped
+public class SessionJanitor {
+
+ private final SessionStore sessions;
+ private final TokenLifecycleManager tokens;
+ private @Nullable ScheduledExecutorService scheduler;
+
+ /**
+ * @param sessions the sessions
+ * @param tokens the tokens of the sessions
+ */
+ public SessionJanitor(SessionStore sessions, TokenLifecycleManager tokens) {
+ this.sessions = sessions;
+ this.tokens = tokens;
+ }
+
+ void onStart(@Observes StartupEvent event) {
+ scheduler = Executors.newSingleThreadScheduledExecutor(Thread.ofVirtual().name("trailhand-sessions").factory());
+ scheduler.scheduleWithFixedDelay(this::evict, 1, 1, TimeUnit.MINUTES);
+ }
+
+ void onStop(@Observes ShutdownEvent event) {
+ if (scheduler != null) {
+ scheduler.shutdownNow();
+ }
+ }
+
+ void evict() {
+ sessions.evictExpired().forEach(tokens::revokeAndClear);
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/SessionStore.java b/trailhand/src/main/java/de/cuioss/trailhand/security/SessionStore.java
new file mode 100644
index 0000000..572236e
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/security/SessionStore.java
@@ -0,0 +1,147 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.security;
+
+import de.cuioss.trailhand.config.TrailhandConfiguration;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.security.SecureRandom;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * The web sessions, held in memory (TRH-AUTH-1, TRH-GEN-3: sessions are lost on restart; ADR-0001: one instance).
+ * A session ends after the idle timeout or the absolute lifetime of {@code web.session}.
+ */
+@ApplicationScoped
+public class SessionStore {
+
+ private static final SecureRandom RANDOM = new SecureRandom();
+
+ private final Map sessions = new ConcurrentHashMap<>();
+ /** The ids of sessions {@link #use(String)} found expired, until {@link #evictExpired()} hands them on. */
+ private final Queue ended = new ConcurrentLinkedQueue<>();
+ private final Duration idleTimeout;
+ private final Duration maxLifetime;
+ private final Clock clock;
+
+ /**
+ * @param configuration the configuration with the session lifetimes
+ */
+ @Inject
+ public SessionStore(TrailhandConfiguration configuration) {
+ this(configuration.web().idleTimeout(), configuration.web().maxLifetime(), Clock.systemUTC());
+ }
+
+ /**
+ * @param idleTimeout the idle timeout
+ * @param maxLifetime the absolute lifetime
+ * @param clock the clock
+ */
+ SessionStore(Duration idleTimeout, Duration maxLifetime, Clock clock) {
+ this.idleTimeout = idleTimeout;
+ this.maxLifetime = maxLifetime;
+ this.clock = clock;
+ }
+
+ /**
+ * @return a random, URL-safe token of 256 bits
+ */
+ public static String randomToken() {
+ byte[] bytes = new byte[32];
+ RANDOM.nextBytes(bytes);
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ }
+
+ /**
+ * Opens a session for a completed login.
+ *
+ * @param identity the identity values of the login
+ * @return the new session
+ */
+ public UserSession open(LoginIdentity identity) {
+ var now = clock.instant();
+ var session = new UserSession(randomToken(), identity.issuer(), identity.subject(), identity.name(),
+ identity.groups(), identity.authTime(), identity.acr(), randomToken(), now, now);
+ sessions.put(session.id(), session);
+ return session;
+ }
+
+ /**
+ * Finds a live session and records the access; an expired one is removed, and its id is kept for
+ * {@link #evictExpired()}, which hands it on so its tokens are dropped. Check and renewal are one atomic step: a
+ * session closed meanwhile is not brought back.
+ *
+ * @param id the session id from the cookie
+ * @return the session, or empty when unknown or expired
+ */
+ public Optional use(String id) {
+ var found = new AtomicBoolean();
+ var touched = sessions.computeIfPresent(id, (key, session) -> {
+ found.set(true);
+ // The clock is read inside the atomic step: an older request cannot undo a newer renewal.
+ var now = clock.instant();
+ return expired(session, now) ? null : session.touched(now);
+ });
+ if (touched == null && found.get()) {
+ ended.add(id);
+ }
+ return Optional.ofNullable(touched);
+ }
+
+ /**
+ * @param id the session id
+ * @return the removed session, if it existed
+ */
+ public Optional close(String id) {
+ return Optional.ofNullable(sessions.remove(id));
+ }
+
+ /**
+ * Removes every expired session. A session is removed only as it was found expired: one renewed meanwhile stays.
+ *
+ * @return the ids of the sessions removed here or found expired by {@link #use(String)} since the last call, so
+ * their tokens can be dropped
+ */
+ public List evictExpired() {
+ var now = clock.instant();
+ var removed = new ArrayList();
+ for (UserSession session : sessions.values()) {
+ if (expired(session, now) && sessions.remove(session.id(), session)) {
+ removed.add(session.id());
+ }
+ }
+ for (String id = ended.poll(); id != null; id = ended.poll()) {
+ removed.add(id);
+ }
+ return removed;
+ }
+
+ private boolean expired(UserSession session, Instant now) {
+ return session.lastAccess().plus(idleTimeout).isBefore(now) || session.created().plus(maxLifetime).isBefore(now);
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/TokenClientNativeRegistration.java b/trailhand/src/main/java/de/cuioss/trailhand/security/TokenClientNativeRegistration.java
new file mode 100644
index 0000000..92b46f5
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/security/TokenClientNativeRegistration.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.security;
+
+import de.cuioss.sheriff.token.client.discovery.ProviderMetadata;
+import de.cuioss.sheriff.token.client.discovery._ProviderMetadata_DslJsonConverter;
+import de.cuioss.sheriff.token.client.flow.ParResponse;
+import de.cuioss.sheriff.token.client.flow._ParResponse_DslJsonConverter;
+import de.cuioss.sheriff.token.client.internal.AccessTokenConfirmation;
+import de.cuioss.sheriff.token.client.internal._AccessTokenConfirmation$Confirmation_DslJsonConverter;
+import de.cuioss.sheriff.token.client.internal._AccessTokenConfirmation$JsonObjectProbe_DslJsonConverter;
+import de.cuioss.sheriff.token.client.internal._AccessTokenConfirmation_DslJsonConverter;
+import de.cuioss.sheriff.token.client.token.TokenErrorResponse;
+import de.cuioss.sheriff.token.client.token.TokenResponse;
+import de.cuioss.sheriff.token.client.token.UserInfoResponse;
+import de.cuioss.sheriff.token.client.token._TokenErrorResponse_DslJsonConverter;
+import de.cuioss.sheriff.token.client.token._TokenResponse_DslJsonConverter;
+import de.cuioss.sheriff.token.client.token._UserInfoResponse_DslJsonConverter;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+/**
+ * Registers the response types of Token Sheriff's client and their generated DSL-JSON converters for reflection, so
+ * the client can read the provider's answers (discovery, token, error, PAR, user info, confirmation) in the native
+ * image (TRH-OPS-1). DSL-JSON finds a converter by name and instantiates it reflectively; without the registration the
+ * native image answers "Unable to find reader for provided type". The same registration as API Sheriff's
+ * {@code TokenClientDslJsonReflection}; naming the classes by symbol makes a rename in the client fail the build.
+ */
+@RegisterForReflection(targets = {
+ _ProviderMetadata_DslJsonConverter.class,
+ _ParResponse_DslJsonConverter.class,
+ _TokenResponse_DslJsonConverter.class,
+ _TokenErrorResponse_DslJsonConverter.class,
+ _UserInfoResponse_DslJsonConverter.class,
+ _AccessTokenConfirmation_DslJsonConverter.class,
+ _AccessTokenConfirmation$Confirmation_DslJsonConverter.class,
+ _AccessTokenConfirmation$JsonObjectProbe_DslJsonConverter.class,
+ ProviderMetadata.class,
+ ParResponse.class,
+ TokenResponse.class,
+ TokenErrorResponse.class,
+ UserInfoResponse.class,
+ AccessTokenConfirmation.class,
+ AccessTokenConfirmation.Confirmation.class,
+ AccessTokenConfirmation.JsonObjectProbe.class
+})
+public final class TokenClientNativeRegistration {
+
+ private TokenClientNativeRegistration() {
+ // registration holder
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/UserSession.java b/trailhand/src/main/java/de/cuioss/trailhand/security/UserSession.java
new file mode 100644
index 0000000..6407f33
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/security/UserSession.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.security;
+
+import org.jspecify.annotations.Nullable;
+
+import java.time.Instant;
+import java.util.List;
+
+/**
+ * A server-side web session (TRH-AUTH-1): the identity values of the login, the anti-CSRF token and the lifetimes.
+ * The browser holds only the opaque session id in a cookie; tokens stay in Token Sheriff's token store under the
+ * same id.
+ *
+ * @param id the opaque session id, the cookie value
+ * @param issuer {@code iss}
+ * @param subject {@code sub}
+ * @param name the display name from the token
+ * @param groups the groups the rights are mapped from
+ * @param authTime {@code auth_time}, or {@code null} when the token carries none
+ * @param acr {@code acr}, or {@code null}
+ * @param csrfToken the anti-CSRF token of TRH-WEB-8
+ * @param created when the session began
+ * @param lastAccess when the session was last used
+ */
+public record UserSession(String id, String issuer, String subject, String name, List groups,
+@Nullable Instant authTime, @Nullable String acr, String csrfToken, Instant created, Instant lastAccess) {
+
+ /**
+ * Copies the groups.
+ *
+ * @param id the id
+ * @param issuer the issuer
+ * @param subject the subject
+ * @param name the name
+ * @param groups the groups
+ * @param authTime the authentication time
+ * @param acr the authentication context class
+ * @param csrfToken the anti-CSRF token
+ * @param created the start
+ * @param lastAccess the last use
+ */
+ public UserSession {
+ groups = List.copyOf(groups);
+ }
+
+ /**
+ * @param now the time of the access
+ * @return this session, used at {@code now}
+ */
+ public UserSession touched(Instant now) {
+ return new UserSession(id, issuer, subject, name, groups, authTime, acr, csrfToken, created, now);
+ }
+
+ @Override
+ public String toString() {
+ return "UserSession[issuer=" + issuer + ", created=" + created + "]";
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/security/package-info.java b/trailhand/src/main/java/de/cuioss/trailhand/security/package-info.java
new file mode 100644
index 0000000..2cc8987
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/security/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/**
+ * Rights mapping, the server-side session and the login through Token Sheriff (TRH-AUTH-1, TRH-AUTH-2).
+ */
+@NullMarked
+package de.cuioss.trailhand.security;
+
+import org.jspecify.annotations.NullMarked;
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/service/GitRemoteHealthCheck.java b/trailhand/src/main/java/de/cuioss/trailhand/service/GitRemoteHealthCheck.java
new file mode 100644
index 0000000..2905d6e
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/service/GitRemoteHealthCheck.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.service;
+
+import io.smallrye.health.api.HealthGroup;
+import jakarta.enterprise.context.ApplicationScoped;
+import org.eclipse.microprofile.health.HealthCheck;
+import org.eclipse.microprofile.health.HealthCheckResponse;
+
+/**
+ * The check {@code git-remote} (TRH-GEN-6): {@code DOWN} while the fetch of a repository fails, with the fetch state
+ * per alias. It is a health group of its own ({@code /q/health/group/git-remote}), so an unreachable Git server
+ * neither drops readiness nor restarts the container.
+ */
+@HealthGroup("git-remote")
+@ApplicationScoped
+public class GitRemoteHealthCheck implements HealthCheck {
+
+ private final RepositoryService repositories;
+
+ /**
+ * @param repositories the repository service
+ */
+ public GitRemoteHealthCheck(RepositoryService repositories) {
+ this.repositories = repositories;
+ }
+
+ @Override
+ public HealthCheckResponse call() {
+ var snapshot = repositories.states();
+ var builder = HealthCheckResponse.named("git-remote").status(!RepositoryService.degraded(snapshot));
+ for (RepositoryState state : snapshot) {
+ builder.withData(state.alias(), state.fetchUp() ? "UP" : "DOWN");
+ }
+ return builder.build();
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoriesHealthCheck.java b/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoriesHealthCheck.java
new file mode 100644
index 0000000..15d7f40
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoriesHealthCheck.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.service;
+
+import jakarta.enterprise.context.ApplicationScoped;
+import org.eclipse.microprofile.health.HealthCheck;
+import org.eclipse.microprofile.health.HealthCheckResponse;
+import org.eclipse.microprofile.health.Readiness;
+
+/**
+ * The readiness check {@code repositories} (TRH-OPS-2): {@code UP} once every repository has a local copy; a later
+ * fetch failure does not drop it. The data name the fetch state per alias.
+ */
+@Readiness
+@ApplicationScoped
+public class RepositoriesHealthCheck implements HealthCheck {
+
+ private final RepositoryService repositories;
+
+ /**
+ * @param repositories the repository service
+ */
+ public RepositoriesHealthCheck(RepositoryService repositories) {
+ this.repositories = repositories;
+ }
+
+ @Override
+ public HealthCheckResponse call() {
+ var snapshot = repositories.states();
+ var builder = HealthCheckResponse.named("repositories").status(RepositoryService.allPresent(snapshot));
+ for (RepositoryState state : snapshot) {
+ builder.withData(state.alias(), describe(state));
+ }
+ return builder.build();
+ }
+
+ /**
+ * @param state the state of one repository
+ * @return {@code ABSENT}, {@code UP} or {@code FETCH_DOWN}
+ */
+ static String describe(RepositoryState state) {
+ if (!state.present()) {
+ return "ABSENT";
+ }
+ return state.fetchUp() ? "UP" : "FETCH_DOWN";
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryLifecycle.java b/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryLifecycle.java
new file mode 100644
index 0000000..a35f091
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryLifecycle.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.service;
+
+import de.cuioss.tools.logging.CuiLogger;
+import de.cuioss.trailhand.config.TrailhandConfiguration;
+import io.quarkus.runtime.ShutdownEvent;
+import io.quarkus.runtime.StartupEvent;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.event.Observes;
+import jakarta.enterprise.inject.Produces;
+import jakarta.inject.Singleton;
+import org.eclipse.microprofile.config.inject.ConfigProperty;
+import org.jspecify.annotations.Nullable;
+
+import java.nio.file.Path;
+import java.util.Objects;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import static de.cuioss.trailhand.TrailhandLogMessages.WARN;
+
+/**
+ * Creates the {@link RepositoryService} at boot, clones or opens every repository in the background and fetches at
+ * {@code fetch.interval} (TRH-CONF-2). The boot does not wait for the Git server: readiness reports the state
+ * (TRH-OPS-2).
+ */
+@ApplicationScoped
+public class RepositoryLifecycle {
+
+ private static final CuiLogger LOGGER = new CuiLogger(RepositoryLifecycle.class);
+
+ private final TrailhandConfiguration configuration;
+ private final Path dataDirectory;
+ private @Nullable ScheduledExecutorService scheduler;
+ private @Nullable RepositoryService service;
+
+ /**
+ * @param configuration the configuration
+ * @param dataDirectory the data directory, {@code trailhand.data.dir}
+ */
+ public RepositoryLifecycle(TrailhandConfiguration configuration,
+ @ConfigProperty(name = "trailhand.data.dir", defaultValue = "data") String dataDirectory) {
+ this.configuration = configuration;
+ this.dataDirectory = Path.of(dataDirectory);
+ }
+
+ /**
+ * @return the repository service
+ * @throws IllegalStateException if the library refuses the repositories
+ */
+ @Produces
+ // @Singleton, not @ApplicationScoped: the service is used directly, without a client proxy, by the health checks
+ // and the web resources.
+ @Singleton
+ public synchronized RepositoryService repositoryService() {
+ if (service == null) {
+ var created = RepositoryService.create(configuration.repositories(), dataDirectory);
+ if (created.value() == null) {
+ throw new IllegalStateException("repositories refused: " + created.detail());
+ }
+ service = created.value();
+ }
+ return Objects.requireNonNull(service);
+ }
+
+ void onStart(@Observes StartupEvent event) {
+ var repositories = repositoryService();
+ scheduler = Executors.newSingleThreadScheduledExecutor(Thread.ofVirtual().name("trailhand-fetch").factory());
+ long interval = configuration.fetchInterval().toMillis();
+ scheduler.scheduleWithFixedDelay(() -> refreshSafely(repositories), 0, interval, TimeUnit.MILLISECONDS);
+ }
+
+ /**
+ * Runs one refresh; a failure is logged and the next refresh runs as planned. A scheduled task that throws would
+ * otherwise end the periodic fetch silently.
+ *
+ * @param repositories the repository service
+ */
+ static void refreshSafely(RepositoryService repositories) {
+ try {
+ repositories.refresh();
+ // Deliberately broad: whatever a refresh throws must not end the periodic fetch.
+ // cui-rewrite:disable InvalidExceptionUsageRecipe
+ } catch (RuntimeException | LinkageError e) {
+ LOGGER.warn(e, WARN.REFRESH_FAILED, e.getClass().getName(), e.getMessage());
+ }
+ }
+
+ void onStop(@Observes ShutdownEvent event) {
+ if (scheduler != null) {
+ scheduler.shutdownNow();
+ }
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryService.java b/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryService.java
new file mode 100644
index 0000000..676c500
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryService.java
@@ -0,0 +1,255 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.service;
+
+import de.cuioss.git.document.core.GitOutcome;
+import de.cuioss.git.document.core.JGitRepositoryOperations;
+import de.cuioss.git.document.core.RemotePolicy;
+import de.cuioss.git.document.core.RepositoryOperations;
+import de.cuioss.git.document.store.RepositoryRegistry;
+import de.cuioss.git.document.store.StoreRepository;
+import de.cuioss.tools.logging.CuiLogger;
+import de.cuioss.trailhand.config.RepositorySettings;
+import org.jspecify.annotations.Nullable;
+
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.locks.ReentrantLock;
+
+import static de.cuioss.trailhand.TrailhandLogMessages.INFO;
+import static de.cuioss.trailhand.TrailhandLogMessages.WARN;
+
+/**
+ * Keeps a local bare copy of every configured repository below the data directory and fetches it (TRH-CONF-2,
+ * TRH-OPS-2, TRH-GEN-6), through the {@code git-document-repository} libraries only (TRH-GEN-4).
+ *
+ * A repository is present once a clone exists, whether made now or kept on the volume; a failed fetch later
+ * keeps it present and marks only its fetch {@code DOWN}, so readiness stays {@code UP} while reads are served from
+ * the last fetched state. Signing, anchoring and saving join with the save operation.
+ */
+public class RepositoryService {
+
+ private static final CuiLogger LOGGER = new CuiLogger(RepositoryService.class);
+
+ /** The directory below the data directory that holds the bare repositories. */
+ public static final String REPOSITORIES_DIR = "repositories";
+
+ private static final List FETCH_SPECS = List.of("+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*",
+ "+refs/notes/*:refs/notes/*");
+ private static final List PUSH_SPECS = List.of("refs/heads/main:refs/heads/main");
+
+ private final RepositoryRegistry registry;
+ private final RepositoryOperations operations;
+ private final Path repositoriesDir;
+ /** The fetch state per alias; guarded by the monitor of this service, which is never held during Git transport. */
+ private final Map states = new LinkedHashMap<>();
+ /** Keeps refreshes one at a time without blocking the readers of the state. */
+ private final ReentrantLock refreshLock = new ReentrantLock();
+
+ /**
+ * @param registry the validated repositories
+ * @param operations the Git operations of the library
+ * @param dataDirectory the data directory, {@code /app/data} in the container
+ */
+ public RepositoryService(RepositoryRegistry registry, RepositoryOperations operations, Path dataDirectory) {
+ this.registry = registry;
+ this.operations = operations;
+ this.repositoriesDir = dataDirectory.resolve(REPOSITORIES_DIR);
+ registry.repositories().forEach(repository -> states.put(repository.alias(),
+ new RepositoryState(repository.alias(), false, false)));
+ }
+
+ /**
+ * Builds the registry and the operations for configured repositories.
+ *
+ * @param settings the repositories of {@code trailhand.yaml}
+ * @param dataDirectory the data directory
+ * @return the service, or the library's refusal of the repositories as detail
+ */
+ public static ServiceResult create(List settings, Path dataDirectory) {
+ var policy = remotePolicy(settings);
+ if (policy.isEmpty()) {
+ return ServiceResult.refused("the https remotes must share one origin");
+ }
+ var repositories = settings.stream()
+ .map(entry -> new StoreRepository(entry.alias(), libraryRemote(entry), entry.confidentiality(),
+ entry.retention()))
+ .toList();
+ var registry = RepositoryRegistry.of(repositories, policy.get());
+ var value = registry.value();
+ if (!registry.isOk() || value == null) {
+ return ServiceResult.refused(String.valueOf(registry.detail()));
+ }
+ return ServiceResult.ok(new RepositoryService(value, new JGitRepositoryOperations(policy.get()), dataDirectory));
+ }
+
+ /**
+ * The remote as the library takes it: an {@code https} URL unchanged, a {@code file:} URL as the absolute path of the
+ * local bare repository (relative to the working directory).
+ *
+ * @param settings the repository
+ * @return the remote for the library
+ */
+ static String libraryRemote(RepositorySettings settings) {
+ if (!settings.isLocal()) {
+ return settings.remote();
+ }
+ var path = settings.remote().substring("file:".length());
+ while (path.startsWith("//")) {
+ path = path.substring(1);
+ }
+ return Path.of(path).toAbsolutePath().normalize().toString();
+ }
+
+ /**
+ * The policy of the library admits local repositories and at most one HTTPS origin.
+ *
+ * @param settings the repositories
+ * @return the policy, or empty when the HTTPS remotes name more than one origin
+ */
+ static Optional remotePolicy(List settings) {
+ var origins = settings.stream().filter(entry -> !entry.isLocal()).map(entry -> URI.create(entry.remote()))
+ .map(uri -> URI.create("https://" + uri.getRawAuthority())).distinct().toList();
+ if (origins.isEmpty()) {
+ return Optional.of(RemotePolicy.localOnly());
+ }
+ return origins.size() == 1 ? Optional.of(RemotePolicy.httpsOrigin(origins.getFirst())) : Optional.empty();
+ }
+
+ /**
+ * Makes sure every repository has a local copy: an existing one is opened, a missing one is cloned. A repository
+ * whose clone fails stays absent; the next refresh tries again. Refreshes run one at a time; the state stays
+ * readable while a clone or fetch waits for the remote.
+ */
+ public void refresh() {
+ refreshLock.lock();
+ try {
+ for (StoreRepository repository : registry.repositories()) {
+ var gitDir = repositoriesDir.resolve(repository.alias() + ".git");
+ if (isPresent(repository.alias())) {
+ fetch(repository, gitDir);
+ } else {
+ cloneOrOpen(repository, gitDir);
+ }
+ }
+ } finally {
+ refreshLock.unlock();
+ }
+ }
+
+ private synchronized boolean isPresent(String alias) {
+ var known = states.get(alias);
+ return known != null && known.present();
+ }
+
+ private synchronized void recordState(RepositoryState state) {
+ states.put(state.alias(), state);
+ }
+
+ private void cloneOrOpen(StoreRepository repository, Path gitDir) {
+ var existed = Files.isDirectory(gitDir);
+ var result = operations.cloneIfMissing(
+ new RepositoryOperations.CloneInput(gitDir, repository.remote(), PUSH_SPECS, null));
+ if (result.outcome() == GitOutcome.OK) {
+ LOGGER.info(INFO.REPOSITORY_READY, repository.alias());
+ // A fresh clone has reached the remote; an existing one is opened without it, so its fetch state stays
+ // DOWN until the fetch below succeeds.
+ recordState(new RepositoryState(repository.alias(), true, !existed));
+ fetch(repository, gitDir);
+ } else {
+ LOGGER.warn(WARN.CLONE_FAILED, repository.alias(), result.outcome(), result.detail());
+ recordState(new RepositoryState(repository.alias(), false, false));
+ }
+ }
+
+ private void fetch(StoreRepository repository, Path gitDir) {
+ var result = operations.fetch(new RepositoryOperations.FetchInput(gitDir, "origin", FETCH_SPECS, null));
+ boolean up = result.outcome() == GitOutcome.OK;
+ if (!up) {
+ LOGGER.warn(WARN.FETCH_FAILED, repository.alias(), result.outcome(), result.detail());
+ }
+ recordState(new RepositoryState(repository.alias(), true, up));
+ }
+
+ /**
+ * @return the state of every repository, in configuration order
+ */
+ public synchronized List states() {
+ return new ArrayList<>(states.values());
+ }
+
+ /**
+ * @return whether every repository has a local copy (the readiness check {@code repositories})
+ */
+ public boolean allPresent() {
+ return allPresent(states());
+ }
+
+ /**
+ * @return whether a repository's last fetch failed (the degraded state of TRH-GEN-6)
+ */
+ public boolean degraded() {
+ return degraded(states());
+ }
+
+ /**
+ * @param snapshot the states from one call of {@link #states()}
+ * @return whether every repository of the snapshot has a local copy
+ */
+ public static boolean allPresent(List snapshot) {
+ return snapshot.stream().allMatch(RepositoryState::present);
+ }
+
+ /**
+ * @param snapshot the states from one call of {@link #states()}
+ * @return whether a repository of the snapshot failed its last fetch
+ */
+ public static boolean degraded(List snapshot) {
+ return snapshot.stream().anyMatch(state -> !state.fetchUp());
+ }
+
+ /**
+ * @param alias an alias
+ * @return the local git directory of a configured repository
+ */
+ public Optional gitDirectory(String alias) {
+ return registry.find(alias).map(repository -> repositoriesDir.resolve(repository.alias() + ".git"));
+ }
+
+ /**
+ * The result of {@link #create(List, Path)}.
+ *
+ * @param value the service, or {@code null} when refused
+ * @param detail the reason of a refusal
+ * @param the value type
+ */
+ public record ServiceResult(@Nullable V value, @Nullable String detail) {
+
+ static ServiceResult ok(V value) {
+ return new ServiceResult<>(value, null);
+ }
+
+ static ServiceResult refused(String detail) {
+ return new ServiceResult<>(null, detail);
+ }
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryState.java b/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryState.java
new file mode 100644
index 0000000..4f961ab
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/service/RepositoryState.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.service;
+
+/**
+ * The fetch state of one repository as the status request and the health checks report it (TRH-OPS-2, TRH-GEN-6).
+ *
+ * @param alias the alias
+ * @param present whether a valid local repository exists (fetched now or kept from an earlier fetch)
+ * @param fetchUp whether the last fetch succeeded
+ */
+public record RepositoryState(String alias, boolean present, boolean fetchUp) {
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/service/package-info.java b/trailhand/src/main/java/de/cuioss/trailhand/service/package-info.java
new file mode 100644
index 0000000..84389ff
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/service/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/**
+ * Application services over the git-document-repository libraries; the only package that uses them (TRH-GEN-4).
+ */
+@NullMarked
+package de.cuioss.trailhand.service;
+
+import org.jspecify.annotations.NullMarked;
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/ApiAnswers.java b/trailhand/src/main/java/de/cuioss/trailhand/web/ApiAnswers.java
new file mode 100644
index 0000000..1828958
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/web/ApiAnswers.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.web;
+
+import lombok.experimental.UtilityClass;
+
+/**
+ * The JSON bodies of the refusals of TRH-WEB-9, written by the request gate before any resource runs.
+ */
+@UtilityClass
+public class ApiAnswers {
+
+ /** The login address a {@code 401} names. */
+ public static final String LOGIN_ADDRESS = "/api/v1/auth/login";
+
+ /** {@code 401 UNAUTHENTICATED}. */
+ public static final String UNAUTHENTICATED = "{\"outcome\":\"UNAUTHENTICATED\",\"login\":\"" + LOGIN_ADDRESS + "\"}";
+
+ /** {@code 403 CSRF_REJECTED}. */
+ public static final String CSRF_REJECTED = "{\"outcome\":\"CSRF_REJECTED\"}";
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/AuthResource.java b/trailhand/src/main/java/de/cuioss/trailhand/web/AuthResource.java
new file mode 100644
index 0000000..6b79d95
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/web/AuthResource.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.web;
+
+import de.cuioss.sheriff.token.commons.error.TokenSheriffException;
+import de.cuioss.trailhand.security.LoginService;
+import de.cuioss.trailhand.security.LoginTransactions;
+import de.cuioss.trailhand.security.UserSession;
+import io.vertx.ext.web.RoutingContext;
+import jakarta.ws.rs.CookieParam;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.QueryParam;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.UriInfo;
+import org.jspecify.annotations.Nullable;
+
+import java.net.URI;
+import java.util.Map;
+
+/**
+ * The login endpoints of TRH-AUTH-1: {@code GET /api/v1/auth/login?return=}, the provider's redirect back to
+ * {@code GET /api/v1/auth/callback} ({@code response_mode=query}), and {@code POST /api/v1/auth/logout}.
+ *
+ * The callback answers a small same-origin page that navigates to the checked {@code return} by
+ * {@code }, not a redirect: the navigation it starts is same-site and carries the
+ * {@code SameSite=Strict} session cookie (TRH-AUTH-1, TRH-WEB-9).
+ */
+@Path(AuthResource.PATH)
+public class AuthResource {
+
+ /** The root of the login requests. */
+ public static final String PATH = "/api/v1/auth";
+
+ /** The start of the login, below {@link #PATH}; public. */
+ public static final String LOGIN_PATH = "/login";
+
+ /** The provider's return, below {@link #PATH}; public. */
+ public static final String CALLBACK_PATH = "/callback";
+
+ private static final String SET_COOKIE = "Set-Cookie";
+ private static final String CACHE_CONTROL = "Cache-Control";
+ private static final String NO_STORE = "no-store";
+
+ private final LoginService login;
+ private final MessageCatalogue messages;
+
+ /**
+ * @param login the login service
+ * @param messages the catalogue for the callback page
+ */
+ public AuthResource(LoginService login, MessageCatalogue messages) {
+ this.login = login;
+ this.messages = messages;
+ }
+
+ /**
+ * Starts the login.
+ *
+ * @param returnAddress the address to return to
+ * @return a redirect to the provider with the login-transaction cookie, {@code 502} when the provider cannot be
+ * used, or {@code 503} when too many logins are pending
+ */
+ @GET
+ @Path(LOGIN_PATH)
+ public Response start(@QueryParam("return") @Nullable String returnAddress) {
+ try {
+ var started = login.start(returnAddress);
+ return Response.status(302).location(URI.create(started.authorizationUrl()))
+ .header(SET_COOKIE, Cookies.loginCookie(started.transactionReference(), LoginTransactions.LIFETIME))
+ .header(CACHE_CONTROL, NO_STORE).build();
+ } catch (LoginService.TooManyLoginsException e) {
+ return Response.status(503).type(MediaType.APPLICATION_JSON).header("Retry-After", "60")
+ .header(CACHE_CONTROL, NO_STORE).entity(Map.of("outcome", "TOO_MANY_LOGINS")).build();
+ } catch (TokenSheriffException | IllegalArgumentException | IllegalStateException e) {
+ return Response.status(502).type(MediaType.APPLICATION_JSON)
+ .entity(Map.of("outcome", "IDENTITY_PROVIDER_UNAVAILABLE")).build();
+ }
+ }
+
+ /**
+ * Completes the login from the provider's redirect.
+ *
+ * @param transaction the login-transaction cookie
+ * @param uriInfo the request address with {@code code}, {@code state} and {@code iss}
+ * @return the page that navigates to the return address with the session cookie, or a page that offers a new
+ * login
+ */
+ @GET
+ @Path(CALLBACK_PATH)
+ @Produces(MediaType.TEXT_HTML)
+ public Response callback(@CookieParam(Cookies.LOGIN) @Nullable String transaction, @Context UriInfo uriInfo) {
+ var query = uriInfo.getRequestUri().getRawQuery();
+ var completed = login.complete(transaction, query == null ? "" : query);
+ var clearLogin = Cookies.expired(Cookies.LOGIN, "Lax");
+ if (completed.isEmpty()) {
+ var page = page(null, messages.english("auth.callback.failed"), "/api/v1/auth/login?return=/",
+ messages.english("auth.callback.retry"));
+ return Response.status(400).entity(page).header(SET_COOKIE, clearLogin)
+ .header(CACHE_CONTROL, NO_STORE).build();
+ }
+ var target = completed.get().returnAddress();
+ var page = page(target, null, target, messages.english("auth.callback.continue"));
+ return Response.ok(page).header(SET_COOKIE, clearLogin)
+ .header(SET_COOKIE, Cookies.sessionCookie(completed.get().session().id()))
+ .header(CACHE_CONTROL, NO_STORE).build();
+ }
+
+ /**
+ * Ends the session (RP-initiated logout); the gate has checked the anti-CSRF header.
+ *
+ * @param context the routing context with the session
+ * @return the address the web app navigates to
+ */
+ @POST
+ @Path("/logout")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response logout(@Context RoutingContext context) {
+ UserSession session = context.get(RequestGate.SESSION_KEY);
+ var redirect = login.logout(session.id());
+ return Response.ok(Map.of("redirect", redirect)).header(SET_COOKIE, Cookies.expired(Cookies.SESSION, "Strict"))
+ .header(CACHE_CONTROL, NO_STORE).build();
+ }
+
+ private String page(@Nullable String refreshTo, @Nullable String text, String link, String linkText) {
+ var refresh = refreshTo == null ? ""
+ : "";
+ var paragraph = text == null ? "" : "
" + escape(text) + "
";
+ return "" + refresh + ""
+ + escape(messages.english("auth.callback.title")) + "" + paragraph
+ + "" + escape(linkText) + "
";
+ }
+
+ static String escape(String text) {
+ return text.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """)
+ .replace("'", "'");
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/Cookies.java b/trailhand/src/main/java/de/cuioss/trailhand/web/Cookies.java
new file mode 100644
index 0000000..ec894a9
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/web/Cookies.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.web;
+
+import lombok.experimental.UtilityClass;
+
+import java.time.Duration;
+
+/**
+ * The two cookies of TRH-AUTH-1. Both carry the {@code __Host-} prefix: {@code Secure}, {@code Path=/}, no
+ * {@code Domain}.
+ */
+@UtilityClass
+public class Cookies {
+
+ /** The session cookie. */
+ public static final String SESSION = "__Host-trailhand-session";
+
+ /** The login-transaction cookie. */
+ public static final String LOGIN = "__Host-trailhand-login";
+
+ /**
+ * @param sessionId the session id
+ * @return the {@code Set-Cookie} value of the session: {@code SameSite=Strict}
+ */
+ public static String sessionCookie(String sessionId) {
+ return SESSION + "=" + sessionId + "; Path=/; Secure; HttpOnly; SameSite=Strict";
+ }
+
+ /**
+ * The login-transaction cookie: {@code SameSite=Lax}, because the browser sends no {@code Strict} cookie with the
+ * cross-site navigation back from the identity provider, and the callback is such a navigation by {@code GET}
+ * ({@code response_mode=query}). It carries only an opaque reference, lives ten minutes and is deleted by the
+ * callback.
+ *
+ * @param reference the transaction reference
+ * @param maxAge the lifetime
+ * @return the {@code Set-Cookie} value
+ */
+ public static String loginCookie(String reference, Duration maxAge) {
+ return LOGIN + "=" + reference + "; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=" + maxAge.toSeconds();
+ }
+
+ /**
+ * @param name a cookie name of this class
+ * @param sameSite the {@code SameSite} value it was set with
+ * @return the {@code Set-Cookie} value that deletes it
+ */
+ public static String expired(String name, String sameSite) {
+ return name + "=; Path=/; Secure; HttpOnly; SameSite=" + sameSite + "; Max-Age=0";
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/DueResource.java b/trailhand/src/main/java/de/cuioss/trailhand/web/DueResource.java
new file mode 100644
index 0000000..b9fea82
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/web/DueResource.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.web;
+
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.MediaType;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * {@code GET /api/v1/due} (TRH-WEB-9): the launcher of the Due lens. Empty until the index and the reminders are built
+ * (TRH-GEN-3).
+ */
+@Path("/api/v1/due")
+public class DueResource {
+
+ /**
+ * @return the due entries
+ */
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ public Map> due() {
+ return Map.of("items", List.of());
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/EventStream.java b/trailhand/src/main/java/de/cuioss/trailhand/web/EventStream.java
new file mode 100644
index 0000000..b9c5dc4
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/web/EventStream.java
@@ -0,0 +1,137 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.web;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import de.cuioss.trailhand.service.RepositoryService;
+import io.quarkus.runtime.ShutdownEvent;
+import io.quarkus.runtime.StartupEvent;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.event.Observes;
+import jakarta.ws.rs.sse.Sse;
+import jakarta.ws.rs.sse.SseBroadcaster;
+import jakarta.ws.rs.sse.SseEventSink;
+import org.eclipse.microprofile.config.inject.ConfigProperty;
+import org.jspecify.annotations.Nullable;
+
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * The one event stream of all browsers (TRH-WEB-9): the event {@code status} when the degraded state changes, and a
+ * comment every 15 seconds so idle connections stay open. {@code document-saved} joins with the save operation.
+ */
+@ApplicationScoped
+public class EventStream {
+
+ private static final String STATUS_EVENT = "status";
+
+ private final RepositoryService repositories;
+ private final String version;
+ private final ObjectMapper mapper = new ObjectMapper();
+ /** The SSE factory and the broadcaster, created with the first connection. */
+ private final AtomicReference<@Nullable Channel> channel = new AtomicReference<>();
+ private final AtomicReference lastStatus = new AtomicReference<>("");
+ /** Orders the initial status of a connection with the status broadcasts. */
+ private final Object statusLock = new Object();
+ private @Nullable ScheduledExecutorService scheduler;
+
+ /**
+ * The SSE factory of the first request and the broadcaster it created.
+ *
+ * @param sse the factory of events
+ * @param broadcaster the broadcaster of all connections
+ */
+ private record Channel(Sse sse, SseBroadcaster broadcaster) {
+ }
+
+ /**
+ * @param repositories the repository service
+ * @param version the application version
+ */
+ public EventStream(RepositoryService repositories,
+ @ConfigProperty(name = "quarkus.application.version", defaultValue = "dev") String version) {
+ this.repositories = repositories;
+ this.version = version;
+ }
+
+ void onStart(@Observes StartupEvent event) {
+ scheduler = Executors.newSingleThreadScheduledExecutor(Thread.ofVirtual().name("trailhand-events").factory());
+ scheduler.scheduleWithFixedDelay(this::tick, 5, 5, TimeUnit.SECONDS);
+ scheduler.scheduleWithFixedDelay(this::keepAlive, 15, 15, TimeUnit.SECONDS);
+ }
+
+ void onStop(@Observes ShutdownEvent event) {
+ if (scheduler != null) {
+ scheduler.shutdownNow();
+ }
+ var current = channel.get();
+ if (current != null) {
+ current.broadcaster().close();
+ }
+ }
+
+ /**
+ * Adds a connection and sends it the current status.
+ *
+ * @param sink the connection
+ * @param sseFactory the SSE factory of the request
+ */
+ void register(SseEventSink sink, Sse sseFactory) {
+ var current = channel.updateAndGet(
+ existing -> existing != null ? existing : new Channel(sseFactory, sseFactory.newBroadcaster()));
+ // One lock with tick(): a status broadcast cannot overtake the initial status of a new connection. A status
+ // that changed since the last tick goes to every connection, so no connection keeps a status the others missed.
+ synchronized (statusLock) {
+ current.broadcaster().register(sink);
+ var status = statusJson();
+ if (status.equals(lastStatus.getAndSet(status))) {
+ sink.send(sseFactory.newEventBuilder().name(STATUS_EVENT).data(status).build());
+ } else {
+ current.broadcaster().broadcast(current.sse().newEventBuilder().name(STATUS_EVENT).data(status).build());
+ }
+ }
+ }
+
+ void tick() {
+ synchronized (statusLock) {
+ var status = statusJson();
+ var previous = lastStatus.getAndSet(status);
+ var current = channel.get();
+ if (!status.equals(previous) && current != null) {
+ current.broadcaster().broadcast(current.sse().newEventBuilder().name(STATUS_EVENT).data(status).build());
+ }
+ }
+ }
+
+ void keepAlive() {
+ var current = channel.get();
+ if (current != null) {
+ current.broadcaster().broadcast(current.sse().newEventBuilder().comment("keepalive").build());
+ }
+ }
+
+ private String statusJson() {
+ try {
+ return mapper.writeValueAsString(StatusResource.current(repositories, version));
+ } catch (JsonProcessingException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/EventsResource.java b/trailhand/src/main/java/de/cuioss/trailhand/web/EventsResource.java
new file mode 100644
index 0000000..c03e6c4
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/web/EventsResource.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.web;
+
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.sse.Sse;
+import jakarta.ws.rs.sse.SseEventSink;
+
+/**
+ * {@code GET /api/v1/events} (TRH-WEB-5, TRH-WEB-9): the event stream of the web app. On connect it sends the event
+ * {@code status}; later events come from {@link EventStream}.
+ */
+@Path("/api/v1/events")
+public class EventsResource {
+
+ private final EventStream stream;
+
+ /**
+ * @param stream the shared stream
+ */
+ public EventsResource(EventStream stream) {
+ this.stream = stream;
+ }
+
+ /**
+ * @param sink the sink of this connection
+ * @param sse the SSE factory
+ */
+ @GET
+ @Produces(MediaType.SERVER_SENT_EVENTS)
+ public void events(@Context SseEventSink sink, @Context Sse sse) {
+ stream.register(sink, sse);
+ }
+}
diff --git a/trailhand/src/main/java/de/cuioss/trailhand/web/MessageCatalogue.java b/trailhand/src/main/java/de/cuioss/trailhand/web/MessageCatalogue.java
new file mode 100644
index 0000000..dd960da
--- /dev/null
+++ b/trailhand/src/main/java/de/cuioss/trailhand/web/MessageCatalogue.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright © 2026-present CUI-OpenSource-Software (info@cuioss.de)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package de.cuioss.trailhand.web;
+
+import jakarta.enterprise.context.ApplicationScoped;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.UncheckedIOException;
+import java.nio.charset.StandardCharsets;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Properties;
+import java.util.TreeMap;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.regex.Pattern;
+
+/**
+ * The message catalogue of TRH-WEB-7, read from {@code META-INF/trailhand/messages/messages_.properties} of the
+ * {@code web-app} JAR (UTF-8). The languages are the catalogue files: a language is served when its file exists, so a
+ * new language needs no list here. Each file is read once.
+ */
+@ApplicationScoped
+public class MessageCatalogue {
+
+ private static final String LOCATION = "META-INF/trailhand/messages/messages_%s.properties";
+ /** A language code as the catalogue files name it; anything else is never looked up. */
+ private static final Pattern LANGUAGE = Pattern.compile("[a-z]{2}");
+ private static final String ENGLISH = "en";
+
+ private final Map>> catalogues = new ConcurrentHashMap<>();
+
+ /**
+ * @param language a language code, such as {@code en} or {@code de}
+ * @return the catalogue, or empty when no catalogue file exists for the language
+ */
+ public Optional