SHA256
Добавить лицензию CC0 1.0
This commit is contained in:
@@ -18,7 +18,8 @@ public final class BodyRecordParser {
|
||||
|
||||
// TECH supports Header v1 and CreateChannel current format (ver=1).
|
||||
if (t == (CreateChannelBody.TYPE & 0xFFFF)) {
|
||||
if (st == (HeaderBody.SUBTYPE_COMPAT & 0xFFFF) && v == (HeaderBody.VER & 0xFFFF)) {
|
||||
if (st == (HeaderBody.SUBTYPE_COMPAT & 0xFFFF)
|
||||
&& (v == (HeaderBody.VER & 0xFFFF) || v == (HeaderBody.VER_CC0 & 0xFFFF))) {
|
||||
return new HeaderBody(subType, version, bodyBytes).check();
|
||||
}
|
||||
if (st == (CreateChannelBody.SUBTYPE & 0xFFFF)
|
||||
|
||||
@@ -9,12 +9,13 @@ import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* HeaderBody — type=0, subType=0, version=1.
|
||||
* HeaderBody — TECH type=0, subType=0; version=1 legacy / version=2 CC0.
|
||||
*
|
||||
* bodyBytes (BigEndian):
|
||||
* [TAG_LEN] tag ASCII
|
||||
* [1] loginLength (uint8)
|
||||
* [N] login UTF-8
|
||||
* [15] ASCII "license:CC0-1.0" (version=2 only)
|
||||
* [32] initialBlockchainKey32
|
||||
*
|
||||
* initialBlockchainKey32 is the public blockchain-signing key that created fork #1.
|
||||
@@ -23,7 +24,11 @@ import java.util.Objects;
|
||||
*/
|
||||
public final class HeaderBody implements BodyRecord {
|
||||
public static final short TYPE = 0;
|
||||
public static final short VER = 1;
|
||||
public static final short VER = 1; // Legacy, read-only for newly created chains
|
||||
public static final short VER_CC0 = 2;
|
||||
public static final String LICENSE_CC0 = "CC0-1.0";
|
||||
public static final String LICENSE_FIELD_CC0 = "license:" + LICENSE_CC0;
|
||||
private static final byte[] LICENSE_BYTES = LICENSE_FIELD_CC0.getBytes(StandardCharsets.US_ASCII);
|
||||
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
|
||||
public static final short SUBTYPE_COMPAT = 0;
|
||||
public static final String TAG = ShineSignatureConstants.BLOCKCHAIN_HEADER_TAG;
|
||||
@@ -36,14 +41,16 @@ public final class HeaderBody implements BodyRecord {
|
||||
public final String tag;
|
||||
public final String login;
|
||||
public final byte[] initialBlockchainKey32;
|
||||
public final String license; // null for legacy HEADER v1
|
||||
|
||||
public HeaderBody(short subType, short version, byte[] bodyBytes) {
|
||||
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
||||
this.subType = subType;
|
||||
this.version = version;
|
||||
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
|
||||
if ((version & 0xFFFF) != (VER & 0xFFFF)) throw new IllegalArgumentException("HeaderBody version must be 1");
|
||||
if (bodyBytes.length < TAG_LEN + 1 + 1 + 32) throw new IllegalArgumentException("HeaderBody too short");
|
||||
if (version != VER && version != VER_CC0) throw new IllegalArgumentException("HeaderBody version must be 1 or 2");
|
||||
if (bodyBytes.length < TAG_LEN + 1 + 1 + 32 + (version == VER_CC0 ? LICENSE_BYTES.length : 0))
|
||||
throw new IllegalArgumentException("HeaderBody too short");
|
||||
|
||||
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
||||
byte[] tagBytes = new byte[TAG_LEN];
|
||||
@@ -53,30 +60,52 @@ public final class HeaderBody implements BodyRecord {
|
||||
this.tag = parsedTag;
|
||||
|
||||
int loginLen = Byte.toUnsignedInt(bb.get());
|
||||
if (loginLen <= 0 || bb.remaining() != loginLen + 32) throw new IllegalArgumentException("Bad HeaderBody login/key length");
|
||||
if (loginLen <= 0 || bb.remaining() != loginLen + 32 + (version == VER_CC0 ? LICENSE_BYTES.length : 0))
|
||||
throw new IllegalArgumentException("Bad HeaderBody login/key/license length");
|
||||
byte[] loginBytes = new byte[loginLen];
|
||||
bb.get(loginBytes);
|
||||
this.login = BodyTargetSupport.decodeStrictUtf8(loginBytes, "HeaderBody login");
|
||||
if (version == VER_CC0) {
|
||||
byte[] actual = new byte[LICENSE_BYTES.length];
|
||||
bb.get(actual);
|
||||
if (!Arrays.equals(actual, LICENSE_BYTES)) throw new IllegalArgumentException("Unsupported HEADER license");
|
||||
this.license = LICENSE_CC0;
|
||||
} else {
|
||||
this.license = null;
|
||||
}
|
||||
this.initialBlockchainKey32 = new byte[32];
|
||||
bb.get(this.initialBlockchainKey32);
|
||||
requireNonZeroKey(this.initialBlockchainKey32);
|
||||
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected HeaderBody tail");
|
||||
}
|
||||
|
||||
// Legacy constructor is kept for historical fixtures and importing v1 blocks.
|
||||
public HeaderBody(String login, byte[] initialBlockchainKey32) {
|
||||
this(login, initialBlockchainKey32, VER);
|
||||
}
|
||||
|
||||
public static HeaderBody licensedCc0(String login, byte[] initialBlockchainKey32) {
|
||||
return new HeaderBody(login, initialBlockchainKey32, VER_CC0);
|
||||
}
|
||||
|
||||
private HeaderBody(String login, byte[] initialBlockchainKey32, short version) {
|
||||
Objects.requireNonNull(login, "login == null");
|
||||
Objects.requireNonNull(initialBlockchainKey32, "initialBlockchainKey32 == null");
|
||||
this.subType = SUBTYPE_COMPAT;
|
||||
this.version = VER;
|
||||
this.version = version;
|
||||
this.tag = TAG;
|
||||
this.login = login;
|
||||
this.initialBlockchainKey32 = Arrays.copyOf(initialBlockchainKey32, initialBlockchainKey32.length);
|
||||
this.license = version == VER_CC0 ? LICENSE_CC0 : null;
|
||||
check();
|
||||
}
|
||||
|
||||
@Override
|
||||
public HeaderBody check() {
|
||||
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
|
||||
if (version != VER && version != VER_CC0) throw new IllegalArgumentException("Bad HeaderBody version");
|
||||
if (version == VER_CC0 && !LICENSE_CC0.equals(license)) throw new IllegalArgumentException("Bad HEADER CC0 license");
|
||||
if (version == VER && license != null) throw new IllegalArgumentException("Legacy HEADER must not contain a license");
|
||||
if (login == null || login.isBlank()) throw new IllegalArgumentException("Login is blank");
|
||||
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
|
||||
// В HEADER хранится неизменяемое написание зарегистрированного login@namespace.
|
||||
@@ -95,10 +124,11 @@ public final class HeaderBody implements BodyRecord {
|
||||
public byte[] toBytes() {
|
||||
check();
|
||||
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
|
||||
ByteBuffer bb = ByteBuffer.allocate(TAG_LEN + 1 + loginUtf8.length + 32).order(ByteOrder.BIG_ENDIAN);
|
||||
ByteBuffer bb = ByteBuffer.allocate(TAG_LEN + 1 + loginUtf8.length + 32 + (version == VER_CC0 ? LICENSE_BYTES.length : 0)).order(ByteOrder.BIG_ENDIAN);
|
||||
bb.put(TAG_ASCII);
|
||||
bb.put((byte) loginUtf8.length);
|
||||
bb.put(loginUtf8);
|
||||
if (version == VER_CC0) bb.put(LICENSE_BYTES);
|
||||
bb.put(initialBlockchainKey32);
|
||||
return bb.array();
|
||||
}
|
||||
@@ -112,6 +142,6 @@ public final class HeaderBody implements BodyRecord {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "HeaderBody{login='" + login + "', initialBlockchainKey32=<32 bytes>}";
|
||||
return "HeaderBody{version=" + version + ", login='" + login + "', license=" + license + ", initialBlockchainKey32=<32 bytes>}";
|
||||
}
|
||||
}
|
||||
|
||||
+35
@@ -108,6 +108,41 @@ final class TargetLoginFormatTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void licensedHeaderV2IncludesExactCc0ConstantAndParsesAlongsideV1() {
|
||||
HeaderBody v2 = HeaderBody.licensedCc0("Alice@shine", INITIAL_KEY);
|
||||
assertEquals(HeaderBody.VER_CC0, v2.version);
|
||||
assertEquals("CC0-1.0", v2.license);
|
||||
HeaderBody parsed = new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER_CC0, v2.toBytes()).check();
|
||||
assertEquals("Alice@shine", parsed.login);
|
||||
assertEquals("CC0-1.0", parsed.license);
|
||||
assertArrayEquals(INITIAL_KEY, parsed.initialBlockchainKey32);
|
||||
assertArrayEquals(v2.toBytes(), parsed.toBytes());
|
||||
|
||||
HeaderBody legacy = new HeaderBody("Alice@shine", INITIAL_KEY);
|
||||
assertNull(new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER, legacy.toBytes()).license);
|
||||
assertEquals(legacy.toBytes().length + 15, v2.toBytes().length);
|
||||
byte[] expectedLicenseMarker = "license:CC0-1.0".getBytes(java.nio.charset.StandardCharsets.US_ASCII);
|
||||
int markerOffset = 5 + 1 + "Alice@shine".getBytes(java.nio.charset.StandardCharsets.UTF_8).length;
|
||||
assertArrayEquals(expectedLicenseMarker, java.util.Arrays.copyOfRange(v2.toBytes(), markerOffset, markerOffset + 15));
|
||||
assertArrayEquals(INITIAL_KEY, java.util.Arrays.copyOfRange(v2.toBytes(), markerOffset + 15, v2.toBytes().length));
|
||||
|
||||
byte[] invalid = v2.toBytes();
|
||||
invalid[markerOffset + 8] = (byte)'X';
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER_CC0, invalid));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER, v2.toBytes()));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER_CC0, legacy.toBytes()));
|
||||
|
||||
byte[] swapped = v2.toBytes();
|
||||
System.arraycopy(INITIAL_KEY, 0, swapped, markerOffset, 32);
|
||||
System.arraycopy(expectedLicenseMarker, 0, swapped, markerOffset + 32, 15);
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER_CC0, swapped));
|
||||
}
|
||||
|
||||
@Test
|
||||
void namespacedHeaderRejectsMalformedOrOversizedLogin() {
|
||||
for (String login : new String[]{"alice@", "@shine", "alice@@free", "alice@FREE", "alice.free@shine", "abcdefghijklmnopqrstuvwxyz@free"}) {
|
||||
|
||||
@@ -11,5 +11,6 @@ public final class PublicFileApiConfigurator {
|
||||
public static void register(ServletContextHandler context) {
|
||||
context.addServlet(new ServletHolder(new PublicFileServlet()), "/files/*");
|
||||
context.addServlet(new ServletHolder(new R2PrepareServlet()), "/api/files/prepare");
|
||||
context.addServlet(new ServletHolder(new UserFileServerServlet()), "/api/files/user-server");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,7 +32,6 @@ public final class R2DmPrepareServlet extends HttpServlet {
|
||||
private static final Pattern FILE_ID = Pattern.compile("^[1-9A-HJ-NP-Za-km-z]{32,44}$");
|
||||
private static final long MAX_OBJECT_BYTES = 8L * 1024L * 1024L + 16L;
|
||||
private static final String CONTENT_TYPE = "application/octet-stream";
|
||||
private static final String PUBLIC_BASE = "https://dm-files.shineup.me/";
|
||||
|
||||
@Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) {
|
||||
cors(req, resp);
|
||||
@@ -63,7 +62,7 @@ public final class R2DmPrepareServlet extends HttpServlet {
|
||||
var credentials = StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secret));
|
||||
var apiEndpoint = URI.create(endpoint);
|
||||
ObjectNode result = JSON.createObjectNode();
|
||||
result.put("fileUrl", PUBLIC_BASE + fileId);
|
||||
result.put("fileUrl", R2FederatedPublicUrl.forObject("dm-files", fileId));
|
||||
try (S3Client s3 = S3Client.builder().region(Region.of("auto"))
|
||||
.endpointOverride(apiEndpoint).credentialsProvider(credentials).forcePathStyle(true).build()) {
|
||||
try {
|
||||
@@ -108,13 +107,8 @@ public final class R2DmPrepareServlet extends HttpServlet {
|
||||
}
|
||||
|
||||
private static void cors(HttpServletRequest req, HttpServletResponse resp) {
|
||||
String origin = req.getHeader("Origin");
|
||||
if ("https://shineup.me".equals(origin) || "https://www.shineup.me".equals(origin)
|
||||
|| "https://test.shineup.me".equals(origin)
|
||||
|| "https://t2.shineup.me".equals(origin)) {
|
||||
resp.setHeader("Access-Control-Allow-Origin", origin);
|
||||
resp.setHeader("Vary", "Origin");
|
||||
}
|
||||
// Подписанные запросы не используют cookie; интерфейс может работать на любом сервере федерации.
|
||||
resp.setHeader("Access-Control-Allow-Origin", "*");
|
||||
resp.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
|
||||
resp.setHeader("Access-Control-Allow-Headers", "Content-Type, X-Shine-Session-Id, X-Shine-Time-Ms, X-Shine-Signature");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package server.files;
|
||||
|
||||
import shine.db.DbController;
|
||||
import utils.config.AppConfig;
|
||||
|
||||
import java.net.URI;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* File domains are derived from the current access server's own Solana-synced
|
||||
* PDA address. No R2 public-domain setting and no request Host header are used.
|
||||
*/
|
||||
final class R2FederatedPublicUrl {
|
||||
private static final Pattern DOMAIN = Pattern.compile("^[a-z0-9-]+(?:\\.[a-z0-9-]+)+$");
|
||||
|
||||
private R2FederatedPublicUrl() {}
|
||||
|
||||
static String forObject(String kind, String fileId) throws Exception {
|
||||
if (!"files".equals(kind) && !"dm-files".equals(kind)) {
|
||||
throw new IllegalArgumentException("Unexpected file domain kind");
|
||||
}
|
||||
String login = AppConfig.getInstance().getParam("server.SHiNE.login");
|
||||
if (login == null || login.isBlank()) {
|
||||
throw new IllegalStateException("server.SHiNE.login is not configured");
|
||||
}
|
||||
String sql = """
|
||||
SELECT server_address FROM solana_user_pda_current
|
||||
WHERE normalized_login = LOWER(BTRIM(?)) AND is_server = TRUE
|
||||
AND BTRIM(COALESCE(server_address, '')) <> ''
|
||||
LIMIT 1
|
||||
""";
|
||||
String raw;
|
||||
try (Connection connection = DbController.getInstance().getConnection();
|
||||
PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
statement.setString(1, login);
|
||||
try (ResultSet rs = statement.executeQuery()) {
|
||||
if (!rs.next()) throw new IllegalStateException("Local access-server address not synchronized yet");
|
||||
raw = rs.getString(1);
|
||||
}
|
||||
}
|
||||
String address = raw == null ? "" : raw.trim();
|
||||
if (!address.matches("^[a-zA-Z][a-zA-Z0-9+.-]*://.*")) address = "https://" + address;
|
||||
URI uri = URI.create(address);
|
||||
String protocol = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT);
|
||||
if (!("https".equals(protocol) || "wss".equals(protocol) || "http".equals(protocol) || "ws".equals(protocol))
|
||||
|| uri.getUserInfo() != null || uri.getHost() == null) {
|
||||
throw new IllegalStateException("Invalid server PDA address");
|
||||
}
|
||||
String domain = uri.getHost().toLowerCase(Locale.ROOT);
|
||||
if (!DOMAIN.matcher(domain).matches()) throw new IllegalStateException("Invalid access-server domain");
|
||||
return "https://" + kind + "." + domain + "/" + fileId;
|
||||
}
|
||||
}
|
||||
@@ -59,7 +59,7 @@ public final class R2PrepareServlet extends HttpServlet {
|
||||
var creds = StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secret));
|
||||
var httpEndpoint = URI.create(endpoint);
|
||||
ObjectNode out = JSON.createObjectNode();
|
||||
out.put("fileUrl", "https://files.shineup.me/" + root);
|
||||
out.put("fileUrl", R2FederatedPublicUrl.forObject("files", root));
|
||||
try (S3Client s3 = S3Client.builder().region(Region.of("auto")).endpointOverride(httpEndpoint)
|
||||
.credentialsProvider(creds).forcePathStyle(true).build()) {
|
||||
try {
|
||||
@@ -115,11 +115,8 @@ public final class R2PrepareServlet extends HttpServlet {
|
||||
return value == null || value.isBlank() ? null : value.trim();
|
||||
}
|
||||
private static void cors(HttpServletRequest req, HttpServletResponse resp) {
|
||||
String origin = req.getHeader("Origin");
|
||||
if ("https://shineup.me".equals(origin) || "https://www.shineup.me".equals(origin)
|
||||
|| "https://test.shineup.me".equals(origin) || "https://t2.shineup.me".equals(origin)) {
|
||||
resp.setHeader("Access-Control-Allow-Origin", origin); resp.setHeader("Vary", "Origin");
|
||||
}
|
||||
// Подписанные запросы не используют cookie; интерфейс может работать на любом сервере федерации.
|
||||
resp.setHeader("Access-Control-Allow-Origin", "*");
|
||||
resp.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
|
||||
resp.setHeader("Access-Control-Allow-Headers", "Content-Type, X-Shine-Session-Id, X-Shine-Time-Ms, X-Shine-Signature");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package server.files;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import jakarta.servlet.http.HttpServlet;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import shine.db.dao.UserAccessServersCurrentDAO;
|
||||
import shine.db.entities.UserAccessServerRouteEntry;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** Публичный resolver файловых доменов на основе синхронизированной PostgreSQL-проекции Solana. */
|
||||
public final class UserFileServerServlet extends HttpServlet {
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final Pattern LOGIN = Pattern.compile("^[a-zA-Z0-9_.-]{1,64}@[a-zA-Z0-9_.-]{1,128}$");
|
||||
|
||||
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
String login = String.valueOf(request.getParameter("login")).trim();
|
||||
if (!LOGIN.matcher(login).matches()) {
|
||||
reply(response, 400, "Invalid login", null); return;
|
||||
}
|
||||
try {
|
||||
UserAccessServerRouteEntry route = UserAccessServersCurrentDAO.getInstance().findPrimaryByUserLogin(login);
|
||||
if (route == null || route.getServerLogin() == null || route.getServerUrl() == null) {
|
||||
reply(response, 404, "User access server not found in synchronized data", null); return;
|
||||
}
|
||||
reply(response, 200, null, route);
|
||||
} catch (Exception error) {
|
||||
getServletContext().log("User file server lookup failed", error);
|
||||
reply(response, 503, "Server directory temporarily unavailable", null);
|
||||
}
|
||||
}
|
||||
|
||||
private static void reply(HttpServletResponse response, int status, String error,
|
||||
UserAccessServerRouteEntry route) throws IOException {
|
||||
ObjectNode body = JSON.createObjectNode();
|
||||
if (error != null) body.put("error", error);
|
||||
else {
|
||||
body.put("serverLogin", route.getServerLogin());
|
||||
body.put("serverUrl", route.getServerUrl());
|
||||
}
|
||||
response.setStatus(status);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
JSON.writeValue(response.getOutputStream(), body);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user