// MIT License - Copyright (c) 2026 EyeTea Solutions ApS (https://spurvik.com) // Spurvik EU AI Act helper for Java 21+ / Spring Boot 3 / Spring AI / LangChain4j / Quarkus / Kotlin. // Zero Maven or Gradle dependencies required — uses Java 21+ standard library only // (`javax.crypto.Mac`, `java.security.MessageDigest`, `java.net.http.HttpClient`). // // Capabilities: // 1. Keyed HMAC-SHA256 digests (`SpurvikGuard.keyedDigest`, `SpurvikGuard.buildTelemetryEventJson`) with // 0 bytes of raw prompt or completion text transmitted (EU AI Act Art. 12 & GDPR Art. 5(1)(c)). // 2. Canonical `spurvik.payload_summary.v1` field-names-only summaries (`SpurvikGuard.buildPayloadSummary`), // hosted pre-execution human approval requests (`SpurvikGuard.requestHumanApproval`, Art. 14), and // constant-time signed Slack/Teams callback verification (`SpurvikGuard.createSignedApprovalLinks`, // `SpurvikGuard.verifySignedCallback`, `SpurvikGuard.runGateSelfTest` — byte-identical to `spurvik/channels`). // 3. Consent-exempt Thymeleaf / JSP / JTE HTML helpers (`SpurvikGuard.art50BadgeHtml` across all 24 official // EU languages with Cookiebot & Usercentrics zero-cookie attributes, and `SpurvikGuard.trustCardHtml`). // // Drop into src/main/java/com/spurvik/guard/SpurvikGuard.java (or run zero-compile JEP 330 self-test): // curl -fsSL https://spurvik.com/r/SpurvikGuard.java -o SpurvikGuard.java && java SpurvikGuard.java yourdomain.eu // // Environment variables (server-only — never expose in browser code): // - SPURVIK_API_KEY: Workspace key from https://console.spurvik.com/signup?plan=pro // (Pro EUR 19/mo or EUR 190/yr · Team EUR 79/mo or EUR 790/yr · Done-For-You EUR 199 once · Free EUR 0) // - SPURVIK_CONTENT_HASH_SECRET: Server-local secret (>= 16 UTF-8 bytes) that never leaves your JVM // - SPURVIK_SIGNING_SECRET: Secret (>= 16 chars) for signed Art. 14 human approval callback links package com.spurvik.guard; import java.net.URI; import java.net.URLDecoder; import java.net.URLEncoder; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.SecureRandom; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.UUID; import java.util.regex.Pattern; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; public final class SpurvikGuard { public static final String VERSION = "1.0.18"; public static final String CONSOLE_BASE_URL = "https://console.spurvik.com"; public static final String BADGE_SCRIPT_SRC = "https://spurvik.com/badge.js"; public static final String TRUST_WIDGET_SRC = "https://spurvik.com/trust-widget.js"; public static final String PAYLOAD_SUMMARY_SCHEMA = "spurvik.payload_summary.v1"; private static final int MAX_SUMMARY_CHARS = 500; private static final int MAX_SUMMARY_KEYS = 32; private static final long DEFAULT_LINK_MAX_AGE_SECONDS = 86_400L; private static final long MAX_LINK_MAX_AGE_SECONDS = 604_800L; private static final long MAX_CLOCK_SKEW_SECONDS = 300L; private static final Set EU_LOCALES = Set.of( "bg", "cs", "da", "de", "el", "en", "es", "et", "fi", "fr", "ga", "hr", "hu", "it", "lt", "lv", "mt", "nl", "pl", "pt", "ro", "sk", "sl", "sv" ); private static final Set NOTICE_KINDS = Set.of( "interaction", "generated", "deepfake", "public-interest", "emotion-biometric" ); private static final Set BADGE_POSITIONS = Set.of( "bottom-right", "bottom-left", "top-right", "top-left", "inline" ); private static final Pattern KEY_PATTERN = Pattern.compile("^[A-Za-z_][A-Za-z0-9_]{0,63}$"); private static final Pattern HEX64_PATTERN = Pattern.compile("^[0-9a-f]{64}$"); private static final Pattern HOST_PATTERN = Pattern.compile("^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$"); private static final Pattern RESERVED_HOST_PATTERN = Pattern.compile("(?:^|\\.)(?:localhost|local|internal|test|invalid|example)$"); private static final SecureRandom RNG = new SecureRandom(); private static final HttpClient SHARED_HTTP = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(5)) .build(); private SpurvikGuard() {} public record SignedApprovalLinks( String gateId, String actionHmac, long issuedAt, String nonce, String approveUrl, String rejectUrl ) {} public record CallbackCheckResult( boolean valid, boolean executeAllowed, String decision, String reason ) {} public static String keyedDigest(String text, String secret) { byte[] keyBytes = resolveHashSecret(secret); byte[] msgBytes = (text == null ? "" : text).getBytes(StandardCharsets.UTF_8); return hmacHex(keyBytes, msgBytes); } public static String keyedDigest(String text) { return keyedDigest(text, null); } public static String buildPayloadSummary(List fieldNames, String contentFingerprint) { List validKeys = new ArrayList<>(); if (fieldNames != null) { for (String candidate : fieldNames) { if (candidate != null && KEY_PATTERN.matcher(candidate).matches()) { validKeys.add(candidate); if (validKeys.size() >= MAX_SUMMARY_KEYS) { break; } } } } String fp = (contentFingerprint != null && HEX64_PATTERN.matcher(contentFingerprint).matches()) ? contentFingerprint : null; String serialized = encodeSummaryJson(validKeys, fp); while (serialized.getBytes(StandardCharsets.UTF_8).length > MAX_SUMMARY_CHARS && !validKeys.isEmpty()) { validKeys.remove(validKeys.size() - 1); serialized = encodeSummaryJson(validKeys, fp); } return serialized; } public static String buildTelemetryEventJson( String prompt, String output, String modelProvider, String modelVersion, long latencyMs, String riskTier, String secret ) { long clampedLatency = Math.max(0L, Math.min(latencyMs, 3_600_000L)); String cleanProvider = cleanShort(modelProvider, "spring-ai", 64); String cleanVersion = cleanShort(modelVersion, "unknown", 200); String cleanTier = cleanShort(riskTier, "limited_art50", 32); String inHash = keyedDigest(prompt, secret); String outHash = keyedDigest(output, secret); return "{\"events\":[{" + "\"eventId\":" + jsonQuote(UUID.randomUUID().toString()) + "," + "\"timestamp\":" + jsonQuote(Instant.now().toString()) + "," + "\"modelProvider\":" + jsonQuote(cleanProvider) + "," + "\"modelVersion\":" + jsonQuote(cleanVersion) + "," + "\"inputHash\":" + jsonQuote(inHash) + "," + "\"outputHash\":" + jsonQuote(outHash) + "," + "\"contentHashMode\":\"keyed\"," + "\"riskTier\":" + jsonQuote(cleanTier) + "," + "\"latencyMs\":" + clampedLatency + "," + "\"contentMarkingApplied\":false," + "\"hitlStatus\":\"not_required\"" + "}]}"; } public static HttpResponse sendTelemetryEvent( String prompt, String output, String modelProvider, String modelVersion, long latencyMs, String riskTier ) throws Exception { String body = buildTelemetryEventJson(prompt, output, modelProvider, modelVersion, latencyMs, riskTier, null); return postJson("/api/v1/telemetry", body, null, CONSOLE_BASE_URL); } public static HttpResponse requestHumanApproval( String actionName, List payloadFieldNames, String contentFingerprint ) throws Exception { String cleanAction = cleanShort(actionName, "consequential_action", 120); String summary = buildPayloadSummary(payloadFieldNames, contentFingerprint); String body = "{" + "\"action\":" + jsonQuote(cleanAction) + "," + "\"payloadSummary\":" + jsonQuote(summary) + "}"; return postJson("/api/v1/hitl", body, null, CONSOLE_BASE_URL); } public static String computeActionHmac( String gateId, String actionName, Map context, String signingSecret ) { String sec = resolveSigningSecret(signingSecret); List pairs = new ArrayList<>(); if (context != null && !context.isEmpty()) { TreeMap sorted = new TreeMap<>(context); for (Map.Entry e : sorted.entrySet()) { pairs.add(e.getKey() + "=" + (e.getValue() == null ? "" : e.getValue())); } } String msg = "spurvik:art12:v1|" + gateId + "|" + actionName + "|" + String.join("&", pairs); return hmacHex(sec.getBytes(StandardCharsets.UTF_8), msg.getBytes(StandardCharsets.UTF_8)); } public static SignedApprovalLinks createSignedApprovalLinks( String callbackBaseUrl, String gateId, String actionName, Map context, String signingSecret, Long issuedAtUnix, String nonce ) { String sec = resolveSigningSecret(signingSecret); String base = (callbackBaseUrl == null ? "" : callbackBaseUrl.trim()).replaceAll("/+$", ""); if (!base.startsWith("https://") && !base.startsWith("http://localhost")) { throw new IllegalArgumentException("callbackBaseUrl must start with https:// (or http://localhost in local tests)."); } String actionHmac = computeActionHmac(gateId, actionName, context, sec); long issued = issuedAtUnix != null ? issuedAtUnix : Instant.now().getEpochSecond(); String tokNonce = (nonce != null && !nonce.isEmpty()) ? nonce : randomHex(12); String approveSig = hmacHex( sec.getBytes(StandardCharsets.UTF_8), decisionPayload(gateId, actionHmac, "approved", issued, tokNonce).getBytes(StandardCharsets.UTF_8) ); String rejectSig = hmacHex( sec.getBytes(StandardCharsets.UTF_8), decisionPayload(gateId, actionHmac, "rejected", issued, tokNonce).getBytes(StandardCharsets.UTF_8) ); String sep = base.contains("?") ? "&" : "?"; String approveUrl = base + sep + "gateId=" + urlEnc(gateId) + "&actionHmac=" + urlEnc(actionHmac) + "&decision=approved" + "&issuedAt=" + issued + "&nonce=" + urlEnc(tokNonce) + "&sig=" + approveSig; String rejectUrl = base + sep + "gateId=" + urlEnc(gateId) + "&actionHmac=" + urlEnc(actionHmac) + "&decision=rejected" + "&issuedAt=" + issued + "&nonce=" + urlEnc(tokNonce) + "&sig=" + rejectSig; return new SignedApprovalLinks(gateId, actionHmac, issued, tokNonce, approveUrl, rejectUrl); } public static CallbackCheckResult verifySignedCallback( String callbackUrlOrQuery, String expectedActionHmac, String signingSecret, long maxAgeSeconds, Long nowUnix ) { String sec = resolveSigningSecret(signingSecret); Map q = parseQueryString(callbackUrlOrQuery == null ? "" : callbackUrlOrQuery); String gateId = q.get("gateId"); String actionHmac = q.get("actionHmac"); String decision = q.get("decision"); String issuedRaw = q.get("issuedAt"); String nonce = q.get("nonce"); String sig = q.get("sig"); if (gateId == null || gateId.isEmpty() || actionHmac == null || !HEX64_PATTERN.matcher(actionHmac).matches() || sig == null || !HEX64_PATTERN.matcher(sig).matches()) { return new CallbackCheckResult(false, false, null, "malformed_fields"); } if (!"approved".equals(decision) && !"rejected".equals(decision)) { return new CallbackCheckResult(false, false, null, "invalid_decision"); } if (issuedRaw == null || !issuedRaw.matches("^\\d{1,15}$")) { return new CallbackCheckResult(false, false, null, "invalid_timestamp"); } long issuedAt = Long.parseLong(issuedRaw); long now = nowUnix != null ? nowUnix : Instant.now().getEpochSecond(); long clampedMaxAge = Math.max(1L, Math.min(maxAgeSeconds, MAX_LINK_MAX_AGE_SECONDS)); if (issuedAt > now + MAX_CLOCK_SKEW_SECONDS) { return new CallbackCheckResult(false, false, null, "future_timestamp"); } if (now - issuedAt > clampedMaxAge) { return new CallbackCheckResult(false, false, null, "expired_token"); } if (expectedActionHmac != null && !fixedTimeEquals(expectedActionHmac, actionHmac)) { return new CallbackCheckResult(false, false, null, "action_hmac_mismatch"); } String expectedSig = hmacHex( sec.getBytes(StandardCharsets.UTF_8), decisionPayload(gateId, actionHmac, decision, issuedAt, nonce).getBytes(StandardCharsets.UTF_8) ); if (!fixedTimeEquals(expectedSig, sig)) { return new CallbackCheckResult(false, false, null, "invalid_signature"); } return new CallbackCheckResult(true, "approved".equals(decision), decision, "ok"); } public static String art50BadgeHtml( String systemName, String locale, String notice, String position, boolean whiteLabel ) { String cleanSys = htmlEscape(cleanShort(systemName, "AI Assistant", 80)); String cleanNotice = NOTICE_KINDS.contains(notice) ? notice : "interaction"; String cleanPos = BADGE_POSITIONS.contains(position) ? position : "bottom-left"; String locLower = locale == null ? "" : locale.trim().toLowerCase(Locale.ROOT); String locAttr = (!locLower.isEmpty() && !"auto".equals(locLower) && EU_LOCALES.contains(locLower)) ? " data-locale=\"" + locLower + "\"" : " data-locale=\"auto\""; String wlAttr = whiteLabel ? " data-attribution=\"false\"" : " data-attribution=\"true\""; return ""; } public static String trustCardHtml(String domain, String locale, String theme, boolean whiteLabel) { String cleanDom = sanitizePublicHost(domain); if (cleanDom == null) { cleanDom = "yourdomain.eu"; } String locLower = locale == null ? "" : locale.trim().toLowerCase(Locale.ROOT); String locAttr = (!locLower.isEmpty() && !"auto".equals(locLower) && EU_LOCALES.contains(locLower)) ? " data-locale=\"" + locLower + "\"" : ""; String safeTheme = "light".equals(theme) ? "light" : "dark"; String wlAttr = whiteLabel ? "false" : "true"; return ""; } public static boolean runGateSelfTest() { String secret = "spurvik_selftest_signing_secret_2026"; long t0 = 1_764_200_000L; Map ctx = Map.of("amountEur", "250", "invoiceId", "inv_99"); SignedApprovalLinks links = createSignedApprovalLinks( "https://console.spurvik.com/api/v1/hitl/callback", "gate_java_01", "stripe.refunds.create", ctx, secret, t0, "a1b2c3d4e5f60718293a4b5c" ); // 1. Valid approval executes CallbackCheckResult v1 = verifySignedCallback(links.approveUrl(), links.actionHmac(), secret, 3600L, t0 + 15L); if (!v1.valid() || !v1.executeAllowed()) return false; // 2. Valid rejection blocks execution CallbackCheckResult v2 = verifySignedCallback(links.rejectUrl(), links.actionHmac(), secret, 3600L, t0 + 15L); if (!v2.valid() || v2.executeAllowed()) return false; // 3. Tampered decision rejected String tampered = links.rejectUrl().replace("decision=rejected", "decision=approved"); if (verifySignedCallback(tampered, links.actionHmac(), secret, 3600L, t0 + 15L).valid()) return false; // 4. Wrong secret rejected if (verifySignedCallback(links.approveUrl(), links.actionHmac(), "wrong_signing_secret_value_0000", 3600L, t0 + 15L).valid()) return false; // 5. Expired token rejected if (verifySignedCallback(links.approveUrl(), links.actionHmac(), secret, 60L, t0 + 3600L).valid()) return false; // 6. Context swap rejected String swappedHmac = computeActionHmac("gate_java_01", "stripe.refunds.create", Map.of("amountEur", "99999"), secret); if (verifySignedCallback(links.approveUrl(), swappedHmac, secret, 3600L, t0 + 15L).valid()) return false; return true; } public static void main(String[] args) { String host = (args != null && args.length > 0) ? sanitizePublicHost(args[0]) : null; if (host == null) host = "acme.eu"; boolean passed = runGateSelfTest(); if (!passed) { System.err.println("SpurvikGuard Java self-test FAILED."); System.exit(1); } System.out.println("SpurvikGuard " + VERSION + " (Java 21+ / Spring Boot 3 · 0 Maven deps): 6/6 Art. 14 gate vectors PASSED."); System.out.println("Art. 50(1) Thymeleaf tag: " + art50BadgeHtml(host, "auto", "interaction", "bottom-left", false)); System.out.println("Pro EUR 19/mo (white-label + 90d Frankfurt vault): " + CONSOLE_BASE_URL + "/signup?plan=pro&appUrl=" + urlEnc(host)); System.out.println("Team EUR 79/mo (2M/mo + 12m vault + Annex IV): " + CONSOLE_BASE_URL + "/signup?plan=team&appUrl=" + urlEnc(host)); } private static byte[] resolveHashSecret(String secret) { String raw = secret != null ? secret : System.getenv("SPURVIK_CONTENT_HASH_SECRET"); if (raw == null) raw = ""; byte[] utf8 = raw.getBytes(StandardCharsets.UTF_8); if (utf8.length < 16) { throw new IllegalArgumentException("SPURVIK_CONTENT_HASH_SECRET must be at least 16 UTF-8 bytes."); } return utf8; } private static String resolveSigningSecret(String signingSecret) { String raw = signingSecret; if (raw == null) raw = System.getenv("SPURVIK_SIGNING_SECRET"); if (raw == null) raw = System.getenv("SPURVIK_CONTENT_HASH_SECRET"); if (raw == null || raw.isEmpty()) { throw new IllegalArgumentException("SPURVIK_SIGNING_SECRET is missing."); } if (!raw.equals(raw.trim())) { throw new IllegalArgumentException("SPURVIK_SIGNING_SECRET must not have leading or trailing whitespace."); } if (raw.length() < 16) { throw new IllegalArgumentException("SPURVIK_SIGNING_SECRET must be at least 16 characters."); } return raw; } private static String hmacHex(byte[] key, byte[] message) { try { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key, "HmacSHA256")); return HexFormat.of().formatHex(mac.doFinal(message)); } catch (Exception e) { throw new IllegalStateException("HmacSHA256 unavailable", e); } } private static boolean fixedTimeEquals(String a, String b) { return MessageDigest.isEqual( a.getBytes(StandardCharsets.US_ASCII), b.getBytes(StandardCharsets.US_ASCII) ); } private static String decisionPayload(String gateId, String actionHmac, String decision, long issuedAtUnix, String nonce) { String head = "spurvik:art14:decision:v1|" + gateId + "|" + actionHmac + "|" + decision + "|" + issuedAtUnix; return (nonce != null && !nonce.isEmpty()) ? head + "|" + nonce : head; } private static String encodeSummaryJson(List keys, String fp) { StringBuilder sb = new StringBuilder(); sb.append("{\"contentFingerprint\":"); sb.append(fp == null ? "null" : jsonQuote(fp)); sb.append(",\"keys\":["); for (int i = 0; i < keys.size(); i++) { if (i > 0) sb.append(','); sb.append(jsonQuote(keys.get(i))); } sb.append("],\"schema\":").append(jsonQuote(PAYLOAD_SUMMARY_SCHEMA)).append('}'); return sb.toString(); } private static HttpResponse postJson(String path, String jsonBody, String apiKey, String baseUrl) throws Exception { String key = (apiKey != null ? apiKey : System.getenv("SPURVIK_API_KEY")); if (key == null || key.trim().isEmpty()) { throw new IllegalArgumentException("SPURVIK_API_KEY is required for EU Console ingestion."); } String cleanBase = (baseUrl == null ? CONSOLE_BASE_URL : baseUrl).replaceAll("/+$", ""); URI uri = URI.create(cleanBase + "/" + path.replaceAll("^/+", "")); HttpRequest req = HttpRequest.newBuilder(uri) .timeout(Duration.ofSeconds(10)) .header("Authorization", "Bearer " + key.trim()) .header("Content-Type", "application/json") .header("User-Agent", "spurvik-guard-java/" + VERSION) .POST(HttpRequest.BodyPublishers.ofString(jsonBody, StandardCharsets.UTF_8)) .build(); return SHARED_HTTP.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); } private static Map parseQueryString(String urlOrQuery) { int qIdx = urlOrQuery.indexOf('?'); String raw = qIdx >= 0 ? urlOrQuery.substring(qIdx + 1) : urlOrQuery; int hashIdx = raw.indexOf('#'); if (hashIdx >= 0) raw = raw.substring(0, hashIdx); if (raw.isEmpty()) return Collections.emptyMap(); Map out = new LinkedHashMap<>(); for (String part : raw.split("&")) { int eq = part.indexOf('='); if (eq > 0) { String k = URLDecoder.decode(part.substring(0, eq), StandardCharsets.UTF_8); String v = URLDecoder.decode(part.substring(eq + 1), StandardCharsets.UTF_8); out.put(k, v); } } return out; } private static String sanitizePublicHost(String raw) { if (raw == null) return null; String trimmed = raw.trim().toLowerCase(Locale.ROOT); if (trimmed.isEmpty() || trimmed.length() > 253 || trimmed.contains("@")) return null; String candidate = trimmed.replaceFirst("^https?://", "").split("[/?#:]")[0].replaceAll("\\.$", ""); if (!HOST_PATTERN.matcher(candidate).matches() || RESERVED_HOST_PATTERN.matcher(candidate).find()) { return null; } return candidate; } private static String cleanShort(String input, String fallback, int maxChars) { if (input == null) return fallback; StringBuilder sb = new StringBuilder(); for (int i = 0; i < input.length() && sb.length() < maxChars; i++) { char c = input.charAt(i); sb.append(Character.isISOControl(c) ? ' ' : c); } String trimmed = sb.toString().trim(); return trimmed.isEmpty() ? fallback : trimmed; } private static String randomHex(int numBytes) { byte[] buf = new byte[numBytes]; RNG.nextBytes(buf); return HexFormat.of().formatHex(buf); } private static String urlEnc(String s) { return URLEncoder.encode(s == null ? "" : s, StandardCharsets.UTF_8); } private static String htmlEscape(String s) { return s.replace("&", "&") .replace("\"", """) .replace("'", "'") .replace("<", "<") .replace(">", ">"); } private static String jsonQuote(String s) { StringBuilder sb = new StringBuilder(s.length() + 2); sb.append('"'); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '"' -> sb.append("\\\""); case '\\' -> sb.append("\\\\"); case '\n' -> sb.append("\\n"); case '\r' -> sb.append("\\r"); case '\t' -> sb.append("\\t"); default -> { if (c < 0x20) { sb.append(String.format("\\u%04x", (int) c)); } else { sb.append(c); } } } } sb.append('"'); return sb.toString(); } }