HmiStyles.java

package com.workbenchclassic.hmi;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletContext;

/** Shared CSS source for admin API and public, read-only stylesheet servlet. */
final class HmiStyles {
    private HmiStyles() { }
    static String original(ServletContext context) throws IOException {
        try (InputStream stream = context.getResourceAsStream("/ios.css")) {
            if (stream == null) throw new IOException("Original ios.css missing in deployed WAR");
            try (Reader r = new InputStreamReader(stream, StandardCharsets.UTF_8)) { return read(r); }
        }
    }
    static String read(Reader r) throws IOException {
        char[] buf = new char[8192]; int n; StringBuilder value = new StringBuilder();
        while ((n=r.read(buf))>=0) {
            value.append(buf,0,n);
            if (value.length()>512*1024) throw new IOException("CSS exceeds 512 KiB");
        }
        return value.toString();
    }
    static String published() throws SQLException, IOException {
        try (Connection c=HmiDb.open();PreparedStatement p=c.prepareStatement(
                "SELECT CSS_CONTENT FROM "+HmiDb.schemaPrefix()+"HMI_APP_CSS_REVISION WHERE STATUS = ? ORDER BY VERSION_NO DESC")) {
            p.setString(1,"PUBLISHED");try(ResultSet rs=p.executeQuery()){
                if(rs.next()) try (Reader r=rs.getCharacterStream(1)){return read(r);}
            }
        }
        return null;
    }
    /** CSS is powerful. Disallow external fetches, embedded HTML and CSS behaviors. Restrict authoring to approved roles. */
    static void validate(String css) {
        if (css==null || css.isEmpty() || css.length()>512*1024) throw new IllegalArgumentException("CSS muss zwischen 1 und 524288 Zeichen umfassen");
        // Reject remote resources, CSS escapes, and HTML/script injection in published styles.
        if (css.indexOf('\\')>=0 || java.util.regex.Pattern.compile(
                "(?i)@import\\b|url\\s*\\(|image-set\\s*\\(|@font-face\\b|@namespace\\b|expression\\s*\\(|behavior\\s*:|-moz-binding\\s*:|https?://|data:|<|>").matcher(css).find())
            throw new IllegalArgumentException("CSS enthält externe Ressourcen oder nicht erlaubte Inhalte");
        if (!css.contains("{") || !css.contains("}")) throw new IllegalArgumentException("CSS-Regeln fehlen");
    }
}