package io.github.shirainbown.sharelink.download;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.UUID;
import org.springframework.stereotype.Component;

/**
 * A random secret generated at plugin startup. {@code FileStreamer} attaches it as the
 * {@value #HEADER} header on its loopback requests so that
 * {@code UploadProtectFilter} lets them through, while external requests to the same
 * {@code /upload/**} permalinks are rejected.
 */
@Component
public class InternalRequestSecret {

    public static final String HEADER = "X-Sharelink-Internal";

    private final String value = UUID.randomUUID().toString();

    public String value() {
        return value;
    }

    public boolean matches(String headerValue) {
        return headerValue != null
            && MessageDigest.isEqual(value.getBytes(StandardCharsets.UTF_8),
                headerValue.getBytes(StandardCharsets.UTF_8));
    }
}
