SHA256
Проверить вложения и блоки в каналах
This commit is contained in:
@@ -34,9 +34,14 @@ dependencies {
|
|||||||
implementation project(':shine-server-db') // модуль для работы с БД содержит и сущности из БД и саму работу с БД
|
implementation project(':shine-server-db') // модуль для работы с БД содержит и сущности из БД и саму работу с БД
|
||||||
implementation project(':shine-server-geo') // модуль для определения геолокации по IP
|
implementation project(':shine-server-geo') // модуль для определения геолокации по IP
|
||||||
|
|
||||||
|
testImplementation 'org.junit.jupiter:junit-jupiter:5.11.0'
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
test {
|
||||||
|
useJUnitPlatform()
|
||||||
|
}
|
||||||
|
|
||||||
java {
|
java {
|
||||||
sourceCompatibility = JavaVersion.VERSION_17
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
targetCompatibility = JavaVersion.VERSION_17
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
|
|||||||
+92
@@ -0,0 +1,92 @@
|
|||||||
|
package server.logic.ws_protocol.JSON.handlers.channels;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/** Только проверка небезопасных входящих маркеров v=2. Исходный TEXT не переписывается. */
|
||||||
|
final class AttachmentMarkerValidator {
|
||||||
|
private static final Pattern ROOT = Pattern.compile("[1-9A-HJ-NP-Za-km-z]{32,44}");
|
||||||
|
private static final Pattern SHA = Pattern.compile("[0-9a-f]{64}");
|
||||||
|
private static final Pattern TX_ID = Pattern.compile("[A-Za-z0-9_-]{43}");
|
||||||
|
private static final Pattern MIME = Pattern.compile("(?i)[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+");
|
||||||
|
private static final Set<String> ALLOWED = Set.of("v", "nm", "sz", "pr", "sha256", "mm", "ar");
|
||||||
|
|
||||||
|
private AttachmentMarkerValidator() { }
|
||||||
|
|
||||||
|
static boolean validateLeadingV2Markers(String raw) {
|
||||||
|
String text = raw == null ? "" : raw;
|
||||||
|
int offset = 0;
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
String prefix;
|
||||||
|
if (text.startsWith("<S:att;", offset)) prefix = "<S:att;";
|
||||||
|
else if (text.startsWith("<S:attach;", offset)) prefix = "<S:attach;";
|
||||||
|
else if (text.startsWith("<SHiNE:attach;", offset)) prefix = "<SHiNE:attach;";
|
||||||
|
else return true;
|
||||||
|
int start = offset + prefix.length();
|
||||||
|
int end = text.indexOf('>', start);
|
||||||
|
if (end < 0 || end - start > 2048 || text.substring(start, end).contains("\n")) return false;
|
||||||
|
String fields = text.substring(start, end);
|
||||||
|
if (java.util.Arrays.stream(fields.split(";", -1)).anyMatch(field -> field.matches("v\\s*=\\s*0*2"))) {
|
||||||
|
if (!validateV2(fields)) return false;
|
||||||
|
}
|
||||||
|
offset = end + 1;
|
||||||
|
if (offset >= text.length()) return true;
|
||||||
|
if (text.charAt(offset) != '\n') return false;
|
||||||
|
offset++;
|
||||||
|
}
|
||||||
|
// Больше десяти технических тегов трактуем как недопустимые метаданные.
|
||||||
|
return !text.startsWith("<S:att;", offset) && !text.startsWith("<S:attach;", offset)
|
||||||
|
&& !text.startsWith("<SHiNE:attach;", offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean validateV2(String rawFields) {
|
||||||
|
String[] fields = rawFields.split(";", -1);
|
||||||
|
if (fields.length < 4 || !fields[0].equals("v=2")) return false;
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
String name = null, size = null, root = null, sha = null, mime = null, ar = null;
|
||||||
|
for (String part : fields) {
|
||||||
|
int index = part.indexOf('=');
|
||||||
|
if (index <= 0 || part.indexOf('=', index + 1) >= 0) return false;
|
||||||
|
String key = part.substring(0, index);
|
||||||
|
String value = part.substring(index + 1);
|
||||||
|
if (!ALLOWED.contains(key) || !seen.add(key) || value.isEmpty()) return false;
|
||||||
|
switch (key) {
|
||||||
|
case "v": if (!value.equals("2")) return false; break;
|
||||||
|
case "nm": name = value; break;
|
||||||
|
case "sz": size = value; break;
|
||||||
|
case "pr": root = value; break;
|
||||||
|
case "sha256": sha = value; break;
|
||||||
|
case "mm": mime = value; break;
|
||||||
|
case "ar": ar = value; break;
|
||||||
|
default: return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (name == null || size == null || !seen.contains("v") || (root == null) == (sha == null)) return false;
|
||||||
|
if (!size.matches("[1-9][0-9]{0,18}")) return false;
|
||||||
|
try { if (Long.parseLong(size) < 1) return false; } catch (NumberFormatException e) { return false; }
|
||||||
|
if (root != null && !ROOT.matcher(root).matches()) return false;
|
||||||
|
if (sha != null && !SHA.matcher(sha).matches()) return false;
|
||||||
|
if (mime != null && (mime.length() > 127 || !MIME.matcher(mime).matches())) return false;
|
||||||
|
if (ar != null && !TX_ID.matcher(ar).matches()) return false;
|
||||||
|
|
||||||
|
StringBuilder decoded = new StringBuilder();
|
||||||
|
for (int i = 0; i < name.length(); i++) {
|
||||||
|
char ch = name.charAt(i);
|
||||||
|
if (ch == '%') {
|
||||||
|
if (i + 2 >= name.length()) return false;
|
||||||
|
String code = name.substring(i + 1, i + 3).toUpperCase(java.util.Locale.ROOT);
|
||||||
|
ch = switch (code) {
|
||||||
|
case "25" -> '%'; case "3B" -> ';'; case "3D" -> '=';
|
||||||
|
case "3C" -> '<'; case "3E" -> '>'; default -> 0;
|
||||||
|
};
|
||||||
|
if (ch == 0) return false;
|
||||||
|
i += 2;
|
||||||
|
} else if (ch == '<' || ch == '>' || ch == '=' || ch == ';') return false;
|
||||||
|
if (ch < 32 || ch == 127) return false;
|
||||||
|
decoded.append(ch);
|
||||||
|
}
|
||||||
|
return decoded.toString().getBytes(StandardCharsets.UTF_8).length <= 255;
|
||||||
|
}
|
||||||
|
}
|
||||||
+26
-2
@@ -5,6 +5,7 @@ import blockchain.body.BodyRecord;
|
|||||||
import blockchain.body.CreateChannelBody;
|
import blockchain.body.CreateChannelBody;
|
||||||
import blockchain.body.TextLineBody;
|
import blockchain.body.TextLineBody;
|
||||||
import blockchain.body.TextReplyBody;
|
import blockchain.body.TextReplyBody;
|
||||||
|
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetChannelMessages_Response;
|
||||||
import shine.db.channels.ChannelNameRules;
|
import shine.db.channels.ChannelNameRules;
|
||||||
import shine.db.MsgSubType;
|
import shine.db.MsgSubType;
|
||||||
import shine.db.sql.CurrentUsersSql;
|
import shine.db.sql.CurrentUsersSql;
|
||||||
@@ -226,6 +227,7 @@ final class ChannelsReadSupport {
|
|||||||
} else if (e.body instanceof blockchain.body.StatusActionBody sab) {
|
} else if (e.body instanceof blockchain.body.StatusActionBody sab) {
|
||||||
ti.text = sab.message;
|
ti.text = sab.message;
|
||||||
}
|
}
|
||||||
|
ti.attachmentMetadataValid = AttachmentMarkerValidator.validateLeadingV2Markers(ti.text);
|
||||||
return ti;
|
return ti;
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
return new TextInfo();
|
return new TextInfo();
|
||||||
@@ -236,7 +238,7 @@ final class ChannelsReadSupport {
|
|||||||
String order = asc ? "ASC" : "DESC";
|
String order = asc ? "ASC" : "DESC";
|
||||||
boolean bounded = limit > 0;
|
boolean bounded = limit > 0;
|
||||||
String sql = """
|
String sql = """
|
||||||
SELECT login,bch_name,block_number,block_hash,block_bytes,to_bch_name,to_block_number,to_block_hash,msg_sub_type,this_line_number
|
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_bch_name,to_block_number,to_block_hash,msg_sub_type,this_line_number
|
||||||
FROM blocks
|
FROM blocks
|
||||||
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type IN (?, ?, ?, ?, ?, ?) AND line_code=?
|
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type IN (?, ?, ?, ?, ?, ?) AND line_code=?
|
||||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM user_identity_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM user_identity_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||||
@@ -263,6 +265,9 @@ final class ChannelsReadSupport {
|
|||||||
pb.blockNumber = rs.getInt("block_number");
|
pb.blockNumber = rs.getInt("block_number");
|
||||||
pb.blockHash = rs.getBytes("block_hash");
|
pb.blockHash = rs.getBytes("block_hash");
|
||||||
pb.blockBytes = rs.getBytes("block_bytes");
|
pb.blockBytes = rs.getBytes("block_bytes");
|
||||||
|
pb.dataItemId = rs.getBytes("data_item_id");
|
||||||
|
pb.arweavePublishPending = rs.getBoolean("arweave_publish_pending");
|
||||||
|
pb.arweavePublishedAtMs = (Long) rs.getObject("arweave_published_at_ms");
|
||||||
pb.toBchName = rs.getString("to_bch_name");
|
pb.toBchName = rs.getString("to_bch_name");
|
||||||
pb.toBlockNumber = (Integer) rs.getObject("to_block_number");
|
pb.toBlockNumber = (Integer) rs.getObject("to_block_number");
|
||||||
pb.toBlockHash = rs.getBytes("to_block_hash");
|
pb.toBlockHash = rs.getBytes("to_block_hash");
|
||||||
@@ -286,7 +291,7 @@ final class ChannelsReadSupport {
|
|||||||
|
|
||||||
static List<PostBlock> versionsForPost(Connection c, String ownerBch, int originalBlock, byte[] originalHash) throws SQLException {
|
static List<PostBlock> versionsForPost(Connection c, String ownerBch, int originalBlock, byte[] originalHash) throws SQLException {
|
||||||
String sql = """
|
String sql = """
|
||||||
SELECT login,bch_name,block_number,block_hash,block_bytes
|
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms
|
||||||
FROM blocks
|
FROM blocks
|
||||||
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type=?
|
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type=?
|
||||||
AND to_block_number=? AND to_block_hash=?
|
AND to_block_number=? AND to_block_hash=?
|
||||||
@@ -309,6 +314,9 @@ final class ChannelsReadSupport {
|
|||||||
pb.blockNumber = rs.getInt("block_number");
|
pb.blockNumber = rs.getInt("block_number");
|
||||||
pb.blockHash = rs.getBytes("block_hash");
|
pb.blockHash = rs.getBytes("block_hash");
|
||||||
pb.blockBytes = rs.getBytes("block_bytes");
|
pb.blockBytes = rs.getBytes("block_bytes");
|
||||||
|
pb.dataItemId = rs.getBytes("data_item_id");
|
||||||
|
pb.arweavePublishPending = rs.getBoolean("arweave_publish_pending");
|
||||||
|
pb.arweavePublishedAtMs = (Long) rs.getObject("arweave_published_at_ms");
|
||||||
out.add(pb);
|
out.add(pb);
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
@@ -703,12 +711,27 @@ final class ChannelsReadSupport {
|
|||||||
|| subType == MsgSubType.TEXT_COURSE;
|
|| subType == MsgSubType.TEXT_COURSE;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static String dataItemIdBase64Url(byte[] bytes) {
|
||||||
|
return bytes != null && bytes.length == 32
|
||||||
|
? java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(bytes) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void setStorageInfo(Net_GetChannelMessages_Response.VersionItem out, byte[] id, boolean pending, Long publishedAt, byte[] raw) {
|
||||||
|
out.setArweaveDataItemId(dataItemIdBase64Url(id));
|
||||||
|
out.setArweavePublishPending(pending);
|
||||||
|
out.setArweavePublishedAtMs(publishedAt);
|
||||||
|
out.setSignedDataItemBytes(raw == null ? null : raw.length);
|
||||||
|
}
|
||||||
|
|
||||||
static final class PostBlock {
|
static final class PostBlock {
|
||||||
String login;
|
String login;
|
||||||
String bchName;
|
String bchName;
|
||||||
int blockNumber;
|
int blockNumber;
|
||||||
byte[] blockHash;
|
byte[] blockHash;
|
||||||
byte[] blockBytes;
|
byte[] blockBytes;
|
||||||
|
byte[] dataItemId;
|
||||||
|
boolean arweavePublishPending;
|
||||||
|
Long arweavePublishedAtMs;
|
||||||
String toBchName;
|
String toBchName;
|
||||||
Integer toBlockNumber;
|
Integer toBlockNumber;
|
||||||
byte[] toBlockHash;
|
byte[] toBlockHash;
|
||||||
@@ -717,6 +740,7 @@ final class ChannelsReadSupport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static final class TextInfo {
|
static final class TextInfo {
|
||||||
|
boolean attachmentMetadataValid = true;
|
||||||
String text = "";
|
String text = "";
|
||||||
long createdAtMs = 0L;
|
long createdAtMs = 0L;
|
||||||
}
|
}
|
||||||
|
|||||||
+9
@@ -152,7 +152,9 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
|
|||||||
v1.setBlockNumber(post.blockNumber);
|
v1.setBlockNumber(post.blockNumber);
|
||||||
v1.setBlockHash(ChannelsReadSupport.toHex(post.blockHash));
|
v1.setBlockHash(ChannelsReadSupport.toHex(post.blockHash));
|
||||||
v1.setText(postText.text);
|
v1.setText(postText.text);
|
||||||
|
v1.setAttachmentMetadataValid(postText.attachmentMetadataValid);
|
||||||
v1.setCreatedAtMs(postText.createdAtMs);
|
v1.setCreatedAtMs(postText.createdAtMs);
|
||||||
|
ChannelsReadSupport.setStorageInfo(v1, post.dataItemId, post.arweavePublishPending, post.arweavePublishedAtMs, post.blockBytes);
|
||||||
versionsOut.add(v1);
|
versionsOut.add(v1);
|
||||||
|
|
||||||
if (ChannelsReadSupport.supportsEditPostVersions(post.msgSubType)) {
|
if (ChannelsReadSupport.supportsEditPostVersions(post.msgSubType)) {
|
||||||
@@ -164,13 +166,20 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
|
|||||||
ve.setBlockNumber(edit.blockNumber);
|
ve.setBlockNumber(edit.blockNumber);
|
||||||
ve.setBlockHash(ChannelsReadSupport.toHex(edit.blockHash));
|
ve.setBlockHash(ChannelsReadSupport.toHex(edit.blockHash));
|
||||||
ve.setText(editText.text);
|
ve.setText(editText.text);
|
||||||
|
ve.setAttachmentMetadataValid(editText.attachmentMetadataValid);
|
||||||
ve.setCreatedAtMs(editText.createdAtMs);
|
ve.setCreatedAtMs(editText.createdAtMs);
|
||||||
|
ChannelsReadSupport.setStorageInfo(ve, edit.dataItemId, edit.arweavePublishPending, edit.arweavePublishedAtMs, edit.blockBytes);
|
||||||
versionsOut.add(ve);
|
versionsOut.add(ve);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
item.setVersions(versionsOut);
|
item.setVersions(versionsOut);
|
||||||
item.setVersionsTotal(versionsOut.size());
|
item.setVersionsTotal(versionsOut.size());
|
||||||
|
item.setAttachmentMetadataValid(v1.isAttachmentMetadataValid());
|
||||||
|
item.setArweaveDataItemId(v1.getArweaveDataItemId());
|
||||||
|
item.setArweavePublishPending(v1.getArweavePublishPending());
|
||||||
|
item.setArweavePublishedAtMs(v1.getArweavePublishedAtMs());
|
||||||
|
item.setSignedDataItemBytes(v1.getSignedDataItemBytes());
|
||||||
|
|
||||||
Net_GetChannelMessages_Response.VersionItem lastV = versionsOut.get(versionsOut.size() - 1);
|
Net_GetChannelMessages_Response.VersionItem lastV = versionsOut.get(versionsOut.size() - 1);
|
||||||
item.setText(lastV.getText());
|
item.setText(lastV.getText());
|
||||||
|
|||||||
+20
-10
@@ -19,7 +19,6 @@ import java.sql.PreparedStatement;
|
|||||||
import java.sql.ResultSet;
|
import java.sql.ResultSet;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
@@ -116,7 +115,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
private List<PostRow> findRepliesAndRatings(Connection c, String toBchName, int toBlockNumber, byte[] toBlockHash, int limit) throws Exception {
|
private List<PostRow> findRepliesAndRatings(Connection c, String toBchName, int toBlockNumber, byte[] toBlockHash, int limit) throws Exception {
|
||||||
String targetLogin = ChannelsReadSupport.loginFromChainName(toBchName);
|
String targetLogin = ChannelsReadSupport.loginFromChainName(toBchName);
|
||||||
String sql = """
|
String sql = """
|
||||||
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
||||||
FROM blocks
|
FROM blocks
|
||||||
WHERE msg_type=1
|
WHERE msg_type=1
|
||||||
AND to_block_number=? AND to_block_hash=?
|
AND to_block_number=? AND to_block_hash=?
|
||||||
@@ -153,7 +152,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
|
|
||||||
private PostRow findByLogicalTarget(Connection c, String login, int blockNumber, byte[] blockHash) throws Exception {
|
private PostRow findByLogicalTarget(Connection c, String login, int blockNumber, byte[] blockHash) throws Exception {
|
||||||
String sql = """
|
String sql = """
|
||||||
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
||||||
FROM blocks
|
FROM blocks
|
||||||
WHERE LOWER(login)=LOWER(?) AND block_number=? AND block_hash=?
|
WHERE LOWER(login)=LOWER(?) AND block_number=? AND block_hash=?
|
||||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||||
@@ -172,7 +171,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
|
|
||||||
private PostRow findByNumber(Connection c, String bchName, int blockNumber) throws Exception {
|
private PostRow findByNumber(Connection c, String bchName, int blockNumber) throws Exception {
|
||||||
String sql = """
|
String sql = """
|
||||||
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
||||||
FROM blocks
|
FROM blocks
|
||||||
WHERE LOWER(login)=LOWER(?) AND block_number=?
|
WHERE LOWER(login)=LOWER(?) AND block_number=?
|
||||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||||
@@ -191,7 +190,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
|
|
||||||
private PostRow findByNumberAndHash(Connection c, String bchName, int blockNumber, byte[] blockHash) throws Exception {
|
private PostRow findByNumberAndHash(Connection c, String bchName, int blockNumber, byte[] blockHash) throws Exception {
|
||||||
String sql = """
|
String sql = """
|
||||||
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
||||||
FROM blocks
|
FROM blocks
|
||||||
WHERE LOWER(login)=LOWER(?) AND block_number=? AND block_hash=?
|
WHERE LOWER(login)=LOWER(?) AND block_number=? AND block_hash=?
|
||||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||||
@@ -226,6 +225,9 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
row.blockNumber = rs.getInt("block_number");
|
row.blockNumber = rs.getInt("block_number");
|
||||||
row.blockHash = rs.getBytes("block_hash");
|
row.blockHash = rs.getBytes("block_hash");
|
||||||
row.blockBytes = rs.getBytes("block_bytes");
|
row.blockBytes = rs.getBytes("block_bytes");
|
||||||
|
row.dataItemId = rs.getBytes("data_item_id");
|
||||||
|
row.arweavePublishPending = rs.getBoolean("arweave_publish_pending");
|
||||||
|
row.arweavePublishedAtMs = (Long) rs.getObject("arweave_published_at_ms");
|
||||||
row.toLogin = rs.getString("to_login");
|
row.toLogin = rs.getString("to_login");
|
||||||
row.toBchName = rs.getString("to_bch_name");
|
row.toBchName = rs.getString("to_bch_name");
|
||||||
row.toBlockNumber = (Integer) rs.getObject("to_block_number");
|
row.toBlockNumber = (Integer) rs.getObject("to_block_number");
|
||||||
@@ -259,7 +261,13 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
first.setBlockNumber(row.blockNumber);
|
first.setBlockNumber(row.blockNumber);
|
||||||
first.setBlockHash(ChannelsReadSupport.toHex(row.blockHash));
|
first.setBlockHash(ChannelsReadSupport.toHex(row.blockHash));
|
||||||
first.setText(base.text);
|
first.setText(base.text);
|
||||||
|
first.setAttachmentMetadataValid(base.attachmentMetadataValid);
|
||||||
first.setCreatedAtMs(base.createdAtMs);
|
first.setCreatedAtMs(base.createdAtMs);
|
||||||
|
ChannelsReadSupport.setStorageInfo(first, row.dataItemId, row.arweavePublishPending, row.arweavePublishedAtMs, row.blockBytes);
|
||||||
|
node.setArweaveDataItemId(first.getArweaveDataItemId());
|
||||||
|
node.setArweavePublishPending(first.getArweavePublishPending());
|
||||||
|
node.setArweavePublishedAtMs(first.getArweavePublishedAtMs());
|
||||||
|
node.setSignedDataItemBytes(first.getSignedDataItemBytes());
|
||||||
versions.add(first);
|
versions.add(first);
|
||||||
|
|
||||||
if (row.msgSubType == MsgSubType.TEXT_REPLY
|
if (row.msgSubType == MsgSubType.TEXT_REPLY
|
||||||
@@ -275,19 +283,18 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
v.setBlockNumber(edit.blockNumber);
|
v.setBlockNumber(edit.blockNumber);
|
||||||
v.setBlockHash(ChannelsReadSupport.toHex(edit.blockHash));
|
v.setBlockHash(ChannelsReadSupport.toHex(edit.blockHash));
|
||||||
v.setText(et.text);
|
v.setText(et.text);
|
||||||
|
v.setAttachmentMetadataValid(et.attachmentMetadataValid);
|
||||||
v.setCreatedAtMs(et.createdAtMs);
|
v.setCreatedAtMs(et.createdAtMs);
|
||||||
|
ChannelsReadSupport.setStorageInfo(v, edit.dataItemId, edit.arweavePublishPending, edit.arweavePublishedAtMs, edit.blockBytes);
|
||||||
versions.add(v);
|
versions.add(v);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
node.setVersions(versions);
|
node.setVersions(versions);
|
||||||
node.setVersionsTotal(versions.size());
|
node.setVersionsTotal(versions.size());
|
||||||
|
node.setAttachmentMetadataValid(first.isAttachmentMetadataValid());
|
||||||
node.setText(versions.get(versions.size() - 1).getText());
|
node.setText(versions.get(versions.size() - 1).getText());
|
||||||
|
|
||||||
if (row.blockBytes != null) {
|
|
||||||
node.setRawBlockB64(Base64.getEncoder().encodeToString(row.blockBytes));
|
|
||||||
}
|
|
||||||
|
|
||||||
int[] stats = ChannelsReadSupport.loadStats(c, row.bchName, row.blockNumber, row.blockHash);
|
int[] stats = ChannelsReadSupport.loadStats(c, row.bchName, row.blockNumber, row.blockHash);
|
||||||
node.setLikesCount(stats[0]);
|
node.setLikesCount(stats[0]);
|
||||||
node.setPrimaryLikesCount(stats[3]);
|
node.setPrimaryLikesCount(stats[3]);
|
||||||
@@ -310,7 +317,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
|
|
||||||
private List<PostRow> findEdits(Connection c, String bch, int targetBlock, byte[] targetHash, int subType) throws Exception {
|
private List<PostRow> findEdits(Connection c, String bch, int targetBlock, byte[] targetHash, int subType) throws Exception {
|
||||||
String sql = """
|
String sql = """
|
||||||
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
||||||
FROM blocks
|
FROM blocks
|
||||||
WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND msg_sub_type=?
|
WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND msg_sub_type=?
|
||||||
AND to_block_number=? AND to_block_hash=?
|
AND to_block_number=? AND to_block_hash=?
|
||||||
@@ -338,6 +345,9 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
int blockNumber;
|
int blockNumber;
|
||||||
byte[] blockHash;
|
byte[] blockHash;
|
||||||
byte[] blockBytes;
|
byte[] blockBytes;
|
||||||
|
byte[] dataItemId;
|
||||||
|
boolean arweavePublishPending;
|
||||||
|
Long arweavePublishedAtMs;
|
||||||
String toLogin;
|
String toLogin;
|
||||||
String toBchName;
|
String toBchName;
|
||||||
Integer toBlockNumber;
|
Integer toBlockNumber;
|
||||||
|
|||||||
+32
@@ -159,6 +159,11 @@ public class Net_GetChannelMessages_Response extends Net_Response {
|
|||||||
private int repliesCount;
|
private int repliesCount;
|
||||||
private int ratingsCount;
|
private int ratingsCount;
|
||||||
private int versionsTotal;
|
private int versionsTotal;
|
||||||
|
private boolean attachmentMetadataValid = true;
|
||||||
|
private String arweaveDataItemId;
|
||||||
|
private Boolean arweavePublishPending;
|
||||||
|
private Long arweavePublishedAtMs;
|
||||||
|
private Integer signedDataItemBytes;
|
||||||
private List<VersionItem> versions = new ArrayList<>();
|
private List<VersionItem> versions = new ArrayList<>();
|
||||||
|
|
||||||
public BlockRef getMessageRef() { return messageRef; }
|
public BlockRef getMessageRef() { return messageRef; }
|
||||||
@@ -221,6 +226,17 @@ public class Net_GetChannelMessages_Response extends Net_Response {
|
|||||||
public int getRatingsCount() { return ratingsCount; }
|
public int getRatingsCount() { return ratingsCount; }
|
||||||
public void setRatingsCount(int ratingsCount) { this.ratingsCount = ratingsCount; }
|
public void setRatingsCount(int ratingsCount) { this.ratingsCount = ratingsCount; }
|
||||||
|
|
||||||
|
public boolean isAttachmentMetadataValid() { return attachmentMetadataValid; }
|
||||||
|
public void setAttachmentMetadataValid(boolean value) { this.attachmentMetadataValid = value; }
|
||||||
|
public String getArweaveDataItemId() { return arweaveDataItemId; }
|
||||||
|
public void setArweaveDataItemId(String value) { this.arweaveDataItemId = value; }
|
||||||
|
public Boolean getArweavePublishPending() { return arweavePublishPending; }
|
||||||
|
public void setArweavePublishPending(Boolean value) { this.arweavePublishPending = value; }
|
||||||
|
public Long getArweavePublishedAtMs() { return arweavePublishedAtMs; }
|
||||||
|
public void setArweavePublishedAtMs(Long value) { this.arweavePublishedAtMs = value; }
|
||||||
|
public Integer getSignedDataItemBytes() { return signedDataItemBytes; }
|
||||||
|
public void setSignedDataItemBytes(Integer value) { this.signedDataItemBytes = value; }
|
||||||
|
|
||||||
public int getVersionsTotal() { return versionsTotal; }
|
public int getVersionsTotal() { return versionsTotal; }
|
||||||
public void setVersionsTotal(int versionsTotal) { this.versionsTotal = versionsTotal; }
|
public void setVersionsTotal(int versionsTotal) { this.versionsTotal = versionsTotal; }
|
||||||
|
|
||||||
@@ -234,6 +250,22 @@ public class Net_GetChannelMessages_Response extends Net_Response {
|
|||||||
private String blockHash;
|
private String blockHash;
|
||||||
private String text;
|
private String text;
|
||||||
private long createdAtMs;
|
private long createdAtMs;
|
||||||
|
private boolean attachmentMetadataValid = true;
|
||||||
|
private String arweaveDataItemId;
|
||||||
|
private Boolean arweavePublishPending;
|
||||||
|
private Long arweavePublishedAtMs;
|
||||||
|
private Integer signedDataItemBytes;
|
||||||
|
|
||||||
|
public boolean isAttachmentMetadataValid() { return attachmentMetadataValid; }
|
||||||
|
public void setAttachmentMetadataValid(boolean value) { this.attachmentMetadataValid = value; }
|
||||||
|
public String getArweaveDataItemId() { return arweaveDataItemId; }
|
||||||
|
public void setArweaveDataItemId(String value) { this.arweaveDataItemId = value; }
|
||||||
|
public Boolean getArweavePublishPending() { return arweavePublishPending; }
|
||||||
|
public void setArweavePublishPending(Boolean value) { this.arweavePublishPending = value; }
|
||||||
|
public Long getArweavePublishedAtMs() { return arweavePublishedAtMs; }
|
||||||
|
public void setArweavePublishedAtMs(Long value) { this.arweavePublishedAtMs = value; }
|
||||||
|
public Integer getSignedDataItemBytes() { return signedDataItemBytes; }
|
||||||
|
public void setSignedDataItemBytes(Integer value) { this.signedDataItemBytes = value; }
|
||||||
|
|
||||||
public int getVersionIndex() { return versionIndex; }
|
public int getVersionIndex() { return versionIndex; }
|
||||||
public void setVersionIndex(int versionIndex) { this.versionIndex = versionIndex; }
|
public void setVersionIndex(int versionIndex) { this.versionIndex = versionIndex; }
|
||||||
|
|||||||
-3
@@ -21,13 +21,10 @@ public class Net_GetMessageThread_Response extends Net_Response {
|
|||||||
|
|
||||||
public static class MessageNode extends Net_GetChannelMessages_Response.MessageItem {
|
public static class MessageNode extends Net_GetChannelMessages_Response.MessageItem {
|
||||||
private ChannelInfo channelInfo;
|
private ChannelInfo channelInfo;
|
||||||
private String rawBlockB64;
|
|
||||||
|
|
||||||
public ChannelInfo getChannelInfo() { return channelInfo; }
|
public ChannelInfo getChannelInfo() { return channelInfo; }
|
||||||
public void setChannelInfo(ChannelInfo channelInfo) { this.channelInfo = channelInfo; }
|
public void setChannelInfo(ChannelInfo channelInfo) { this.channelInfo = channelInfo; }
|
||||||
|
|
||||||
public String getRawBlockB64() { return rawBlockB64; }
|
|
||||||
public void setRawBlockB64(String rawBlockB64) { this.rawBlockB64 = rawBlockB64; }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class ChannelInfo {
|
public static class ChannelInfo {
|
||||||
|
|||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
package server.logic.ws_protocol.JSON.handlers.channels;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class AttachmentMarkerValidatorTest {
|
||||||
|
private static final String PR = "4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi";
|
||||||
|
private static String marker(String fields) { return "<S:att;" + fields + ">\nтекст"; }
|
||||||
|
|
||||||
|
@Test void validUnicodeAndEscapes() {
|
||||||
|
assertTrue(AttachmentMarkerValidator.validateLeadingV2Markers(marker("v=2;nm=Водопад%3Bлето%3D2026.mp4;sz=1837243;pr=" + PR + ";mm=video/mp4")));
|
||||||
|
assertTrue(AttachmentMarkerValidator.validateLeadingV2Markers("Обычный текст"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void rejectsMalformedV2WithoutChangingBlock() {
|
||||||
|
for (String fields : new String[]{
|
||||||
|
"v=2;nm=abc;sz=10;sz=20;pr=" + PR,
|
||||||
|
"v=2;nm=abc%ZZ;sz=10;pr=" + PR,
|
||||||
|
"v=2;nm=abc;unknown=x;sz=10;pr=" + PR,
|
||||||
|
"v=2;nm=abc;sz=-1;pr=" + PR,
|
||||||
|
"v=2;nm=abc;sz=10;pr=bad",
|
||||||
|
"nm=abc;v=2;sz=10;pr=" + PR
|
||||||
|
}) assertFalse(AttachmentMarkerValidator.validateLeadingV2Markers(marker(fields)), fields);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -73,7 +73,8 @@ DEPLOY_SOLANA_ENDPOINT="https://t2.shineup.me/solana-rpc" bash deploy/scripts/te
|
|||||||
bash deploy/scripts/test_t3_server.sh
|
bash deploy/scripts/test_t3_server.sh
|
||||||
DEPLOY_SOLANA_ENDPOINT="https://t3.shineup.me/solana-rpc" bash deploy/scripts/test_t3_ui.sh
|
DEPLOY_SOLANA_ENDPOINT="https://t3.shineup.me/solana-rpc" bash deploy/scripts/test_t3_ui.sh
|
||||||
|
|
||||||
DEPLOY_SOLANA_ENDPOINT="https://test.shineup.me/solana-rpc" bash deploy/scripts/deploy_ui.sh
|
bash deploy/scripts/test_shineupme_server.sh
|
||||||
|
DEPLOY_SOLANA_ENDPOINT="https://test.shineup.me/solana-rpc" bash deploy/scripts/test_shineupme_ui.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
## Проверка
|
## Проверка
|
||||||
|
|||||||
Executable
+27
@@ -0,0 +1,27 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
# test.shineup.me использует /etc/shine/shine-test.env. Не вызываем
|
||||||
|
# deploy_server.sh: тот пересоздаёт unit без EnvironmentFile.
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
ROOT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
|
||||||
|
REMOTE_HOST="player@t4.shineup.me"
|
||||||
|
REMOTE_SERVER_DIR="/home/player/t4/server"
|
||||||
|
REMOTE_SERVICE_NAME="shine-test"
|
||||||
|
LOCAL_JAR="$ROOT_DIR/SHiNE-server/build/libs/shine-server.jar"
|
||||||
|
|
||||||
|
echo "==> Building server jar"
|
||||||
|
(cd "$ROOT_DIR" && ./gradlew shadowJar)
|
||||||
|
|
||||||
|
if [[ ! -s "$LOCAL_JAR" ]]; then
|
||||||
|
echo "ERROR: server jar not found: $LOCAL_JAR" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> Deploy server to test.shineup.me ($REMOTE_HOST)"
|
||||||
|
ssh -o BatchMode=yes -o ConnectTimeout=20 "$REMOTE_HOST" "echo SSH OK" >/dev/null
|
||||||
|
rsync -az --timeout=120 "$LOCAL_JAR" "$ROOT_DIR/allowed-email-domains.txt" \
|
||||||
|
"$REMOTE_HOST:$REMOTE_SERVER_DIR/"
|
||||||
|
ssh "$REMOTE_HOST" "sudo systemctl restart '$REMOTE_SERVICE_NAME'; sudo systemctl --no-pager --full status '$REMOTE_SERVICE_NAME'"
|
||||||
|
|
||||||
|
echo "Всё хорошо: сервер test.shineup.me обновлён и сервис $REMOTE_SERVICE_NAME перезапущен"
|
||||||
Executable
+20
@@ -0,0 +1,20 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
# Use an explicit public RPC gateway URL. Never commit an Helius API key.
|
||||||
|
if [[ -z "${DEPLOY_SOLANA_ENDPOINT:-}" ]]; then
|
||||||
|
echo "ERROR: DEPLOY_SOLANA_ENDPOINT is required for test.shineup.me UI deploy." >&2
|
||||||
|
echo "Set it to a working public RPC gateway (prefer https://test.shineup.me/solana-rpc)." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
REMOTE_HOST="player@t4.shineup.me" \
|
||||||
|
REMOTE_UI_DIR="/home/player/t4/UI" \
|
||||||
|
EXPECTED_CADDY_UI_ROOT="/home/player/t4/UI" \
|
||||||
|
EXPECTED_CADDY_SITE="test.shineup.me" \
|
||||||
|
DEPLOY_SERVER_LOGIN="test_server@shine" \
|
||||||
|
DEPLOY_SERVER_ADDRESS="test.shineup.me" \
|
||||||
|
DEPLOY_SOLANA_CLUSTER="devnet" \
|
||||||
|
DEPLOY_SOLANA_ENDPOINT="$DEPLOY_SOLANA_ENDPOINT" \
|
||||||
|
TARGET_URL="https://test.shineup.me" \
|
||||||
|
bash "$(dirname "$0")/deploy_ui.sh"
|
||||||
@@ -275,9 +275,10 @@
|
|||||||
### MessageNode (дополнение)
|
### MessageNode (дополнение)
|
||||||
- `MessageNode` расширяет формат сообщения из `GetChannelMessages` и дополнительно содержит:
|
- `MessageNode` расширяет формат сообщения из `GetChannelMessages` и дополнительно содержит:
|
||||||
- `channelInfo` — мета-информация о канале (если применимо);
|
- `channelInfo` — мета-информация о канале (если применимо);
|
||||||
- `rawBlockB64` — сырой `block_bytes` текущего блока в Base64.
|
- `channelInfo` не содержит бинарной записи. Для полного оригинала используется существующая публичная операция `GetBlockchainBlock` (поля `blockchainName`, `blockNumber`, ответ `blockBytesB64`).
|
||||||
- Поле `rawBlockB64` присутствует у узлов во всех частях ответа `GetMessageThread`: `focus`, `ancestors[]`, `descendants[]`.
|
- `rawBlockB64` больше **не отправляется** в обычном `GetMessageThread` — ни для focus, ни для ancestors/descendants, что экономит трафик.
|
||||||
- В `GetChannelMessages` поле `rawBlockB64` **не добавляется** (лента канала без сырого блока, чтобы не раздувать ответ).
|
- В `GetChannelMessages` полный бинарный блок также не передаётся.
|
||||||
|
- В обоих ответах `MessageItem` содержит `arweaveDataItemId` (Base64URL SHA-256 подписи, 43 символа), `arweavePublishPending`, `arweavePublishedAtMs`, `signedDataItemBytes`, `attachmentMetadataValid` (серверная проверка синтаксиса маркеров `v=2`; исходный текст остаётся неизменным). Эти же поля возвращаются **для каждого элемента `versions[]`**, поскольку каждая редакция — отдельный DataItem. `arweavePublishedAtMs` означает регистрацию отправки сервисом, а не независимую проверку шлюза. Поля могут быть `null`, если metadata отсутствует. URL полезных данных: `https://arweave.net/raw/<arweaveDataItemId>`; полный подписанный ANS-104 возвращается по `GetBlockchainBlock`, но это ответ сервера SHiNE, не доказательство извлечения оболочки из Arweave.
|
||||||
- И в `GetChannelMessages`, и в `GetMessageThread` каждое сообщение теперь содержит:
|
- И в `GetChannelMessages`, и в `GetMessageThread` каждое сообщение теперь содержит:
|
||||||
- `repliesCount` — число дочерних сообщений типа `TEXT_REPLY`;
|
- `repliesCount` — число дочерних сообщений типа `TEXT_REPLY`;
|
||||||
- `ratingsCount` — число дочерних сообщений типа `TEXT_RATING`.
|
- `ratingsCount` — число дочерних сообщений типа `TEXT_RATING`.
|
||||||
|
|||||||
@@ -103,7 +103,7 @@ Login/fork для edit не подписываются: edit может ссыл
|
|||||||
- Такой edit трактуется как логическое удаление содержимого сообщения.
|
- Такой edit трактуется как логическое удаление содержимого сообщения.
|
||||||
- Для удаления отдельного сообщения используется именно edit-блок; отдельного `DELETE`-подтипа сообщения нет. `TEXT_CHANNEL_DELETE=92` относится только к soft-delete всего канала.
|
- Для удаления отдельного сообщения используется именно edit-блок; отдельного `DELETE`-подтипа сообщения нет. `TEXT_CHANNEL_DELETE=92` относится только к soft-delete всего канала.
|
||||||
|
|
||||||
## Вложения в текстовых сообщениях (`S:att v=1`)
|
## Вложения в текстовых сообщениях (`S:att v=1` и `v=2`)
|
||||||
|
|
||||||
Для `TEXT_POST`, `TEXT_REPLY`, `TEXT_EDIT_POST` и `TEXT_EDIT_REPLY` клиент может хранить вложения как технические строки в начале обычного `text`.
|
Для `TEXT_POST`, `TEXT_REPLY`, `TEXT_EDIT_POST` и `TEXT_EDIT_REPLY` клиент может хранить вложения как технические строки в начале обычного `text`.
|
||||||
|
|
||||||
@@ -127,8 +127,8 @@ Arweave-вложение:
|
|||||||
|
|
||||||
Обязательные поля:
|
Обязательные поля:
|
||||||
|
|
||||||
- `v=1`
|
- `v=1` для исторических записей, `v=2` для новых
|
||||||
- `nm` - имя файла, закодированное через `encodeURIComponent`
|
- `nm` - имя файла: для `v=1` старое `encodeURIComponent`, для `v=2` UTF-8 с экранированием только `%`, `<`, `>`, `=`, `;`
|
||||||
- `sz` - размер файла в байтах
|
- `sz` - размер файла в байтах
|
||||||
- `sha256` - SHA-256 исходного файла в hex
|
- `sha256` - SHA-256 исходного файла в hex
|
||||||
|
|
||||||
@@ -151,4 +151,6 @@ Arweave-вложение:
|
|||||||
- старые клиенты без поддержки вложений могут показывать технические строки как обычный текст;
|
- старые клиенты без поддержки вложений могут показывать технические строки как обычный текст;
|
||||||
- пустой пользовательский текст допустим, если перед ним есть хотя бы один валидный attach-блок.
|
- пустой пользовательский текст допустим, если перед ним есть хотя бы один валидный attach-блок.
|
||||||
|
|
||||||
|
В `v=2` при структурированном чтении проверяется уникальность полей, допустимость кодирования и значений. Безопасное текстовое представление и файловые URL должны дополнительно валидироваться на клиенте и сервере.
|
||||||
|
|
||||||
Сам файл всегда хранится вне блокчейна. В блокчейне остаются имя, размер, SHA-256 и, только для Arweave-вложения, `ar`.
|
Сам файл всегда хранится вне блокчейна. В блокчейне остаются имя, размер, SHA-256 и, только для Arweave-вложения, `ar`.
|
||||||
|
|||||||
@@ -1,17 +1,19 @@
|
|||||||
# Вложения в TEXT-сообщениях (`S:att;v=1`)
|
# Вложения в TEXT-сообщениях (`S:att;v=1` и `v=2`)
|
||||||
|
|
||||||
Технический префикс в UTF-8 `text` для `TEXT_POST`, `TEXT_REPLY`, `TEXT_EDIT_POST`, `TEXT_EDIT_REPLY`. Бинарный формат TEXT не меняется. До 10 вложений в начале сообщения, затем обычный текст; порядок сохраняется.
|
Технический префикс в UTF-8 `text` для `TEXT_POST`, `TEXT_REPLY`, `TEXT_EDIT_POST`, `TEXT_EDIT_REPLY`. Бинарный формат TEXT не меняется. До 10 вложений в начале сообщения, затем обычный текст; порядок сохраняется.
|
||||||
|
|
||||||
## Канонический формат (2026-11)
|
## Канонический формат (2026-11, v=2)
|
||||||
|
|
||||||
```text
|
```text
|
||||||
<S:att;v=1;nm=photo.jpg;sz=248193;pr=BASE58_ROOT;mm=image/jpeg>
|
<S:att;v=2;nm=photo.jpg;sz=248193;pr=BASE58_ROOT;mm=image/jpeg>
|
||||||
<S:att;v=1;nm=video.mp4;sz=15000000;pr=BASE58_ROOT;mm=video/mp4;ar=TXID>
|
<S:att;v=2;nm=video.mp4;sz=15000000;pr=BASE58_ROOT;mm=video/mp4;ar=TXID>
|
||||||
Текст публикации
|
Текст публикации
|
||||||
```
|
```
|
||||||
|
|
||||||
- `v` — версия (1).
|
- `v` — версия: **2** для новых публикаций, старые `v=1` остаются читаемыми.
|
||||||
- `nm` — имя файла в `encodeURIComponent`.
|
- `nm` — UTF-8 имя файла без массового URL-кодирования. В `v=2` только служебные символы кодируются однобайтовыми ASCII-последовательностями: `%`→`%25`, `;`→`%3B`, `=`→`%3D`, `<`→`%3C`, `>`→`%3E`. Управляющие символы в именах не допускаются. Фактическая нормализация клиента заменяет `\` и `/` на `_` (старое правило).
|
||||||
|
- Пример: `Водопад.mp4` записывается как `Водопад.mp4`; `Лето;фильм=1.mp4` — как `Лето%3Bфильм%3D1.mp4`.
|
||||||
|
- Парсер v=2 отвергает неизвестные и повторные ключи, неверное экранирование, ошибочный MIME, некорректную длину/идентификатор. Сервер/импортёр не должны доверять метаданным клиента и обязаны проверять формат при структурированном чтении. Блокчейн и исходный `text` хранятся побайтово неизменными.
|
||||||
- `sz` — размер подготовленных байтов в десятичном виде.
|
- `sz` — размер подготовленных байтов в десятичном виде.
|
||||||
- `pr` — **BitTorrent v2 Pieces Root (32 байта), Base58**, не SHA-256 целого файла; текущий стандарт новых вложений.
|
- `pr` — **BitTorrent v2 Pieces Root (32 байта), Base58**, не SHA-256 целого файла; текущий стандарт новых вложений.
|
||||||
- `mm` — необязательный MIME, в формате `type/subtype`; неизвестный — `application/octet-stream`.
|
- `mm` — необязательный MIME, в формате `type/subtype`; неизвестный — `application/octet-stream`.
|
||||||
@@ -32,4 +34,4 @@ HTML, SVG, XHTML, JavaScript, XML по расширению или MIME выво
|
|||||||
|
|
||||||
## Совместимость
|
## Совместимость
|
||||||
|
|
||||||
Парсер терпимо читает старое поле `sha256` и префиксы `<SHiNE:attach>`/`<S:attach>`, если данные сохранились. Массовая миграция не выполняется. Экспериментальные `preAr`, `preSha256`, `previewAr`, `previewSha256`, `width`, `duration`, `thumbnail` не входят в протокол.
|
Существующий `v=1` использует `encodeURIComponent`/`decodeURIComponent`. Новые записи создаются в `v=2`, уже записанные блоки не переписываются. Парсер терпимо читает старое поле `sha256` и префиксы `<SHiNE:attach>`/`<S:attach>`, если данные сохранились. Массовая миграция не выполняется. Экспериментальные `preAr`, `preSha256`, `previewAr`, `previewSha256`, `width`, `duration`, `thumbnail` не входят в протокол.
|
||||||
|
|||||||
@@ -1,3 +1,8 @@
|
|||||||
|
## 2026-11-19 — Компактные имена вложений в `S:att v=2`
|
||||||
|
|
||||||
|
- `S:att;v=2` записывает UTF-8 имена непосредственно и %-кодирует только служебные символы; `v=1` остаётся читаемым, бинарный Frame не изменён.
|
||||||
|
- Парсер клиента проверяет имена, повторные поля, MIME и идентификаторы. Сервер передаёт исходный текст неизменным и не считает маркеры вложений достоверными без их разбора.
|
||||||
|
|
||||||
## 2026-11-08 — Минимальная длина имени нового канала в TECH_CREATE_CHANNEL
|
## 2026-11-08 — Минимальная длина имени нового канала в TECH_CREATE_CHANNEL
|
||||||
|
|
||||||
- Для создания блока `TECH_CREATE_CHANNEL (type=0/subType=1/version=1)` введён протокольный минимум `channelName`: **4 символа**; максимум остаётся 32.
|
- Для создания блока `TECH_CREATE_CHANNEL (type=0/subType=1/version=1)` введён протокольный минимум `channelName`: **4 символа**; максимум остаётся 32.
|
||||||
|
|||||||
@@ -0,0 +1,173 @@
|
|||||||
|
import { t } from '../i18n/index.js';
|
||||||
|
import { formatDateTime } from '../i18n/format.js';
|
||||||
|
import { escapeHtml } from '../services/attachment-format.js';
|
||||||
|
import { arweaveBlockUrl, checkArweavePayload, checkSolanaAuthor, readSignedBlock, signedDataItemFilename } from '../services/blockchain-proof-service.js';
|
||||||
|
import { showToast } from '../services/channels-ux.js';
|
||||||
|
|
||||||
|
const validHash = (value) => /^[0-9a-f]{64}$/iu.test(String(value || ''));
|
||||||
|
const label = (key) => t(`blockchain_details.${key}`);
|
||||||
|
const safe = (value) => escapeHtml(String(value ?? ''));
|
||||||
|
const shortened = (value) => String(value || '').length > 24
|
||||||
|
? `${String(value).slice(0, 12)}…${String(value).slice(-8)}` : String(value || '');
|
||||||
|
|
||||||
|
function asVersions(details) {
|
||||||
|
const raw = Array.isArray(details?.raw?.versions) ? details.raw.versions : [];
|
||||||
|
if (raw.length) return raw.map((v, i) => ({ ...v, versionIndex: Number(v.versionIndex || i + 1) }));
|
||||||
|
return [{ versionIndex: 1, blockNumber: details.blockNumber, blockHash: details.blockHash,
|
||||||
|
createdAtMs: details.createdAtMs, arweaveDataItemId: details.raw?.arweaveDataItemId || '',
|
||||||
|
arweavePublishPending: details.raw?.arweavePublishPending,
|
||||||
|
arweavePublishedAtMs: details.raw?.arweavePublishedAtMs,
|
||||||
|
signedDataItemBytes: details.raw?.signedDataItemBytes }];
|
||||||
|
}
|
||||||
|
function field(title, value, { code = false } = {}) {
|
||||||
|
const valueHtml = code ? `<code title="${safe(value)}">${safe(value)}</code>` : `<strong>${safe(value)}</strong>`;
|
||||||
|
return `<div class="block-proof-row"><span>${safe(title)}</span>${valueHtml}</div>`;
|
||||||
|
}
|
||||||
|
function statusFor(version) {
|
||||||
|
if (version?.arweavePublishedAtMs > 0) return { color: 'success', text: label('published') };
|
||||||
|
if (version?.arweavePublishPending === true) return { color: 'pending', text: label('pending') };
|
||||||
|
return { color: 'unknown', text: label('unknown') };
|
||||||
|
}
|
||||||
|
async function copy(value) {
|
||||||
|
const text = String(value || '');
|
||||||
|
if (!text) return;
|
||||||
|
if (navigator.clipboard?.writeText) {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
} else {
|
||||||
|
const input = document.createElement('textarea');
|
||||||
|
input.value = text; input.style.position = 'fixed'; input.style.opacity = '0';
|
||||||
|
document.body.append(input); input.select(); document.execCommand('copy'); input.remove();
|
||||||
|
}
|
||||||
|
showToast(label('copied'));
|
||||||
|
}
|
||||||
|
function resultRow(name, status, reason = '') {
|
||||||
|
const mark = status === 'valid' ? '✓' : status === 'invalid' ? '✕' : '—';
|
||||||
|
const description = status === 'valid' ? label('verified') : status === 'invalid' ? label('failed') : label('not_verified');
|
||||||
|
return `<div class="block-proof-check block-proof-check--${status}"><span aria-hidden="true">${mark}</span><div><strong>${safe(name)}: ${safe(description)}</strong>${reason ? `<small>${safe(reason)}</small>` : ''}</div></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Единый диалог для ленты канала и страницы обсуждения. */
|
||||||
|
export function openBlockchainDetailsModal(details, { authService, solanaEndpoint, isActive = () => true } = {}) {
|
||||||
|
const root = document.getElementById('modal-root');
|
||||||
|
if (!root) return;
|
||||||
|
const versions = asVersions(details);
|
||||||
|
let current = versions.length - 1;
|
||||||
|
let busy = false;
|
||||||
|
const rawText = JSON.stringify(details.raw || {}, null, 2);
|
||||||
|
root.innerHTML = `
|
||||||
|
<div class="modal" id="blockchain-details-modal">
|
||||||
|
<section class="modal-card stack blockchain-details-card block-proof-card" role="dialog" aria-modal="true" aria-label="${safe(label('title'))}">
|
||||||
|
<header class="block-proof-header">
|
||||||
|
<span class="block-proof-icon" aria-hidden="true">⛓</span>
|
||||||
|
<div><h3 class="modal-title">${safe(label('title'))}</h3><p class="meta-muted">${safe(label('description'))}</p></div>
|
||||||
|
</header>
|
||||||
|
${versions.length > 1 ? `<label class="field-label" for="block-proof-version">${safe(label('version'))}</label>
|
||||||
|
<select class="input" id="block-proof-version">${versions.map((v, i) => `<option value="${i}" ${i === current ? 'selected' : ''}>${safe(label('version'))} ${i + 1} · #${safe(v.blockNumber)}</option>`).join('')}</select>` : ''}
|
||||||
|
<div id="block-proof-content"></div>
|
||||||
|
<div class="block-proof-actions">
|
||||||
|
<a class="secondary-btn block-proof-link" id="block-proof-open" target="_blank" rel="noopener noreferrer">↗ ${safe(label('open_arweave'))}</a>
|
||||||
|
<button class="secondary-btn" type="button" id="block-proof-copy-url">${safe(label('copy_url'))}</button>
|
||||||
|
<button class="secondary-btn" type="button" id="block-proof-download">↓ ${safe(label('download_signed'))}</button>
|
||||||
|
<button class="secondary-btn block-proof-verify" type="button" id="block-proof-verify">🛡 ${safe(label('verify'))}</button>
|
||||||
|
</div>
|
||||||
|
<div id="block-proof-results" class="block-proof-results" hidden aria-live="polite"></div>
|
||||||
|
<details class="block-proof-raw"><summary>${safe(label('technical'))}</summary>
|
||||||
|
<pre class="blockchain-raw-block">${safe(rawText)}</pre>
|
||||||
|
<button class="secondary-btn" id="block-proof-copy-raw" type="button">${safe(label('copy_raw'))}</button>
|
||||||
|
</details>
|
||||||
|
<button class="secondary-btn" id="block-proof-close" type="button">${safe(label('close'))}</button>
|
||||||
|
</section>
|
||||||
|
</div>`;
|
||||||
|
const get = (id) => root.querySelector(`#${id}`);
|
||||||
|
const currentVersion = () => versions[current];
|
||||||
|
const content = get('block-proof-content');
|
||||||
|
const results = get('block-proof-results');
|
||||||
|
const button = get('block-proof-download');
|
||||||
|
const verify = get('block-proof-verify');
|
||||||
|
const close = () => { if (get('blockchain-details-modal')) root.innerHTML = ''; };
|
||||||
|
function renderVersion() {
|
||||||
|
const v = currentVersion();
|
||||||
|
const archive = statusFor(v);
|
||||||
|
const hash = validHash(v.blockHash) ? v.blockHash : '';
|
||||||
|
const url = arweaveBlockUrl(v.arweaveDataItemId);
|
||||||
|
const date = Number(v.createdAtMs || details.createdAtMs);
|
||||||
|
content.innerHTML = `
|
||||||
|
<div class="block-proof-facts">
|
||||||
|
${field(label('author'), details.authorLogin || '—')}
|
||||||
|
${field(label('blockchain'), details.authorBlockchainName || '—', { code: true })}
|
||||||
|
${field(label('block_number'), v.blockNumber)}
|
||||||
|
${field(label('created'), date > 0 ? formatDateTime(new Date(date)) : '—')}
|
||||||
|
${field(label('storage'), 'Arweave')}
|
||||||
|
${field(label('signed_size'), Number.isInteger(v.signedDataItemBytes) ? `${v.signedDataItemBytes} ${label('bytes')}` : '—')}
|
||||||
|
</div>
|
||||||
|
${v.attachmentMetadataValid === false ? `<p class="block-proof-warning">${safe(label('invalid_attachment'))}</p>` : ''}
|
||||||
|
<div class="block-proof-status block-proof-status--${archive.color}"><span class="block-proof-dot"></span>${safe(archive.text)}</div>
|
||||||
|
<div class="block-proof-hash"><span>${safe(label('hash'))}</span><div><code title="${safe(hash)}">${safe(shortened(hash) || '—')}</code><button type="button" class="block-proof-copy-icon" id="block-proof-copy-hash" ${hash ? '' : 'disabled'} aria-label="${safe(label('copy_hash'))}" title="${safe(label('copy_hash'))}">⧉</button></div></div>
|
||||||
|
${url ? `<div class="block-proof-hash"><span>Arweave DataItem ID</span><div><code title="${safe(v.arweaveDataItemId)}">${safe(shortened(v.arweaveDataItemId))}</code><button type="button" class="block-proof-copy-icon" id="block-proof-copy-id" aria-label="${safe(label('copy_id'))}" title="${safe(label('copy_id'))}">⧉</button></div></div>` : ''}`;
|
||||||
|
get('block-proof-open').href = url || '#';
|
||||||
|
get('block-proof-open').hidden = !url;
|
||||||
|
get('block-proof-copy-url').disabled = !url;
|
||||||
|
get('block-proof-copy-hash')?.addEventListener('click', () => { void copy(hash); });
|
||||||
|
get('block-proof-copy-id')?.addEventListener('click', () => { void copy(v.arweaveDataItemId); });
|
||||||
|
results.hidden = true;
|
||||||
|
results.replaceChildren();
|
||||||
|
}
|
||||||
|
async function signedBlock() {
|
||||||
|
const v = currentVersion();
|
||||||
|
if (!validHash(v.blockHash)) throw new Error(label('missing_hash'));
|
||||||
|
return readSignedBlock({ authService, blockchainName: details.authorBlockchainName,
|
||||||
|
blockNumber: v.blockNumber, blockHash: v.blockHash, dataItemId: v.arweaveDataItemId });
|
||||||
|
}
|
||||||
|
get('block-proof-version')?.addEventListener('change', (event) => {
|
||||||
|
if (busy) { event.target.value = String(current); return; }
|
||||||
|
current = Number(event.target.value); renderVersion();
|
||||||
|
});
|
||||||
|
get('block-proof-copy-url')?.addEventListener('click', () => { void copy(arweaveBlockUrl(currentVersion().arweaveDataItemId)); });
|
||||||
|
get('block-proof-copy-raw')?.addEventListener('click', () => { void copy(rawText); });
|
||||||
|
get('block-proof-close')?.addEventListener('click', close);
|
||||||
|
button.addEventListener('click', async () => {
|
||||||
|
if (busy) return;
|
||||||
|
busy = true; button.disabled = true; verify.disabled = true;
|
||||||
|
try {
|
||||||
|
const proof = await signedBlock();
|
||||||
|
if (!isActive() || !get('blockchain-details-modal')) return;
|
||||||
|
const blobUrl = URL.createObjectURL(new Blob([proof.bytes], { type: 'application/octet-stream' }));
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = blobUrl;
|
||||||
|
link.download = signedDataItemFilename(details.authorBlockchainName, currentVersion().blockNumber);
|
||||||
|
document.body.append(link); link.click(); link.remove();
|
||||||
|
setTimeout(() => URL.revokeObjectURL(blobUrl), 30000);
|
||||||
|
} catch (error) { if (isActive()) showToast(String(error?.message || error), { kind: 'error' }); }
|
||||||
|
finally { busy = false; button.disabled = false; verify.disabled = false; }
|
||||||
|
});
|
||||||
|
verify.addEventListener('click', async () => {
|
||||||
|
if (busy) return;
|
||||||
|
busy = true; verify.disabled = true; button.disabled = true;
|
||||||
|
const select = get('block-proof-version'); if (select) select.disabled = true;
|
||||||
|
results.hidden = false; results.textContent = label('checking');
|
||||||
|
try {
|
||||||
|
const proof = await signedBlock();
|
||||||
|
const id = currentVersion().arweaveDataItemId || proof.actualId;
|
||||||
|
const [arweave, solana] = await Promise.all([
|
||||||
|
checkArweavePayload(id, proof.data),
|
||||||
|
checkSolanaAuthor({ authorLogin: details.authorLogin, blockchainName: details.authorBlockchainName,
|
||||||
|
owner32: proof.owner32, solanaEndpoint }),
|
||||||
|
]);
|
||||||
|
if (!isActive() || !get('blockchain-details-modal')) return;
|
||||||
|
results.innerHTML = [
|
||||||
|
resultRow(label('signature'), 'valid'),
|
||||||
|
resultRow(label('integrity'), 'valid'),
|
||||||
|
resultRow(label('arweave_check'), arweave.status, arweave.reason),
|
||||||
|
resultRow(label('solana_check'), solana.status, solana.reason),
|
||||||
|
`<p class="meta-muted">${safe(label('proof_note'))}</p>`,
|
||||||
|
].join('');
|
||||||
|
} catch (error) {
|
||||||
|
if (!isActive() || !get('blockchain-details-modal')) return;
|
||||||
|
results.innerHTML = resultRow(label('signed_check'), 'unavailable', String(error?.message || error));
|
||||||
|
} finally {
|
||||||
|
busy = false;
|
||||||
|
if (get('blockchain-details-modal')) { verify.disabled = false; button.disabled = false; if (select) select.disabled = false; }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
renderVersion();
|
||||||
|
}
|
||||||
@@ -4856,5 +4856,43 @@
|
|||||||
"usdt_limit": "Beta limit: up to 5 USDT per swap. Keep SOL available for fees.",
|
"usdt_limit": "Beta limit: up to 5 USDT per swap. Keep SOL available for fees.",
|
||||||
"wallet_hint": "🧪 Experimental SOL ↔ USDT swaps via Jupiter. Not recommended for real funds; please review the warnings before trying.",
|
"wallet_hint": "🧪 Experimental SOL ↔ USDT swaps via Jupiter. Not recommended for real funds; please review the warnings before trying.",
|
||||||
"wallet_button": "Swap · Jupiter β"
|
"wallet_button": "Swap · Jupiter β"
|
||||||
|
},
|
||||||
|
"blockchain_details": {
|
||||||
|
"invalid_attachment": "Attachment metadata is invalid; the original block remains unchanged.",
|
||||||
|
"title": "Blockchain data",
|
||||||
|
"description": "Original record and independent verification",
|
||||||
|
"author": "Author",
|
||||||
|
"blockchain": "Author blockchain",
|
||||||
|
"block_number": "Block number",
|
||||||
|
"created": "Created",
|
||||||
|
"storage": "Storage",
|
||||||
|
"signed_size": "Signed DataItem size",
|
||||||
|
"bytes": "bytes",
|
||||||
|
"published": "Submitted to Arweave",
|
||||||
|
"pending": "Pending upload to Arweave",
|
||||||
|
"unknown": "Arweave status not confirmed",
|
||||||
|
"hash": "SHiNE block SHA-256",
|
||||||
|
"copy_hash": "Copy hash",
|
||||||
|
"copy_id": "Copy DataItem ID",
|
||||||
|
"version": "Version",
|
||||||
|
"open_arweave": "Open in Arweave",
|
||||||
|
"copy_url": "Copy link",
|
||||||
|
"download_signed": "Download signed record",
|
||||||
|
"verify": "Verify authenticity",
|
||||||
|
"technical": "Original server response · technical data",
|
||||||
|
"copy_raw": "Copy JSON",
|
||||||
|
"close": "Close",
|
||||||
|
"copied": "Copied",
|
||||||
|
"missing_hash": "Missing valid block hash",
|
||||||
|
"checking": "Checking the record, Arweave and Solana…",
|
||||||
|
"verified": "verified",
|
||||||
|
"failed": "does not match",
|
||||||
|
"not_verified": "not verified",
|
||||||
|
"signature": "Ed25519 signature",
|
||||||
|
"integrity": "Block integrity and DataItem ID",
|
||||||
|
"arweave_check": "Data in Arweave",
|
||||||
|
"solana_check": "Author key in Solana",
|
||||||
|
"signed_check": "Signed record",
|
||||||
|
"proof_note": "Verification runs in your browser. Unavailable Arweave or Solana data does not mean forgery. Key ownership does not prove an exact publication time. Free users without a PDA cannot be verified through Solana."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4856,5 +4856,43 @@
|
|||||||
"usdt_limit": "Бета-лимит: до 5 USDT за обмен. Нужен запас SOL на комиссии.",
|
"usdt_limit": "Бета-лимит: до 5 USDT за обмен. Нужен запас SOL на комиссии.",
|
||||||
"wallet_hint": "🧪 Тестовый обмен SOL ↔ USDT через Jupiter. Функция не рекомендована для реальных средств: откройте предупреждение перед использованием.",
|
"wallet_hint": "🧪 Тестовый обмен SOL ↔ USDT через Jupiter. Функция не рекомендована для реальных средств: откройте предупреждение перед использованием.",
|
||||||
"wallet_button": "Обменять · Jupiter β"
|
"wallet_button": "Обменять · Jupiter β"
|
||||||
|
},
|
||||||
|
"blockchain_details": {
|
||||||
|
"invalid_attachment": "Вложение содержит некорректные метаданные; исходный блок сохранён без изменений.",
|
||||||
|
"title": "Данные блокчейна",
|
||||||
|
"description": "Исходная запись и её независимая проверка",
|
||||||
|
"author": "Автор",
|
||||||
|
"blockchain": "Блокчейн автора",
|
||||||
|
"block_number": "Номер блока",
|
||||||
|
"created": "Создан",
|
||||||
|
"storage": "Хранилище",
|
||||||
|
"signed_size": "Полный подписанный блок",
|
||||||
|
"bytes": "байт",
|
||||||
|
"published": "Отправлено в Arweave",
|
||||||
|
"pending": "Ожидает отправки в Arweave",
|
||||||
|
"unknown": "Состояние Arweave не подтверждено",
|
||||||
|
"hash": "SHA-256 блока SHiNE",
|
||||||
|
"copy_hash": "Скопировать хеш",
|
||||||
|
"copy_id": "Скопировать DataItem ID",
|
||||||
|
"version": "Версия",
|
||||||
|
"open_arweave": "Открыть в Arweave",
|
||||||
|
"copy_url": "Скопировать ссылку",
|
||||||
|
"download_signed": "Скачать с подписью",
|
||||||
|
"verify": "Проверить подлинность",
|
||||||
|
"technical": "Исходный ответ сервера · технические данные",
|
||||||
|
"copy_raw": "Скопировать JSON",
|
||||||
|
"close": "Закрыть",
|
||||||
|
"copied": "Скопировано",
|
||||||
|
"missing_hash": "Нет корректного хеша блока",
|
||||||
|
"checking": "Проверяем оригинал, Arweave и Solana…",
|
||||||
|
"verified": "подтверждено",
|
||||||
|
"failed": "не совпадает",
|
||||||
|
"not_verified": "не проверено",
|
||||||
|
"signature": "Подпись Ed25519",
|
||||||
|
"integrity": "Целостность блока и DataItem ID",
|
||||||
|
"arweave_check": "Данные в Arweave",
|
||||||
|
"solana_check": "Ключ автора в Solana",
|
||||||
|
"signed_check": "Подписанный блок",
|
||||||
|
"proof_note": "Проверка выполняется в браузере. Отсутствие ответа Arweave или Solana не означает подделку. Действительность ключа не подтверждает точное время публикации. Для бесплатных пользователей без PDA проверка авторства через Solana недоступна."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { formatDateTime } from '../i18n/format.js';
|
|||||||
import { t, th } from '../i18n/index.js';
|
import { t, th } from '../i18n/index.js';
|
||||||
import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
||||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||||
|
import { openBlockchainDetailsModal } from '../components/blockchain-details-dialog.js';
|
||||||
import { confirmLikeAction, showLikeStatistics } from '../components/like-action-sheet.js';
|
import { confirmLikeAction, showLikeStatistics } from '../components/like-action-sheet.js';
|
||||||
import { iconHtml } from '../components/ui-icon.js';
|
import { iconHtml } from '../components/ui-icon.js';
|
||||||
import { consumeReplyEditorOnOpen, rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js';
|
import { consumeReplyEditorOnOpen, rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js';
|
||||||
@@ -460,56 +461,10 @@ function buildBlockchainDetails({ target, authorLogin, timestampMs, text, raw, l
|
|||||||
msgSubType: msgSubType ?? source.msgSubType ?? '',
|
msgSubType: msgSubType ?? source.msgSubType ?? '',
|
||||||
createdAtMs: timestampMs || source.createdAtMs || '',
|
createdAtMs: timestampMs || source.createdAtMs || '',
|
||||||
text: String(text || ''),
|
text: String(text || ''),
|
||||||
signature: source.signature || source.blockSignature || source.authorSignature || t('screens.channel_thread_view.text_080'),
|
|
||||||
publicKey: source.publicKey || source.authorPublicKey || t('screens.channel_thread_view.text_081'),
|
|
||||||
raw,
|
raw,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function openBlockchainDetailsModal(details, { isActive = () => true } = {}) {
|
|
||||||
const root = document.getElementById('modal-root');
|
|
||||||
const rawText = JSON.stringify(details.raw || details, null, 2);
|
|
||||||
root.innerHTML = `
|
|
||||||
<div class="modal" id="thread-blockchain-details-modal">
|
|
||||||
<div class="modal-card stack blockchain-details-card">
|
|
||||||
<h3 class="modal-title">${t('dialogs.modals.channel_thread_view.label_001')}</h3>
|
|
||||||
<p class="meta-muted">${t('dialogs.modals.channel_thread_view.label_002')}</p>
|
|
||||||
<div class="blockchain-details-grid">
|
|
||||||
<span>${t('dialogs.modals.channel_thread_view.label_003')}</span><strong>${escapeHtml(details.authorLogin)}</strong>
|
|
||||||
<span>${t('dialogs.modals.channel_thread_view.label_004')}</span><code>${escapeHtml(details.authorBlockchainName)}</code>
|
|
||||||
<span>${t('dialogs.modals.channel_thread_view.label_005')}</span><code>${escapeHtml(details.blockNumber)}</code>
|
|
||||||
<span>${t('dialogs.modals.channel_thread_view.label_006')}</span><code>${escapeHtml(details.blockHash)}</code>
|
|
||||||
<span>${t('dialogs.modals.channel_thread_view.label_007')}</span><code>${escapeHtml(details.msgSubType)}</code>
|
|
||||||
<span>${t('dialogs.modals.channel_thread_view.label_008')}</span><code>${escapeHtml(details.createdAtMs ? formatDateTime(new Date(Number(details.createdAtMs))) : '–')}</code>
|
|
||||||
<span>Public key</span><code>${escapeHtml(details.publicKey)}</code>
|
|
||||||
<span>${t('dialogs.modals.channel_thread_view.label_009')}</span><code>${escapeHtml(details.signature)}</code>
|
|
||||||
</div>
|
|
||||||
<label class="field-label" for="thread-blockchain-details-text">${t('dialogs.modals.channel_thread_view.label_010')}</label>
|
|
||||||
<textarea class="input" id="thread-blockchain-details-text" rows="4" readonly>${escapeHtml(details.text)}</textarea>
|
|
||||||
<pre class="blockchain-raw-block" id="thread-blockchain-raw-block" hidden>${escapeHtml(rawText)}</pre>
|
|
||||||
<div class="form-actions-grid">
|
|
||||||
<button class="secondary-btn" id="thread-blockchain-details-copy" type="button">${t('dialogs.modals.channel_thread_view.label_011')}</button>
|
|
||||||
<button class="secondary-btn" id="thread-blockchain-details-raw" type="button">${t('dialogs.modals.channel_thread_view.label_012')}</button>
|
|
||||||
</div>
|
|
||||||
<button class="secondary-btn" id="thread-blockchain-details-close" type="button">${t('dialogs.modals.channel_thread_view.label_013')}</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
root.querySelector('#thread-blockchain-details-close')?.addEventListener('click', () => {
|
|
||||||
root.innerHTML = '';
|
|
||||||
});
|
|
||||||
root.querySelector('#thread-blockchain-details-copy')?.addEventListener('click', async () => {
|
|
||||||
await copyTextToClipboard(rawText);
|
|
||||||
if (!isActive()) return;
|
|
||||||
showToast(t('dialogs.remaining.pages.channel_thread_view.openblockchaindetailsmodal.dannye_blokcheyna_skopirovany'));
|
|
||||||
});
|
|
||||||
root.querySelector('#thread-blockchain-details-raw')?.addEventListener('click', () => {
|
|
||||||
const rawEl = root.querySelector('#thread-blockchain-raw-block');
|
|
||||||
if (!rawEl) return;
|
|
||||||
rawEl.hidden = !rawEl.hidden;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveNodeText(node) {
|
function resolveNodeText(node) {
|
||||||
return firstNonEmptyText(
|
return firstNonEmptyText(
|
||||||
latestVersionText(node?.versions),
|
latestVersionText(node?.versions),
|
||||||
@@ -1020,7 +975,7 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
|
|||||||
raw: node,
|
raw: node,
|
||||||
localNumber,
|
localNumber,
|
||||||
msgSubType,
|
msgSubType,
|
||||||
}), { isActive: handlers.isActive });
|
}), { isActive: handlers.isActive, authService, solanaEndpoint: state.entrySettings.solanaServer });
|
||||||
});
|
});
|
||||||
menuItems.push({ label: t('screens.channel_thread_view.text_012'), action: () => detailsButton.click() });
|
menuItems.push({ label: t('screens.channel_thread_view.text_012'), action: () => detailsButton.click() });
|
||||||
if (isOwnMessage) {
|
if (isOwnMessage) {
|
||||||
@@ -1255,7 +1210,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
|
|||||||
try { await navigator.clipboard.writeText(parsed.text); showToast(t('screens.channel_thread_view.text_046')); }
|
try { await navigator.clipboard.writeText(parsed.text); showToast(t('screens.channel_thread_view.text_046')); }
|
||||||
catch { showToast(t('screens.channel_thread_view.text_047'), { kind: 'error' }); }
|
catch { showToast(t('screens.channel_thread_view.text_047'), { kind: 'error' }); }
|
||||||
} },
|
} },
|
||||||
{ label: t('screens.channel_thread_view.text_020'), iconHtml: iconHtml('info'), action: () => openBlockchainDetailsModal(buildBlockchainDetails({ target, authorLogin: author, timestampMs: node?.createdAtMs, text: resolveNodeText(node), raw: node, localNumber: 0, msgSubType: Number(node?.msgSubType || 0) }), { isActive: handlers.isActive }) },
|
{ label: t('screens.channel_thread_view.text_020'), iconHtml: iconHtml('info'), action: () => openBlockchainDetailsModal(buildBlockchainDetails({ target, authorLogin: author, timestampMs: node?.createdAtMs, text: resolveNodeText(node), raw: node, localNumber: 0, msgSubType: Number(node?.msgSubType || 0) }), { isActive: handlers.isActive, authService, solanaEndpoint: state.entrySettings.solanaServer }) },
|
||||||
];
|
];
|
||||||
if (versions.length > 1) menuItems.push({ label: t('screens.channel_thread_view.text_021'), action: () => openMessageHistoryModal({ versions }) });
|
if (versions.length > 1) menuItems.push({ label: t('screens.channel_thread_view.text_021'), action: () => openMessageHistoryModal({ versions }) });
|
||||||
if (isOwn) {
|
if (isOwn) {
|
||||||
@@ -1893,7 +1848,7 @@ export function render({ navigate, route, chrome }) {
|
|||||||
const modalRoot = document.getElementById('modal-root');
|
const modalRoot = document.getElementById('modal-root');
|
||||||
if (!modalRoot) return;
|
if (!modalRoot) return;
|
||||||
if (modalRoot.querySelector([
|
if (modalRoot.querySelector([
|
||||||
'#thread-blockchain-details-modal',
|
'#blockchain-details-modal',
|
||||||
'#thread-edit-modal',
|
'#thread-edit-modal',
|
||||||
'#thread-history-modal',
|
'#thread-history-modal',
|
||||||
'#thread-reply-modal',
|
'#thread-reply-modal',
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { formatDateTime, getIntlLocale } from '../i18n/format.js';
|
|||||||
import { t, th } from '../i18n/index.js';
|
import { t, th } from '../i18n/index.js';
|
||||||
import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
||||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||||
|
import { openBlockchainDetailsModal } from '../components/blockchain-details-dialog.js';
|
||||||
import { confirmLikeAction, showLikeStatistics } from '../components/like-action-sheet.js';
|
import { confirmLikeAction, showLikeStatistics } from '../components/like-action-sheet.js';
|
||||||
import { iconHtml } from '../components/ui-icon.js';
|
import { iconHtml } from '../components/ui-icon.js';
|
||||||
import { createOverflowDots } from '../components/overflow-dots.js';
|
import { createOverflowDots } from '../components/overflow-dots.js';
|
||||||
@@ -850,56 +851,10 @@ function buildBlockchainDetails({ messageRef, authorLogin, timestampMs, text, ra
|
|||||||
msgSubType: msgSubType ?? source.msgSubType ?? '',
|
msgSubType: msgSubType ?? source.msgSubType ?? '',
|
||||||
createdAtMs: timestampMs || source.createdAtMs || '',
|
createdAtMs: timestampMs || source.createdAtMs || '',
|
||||||
text: String(text || ''),
|
text: String(text || ''),
|
||||||
signature: source.signature || source.blockSignature || source.authorSignature || t('screens.channel_view.text_114'),
|
|
||||||
publicKey: source.publicKey || source.authorPublicKey || t('screens.channel_view.text_115'),
|
|
||||||
raw,
|
raw,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function openBlockchainDetailsModal(details, { isActive = () => true } = {}) {
|
|
||||||
const root = document.getElementById('modal-root');
|
|
||||||
const rawText = JSON.stringify(details.raw || details, null, 2);
|
|
||||||
root.innerHTML = `
|
|
||||||
<div class="modal" id="blockchain-details-modal">
|
|
||||||
<div class="modal-card stack blockchain-details-card">
|
|
||||||
<h3 class="modal-title">${t('dialogs.modals.channel_view.label_011')}</h3>
|
|
||||||
<p class="meta-muted">${t('dialogs.modals.channel_view.label_012')}</p>
|
|
||||||
<div class="blockchain-details-grid">
|
|
||||||
<span>${t('dialogs.modals.channel_view.label_013')}</span><strong>${escapeHtml(details.authorLogin)}</strong>
|
|
||||||
<span>${t('dialogs.modals.channel_view.label_014')}</span><code>${escapeHtml(details.authorBlockchainName)}</code>
|
|
||||||
<span>${t('dialogs.modals.channel_view.label_015')}</span><code>${escapeHtml(details.blockNumber)}</code>
|
|
||||||
<span>${t('dialogs.modals.channel_view.label_016')}</span><code>${escapeHtml(details.blockHash)}</code>
|
|
||||||
<span>${t('dialogs.modals.channel_view.label_017')}</span><code>${escapeHtml(details.msgSubType)}</code>
|
|
||||||
<span>${t('dialogs.modals.channel_view.label_018')}</span><code>${escapeHtml(details.createdAtMs ? formatDateTime(new Date(Number(details.createdAtMs))) : '–')}</code>
|
|
||||||
<span>Public key</span><code>${escapeHtml(details.publicKey)}</code>
|
|
||||||
<span>${t('dialogs.modals.channel_view.label_019')}</span><code>${escapeHtml(details.signature)}</code>
|
|
||||||
</div>
|
|
||||||
<label class="field-label" for="blockchain-details-text">${t('dialogs.modals.channel_view.label_020')}</label>
|
|
||||||
<textarea class="input" id="blockchain-details-text" rows="4" readonly>${escapeHtml(details.text)}</textarea>
|
|
||||||
<pre class="blockchain-raw-block" id="blockchain-raw-block" hidden>${escapeHtml(rawText)}</pre>
|
|
||||||
<div class="form-actions-grid">
|
|
||||||
<button class="secondary-btn" id="blockchain-details-copy" type="button">${t('dialogs.modals.channel_view.label_021')}</button>
|
|
||||||
<button class="secondary-btn" id="blockchain-details-raw" type="button">${t('dialogs.modals.channel_view.label_022')}</button>
|
|
||||||
</div>
|
|
||||||
<button class="secondary-btn" id="blockchain-details-close" type="button">${t('dialogs.modals.channel_view.label_005')}</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
root.querySelector('#blockchain-details-close')?.addEventListener('click', () => {
|
|
||||||
root.innerHTML = '';
|
|
||||||
});
|
|
||||||
root.querySelector('#blockchain-details-copy')?.addEventListener('click', async () => {
|
|
||||||
await copyTextToClipboard(rawText);
|
|
||||||
if (!isActive()) return;
|
|
||||||
showToast(t('dialogs.remaining.pages.channel_view.openblockchaindetailsmodal.dannye_blokcheyna_skopirovany'));
|
|
||||||
});
|
|
||||||
root.querySelector('#blockchain-details-raw')?.addEventListener('click', () => {
|
|
||||||
const rawEl = root.querySelector('#blockchain-raw-block');
|
|
||||||
if (!rawEl) return;
|
|
||||||
rawEl.hidden = !rawEl.hidden;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderDraftAttachments(container, attachments) {
|
function renderDraftAttachments(container, attachments) {
|
||||||
if (!container) return;
|
if (!container) return;
|
||||||
container.innerHTML = '';
|
container.innerHTML = '';
|
||||||
@@ -2259,7 +2214,7 @@ function renderPostCard(post, {
|
|||||||
raw: post.rawMessage,
|
raw: post.rawMessage,
|
||||||
localNumber: post.localNumber,
|
localNumber: post.localNumber,
|
||||||
msgSubType: post.msgSubType,
|
msgSubType: post.msgSubType,
|
||||||
}), { isActive });
|
}), { isActive, authService, solanaEndpoint: state.entrySettings.solanaServer });
|
||||||
});
|
});
|
||||||
menuItems.push({ label: t('screens.channel_view.text_034'), iconHtml: iconHtml('info'), action: () => detailsButton.click() });
|
menuItems.push({ label: t('screens.channel_view.text_034'), iconHtml: iconHtml('info'), action: () => detailsButton.click() });
|
||||||
if (post.isOwnMessage) {
|
if (post.isOwnMessage) {
|
||||||
|
|||||||
@@ -201,3 +201,14 @@ export async function createAns104DataItemWithRawParts({
|
|||||||
data,
|
data,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Проверка исходной подписи ANS-104 локально, без доверия к серверному статусу. */
|
||||||
|
export async function verifyAns104DataItem(rawBytes) {
|
||||||
|
const item = parseAns104DataItem(rawBytes);
|
||||||
|
const signedMessage = await ans104SigningMessageRaw(item);
|
||||||
|
const key = await crypto.subtle.importKey('raw', item.owner32, { name: 'Ed25519' }, false, ['verify']);
|
||||||
|
const signatureValid = await crypto.subtle.verify('Ed25519', key, item.signature, signedMessage);
|
||||||
|
const idHash = await digest('SHA-256', item.signature);
|
||||||
|
const frameHash = await digest('SHA-256', item.data);
|
||||||
|
return { ...item, signatureValid, dataItemIdBytes: idHash, frameHashBytes: frameHash };
|
||||||
|
}
|
||||||
|
|||||||
@@ -7,7 +7,11 @@ import { resolvePublicFileUrl } from './public-file-service.js';
|
|||||||
import { updatedUserFileUrlAfterError } from './user-file-server-service.js';
|
import { updatedUserFileUrlAfterError } from './user-file-server-service.js';
|
||||||
import { validatePublicPiecesRoot } from './public-pieces-root.js';
|
import { validatePublicPiecesRoot } from './public-pieces-root.js';
|
||||||
|
|
||||||
const ATTACH_BLOCK_RE = /^<(?:SHiNE|S):(attach|att);([^>]*)>\n?/u;
|
const ATTACH_BLOCK_RE = /^<(?:SHiNE|S):(attach|att);([^>\n]{1,2048})>\n?/u;
|
||||||
|
// В v=2 ASCII-разделители и управляющие синтаксисом символы экранируются, UTF-8 остаётся как есть.
|
||||||
|
const V2_RESERVED = /[%<>=;\r\n]/g;
|
||||||
|
const V2_ESCAPE = { '%': '%25', '<': '%3C', '>': '%3E', '=': '%3D', ';': '%3B', '\r': '%0D', '\n': '%0A' };
|
||||||
|
const ATTACH_ALLOWED_FIELDS = new Set(['v', 'nm', 'sz', 'pr', 'sha256', 'mm', 'ar']);
|
||||||
export const MAX_MESSAGE_ATTACHMENTS = 10;
|
export const MAX_MESSAGE_ATTACHMENTS = 10;
|
||||||
const RECENT_UNAVAILABLE_MS = 20 * 60 * 1000;
|
const RECENT_UNAVAILABLE_MS = 20 * 60 * 1000;
|
||||||
const IMAGE_EXTENSIONS = new Set(['apng', 'avif', 'bmp', 'gif', 'jpeg', 'jpg', 'png', 'svg', 'webp']);
|
const IMAGE_EXTENSIONS = new Set(['apng', 'avif', 'bmp', 'gif', 'jpeg', 'jpg', 'png', 'svg', 'webp']);
|
||||||
@@ -49,21 +53,22 @@ export function normalizeAttachment(input = {}) {
|
|||||||
const mm = String(input.mm || '').trim();
|
const mm = String(input.mm || '').trim();
|
||||||
const size = Number(input.sz || input.size || input.sizeBytes || 0);
|
const size = Number(input.sz || input.size || input.sizeBytes || 0);
|
||||||
const name = normalizeName(input.nm || input.name || input.fileName || 'file');
|
const name = normalizeName(input.nm || input.name || input.fileName || 'file');
|
||||||
|
if (new TextEncoder().encode(name).length > 255) throw new Error('Имя файла превышает 255 байт UTF-8');
|
||||||
if (txId && !validateArweaveTxId(txId)) throw new Error(t('remaining.attachment_errors.invalid_arweave_transaction_id'));
|
if (txId && !validateArweaveTxId(txId)) throw new Error(t('remaining.attachment_errors.invalid_arweave_transaction_id'));
|
||||||
if (!validatePublicPiecesRoot(pr) && !validateSha256Hex(sha256Hex)) throw new Error('Некорректный идентификатор файла');
|
if (!validatePublicPiecesRoot(pr) && !validateSha256Hex(sha256Hex)) throw new Error('Некорректный идентификатор файла');
|
||||||
if (pr && !validatePublicPiecesRoot(pr)) throw new Error('Некорректный Pieces Root');
|
if (pr && !validatePublicPiecesRoot(pr)) throw new Error('Некорректный Pieces Root');
|
||||||
if (mm && (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i.test(mm) || mm.length > 127)) throw new Error('Некорректный MIME');
|
if (mm && (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i.test(mm) || mm.length > 127)) throw new Error('Некорректный MIME');
|
||||||
if (!Number.isInteger(size) || size <= 0) throw new Error(t('remaining.attachment_errors.invalid_file_size'));
|
if (!Number.isInteger(size) || size <= 0) throw new Error(t('remaining.attachment_errors.invalid_file_size'));
|
||||||
return { v: 1, name, size, sha256: sha256Hex, pr, mm, ar: txId, uploadedAtMs: Number(input.uploadedAtMs || 0) || Date.now() };
|
return { v: 2, name, size, sha256: sha256Hex, pr, mm, ar: txId, uploadedAtMs: Number(input.uploadedAtMs || 0) || Date.now() };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildAttachmentBlock(attachment) {
|
export function buildAttachmentBlock(attachment) {
|
||||||
const item = normalizeAttachment(attachment);
|
const item = normalizeAttachment(attachment);
|
||||||
const encodedName = encodeURIComponent(item.name);
|
const encodedName = item.name.replace(V2_RESERVED, (char) => V2_ESCAPE[char]);
|
||||||
const id = item.pr ? `;pr=${item.pr}` : `;sha256=${item.sha256}`;
|
const id = item.pr ? `;pr=${item.pr}` : `;sha256=${item.sha256}`;
|
||||||
const mmPart = item.mm ? `;mm=${item.mm}` : '';
|
const mmPart = item.mm ? `;mm=${item.mm}` : '';
|
||||||
const arPart = item.ar ? `;ar=${item.ar}` : '';
|
const arPart = item.ar ? `;ar=${item.ar}` : '';
|
||||||
return `<S:att;v=1;nm=${encodedName};sz=${item.size}${id}${mmPart}${arPart}>`;
|
return `<S:att;v=2;nm=${encodedName};sz=${item.size}${id}${mmPart}${arPart}>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function composeMessageWithAttachments(text, attachments = []) {
|
export function composeMessageWithAttachments(text, attachments = []) {
|
||||||
@@ -76,15 +81,33 @@ export function composeMessageWithAttachments(text, attachments = []) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function parseFields(rawFields) {
|
function parseFields(rawFields) {
|
||||||
const out = {};
|
const parts = String(rawFields || '').split(';');
|
||||||
String(rawFields || '').split(';').forEach((part) => {
|
const fields = Object.create(null);
|
||||||
|
// Для v=1 сохраняем прежний мягкий разбор. Для v=2 — строгое правило полей.
|
||||||
|
const strict = parts.some((part) => /^v\s*=\s*(?:0*2)$/u.test(part));
|
||||||
|
for (const part of parts) {
|
||||||
const eq = part.indexOf('=');
|
const eq = part.indexOf('=');
|
||||||
if (eq <= 0) return;
|
if (eq <= 0) {
|
||||||
|
if (strict) throw new Error('Некорректное поле вложения');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
const key = part.slice(0, eq).trim();
|
const key = part.slice(0, eq).trim();
|
||||||
const value = part.slice(eq + 1).trim();
|
const value = part.slice(eq + 1).trim();
|
||||||
if (key) out[key] = value;
|
if (strict && (!ATTACH_ALLOWED_FIELDS.has(key) || Object.hasOwn(fields, key))) {
|
||||||
});
|
throw new Error('Дублированное либо неизвестное поле вложения');
|
||||||
return out;
|
}
|
||||||
|
if (key) fields[key] = value;
|
||||||
|
}
|
||||||
|
if (strict) {
|
||||||
|
if (!fields.nm || !fields.sz || !(fields.pr || fields.sha256) || (fields.pr && fields.sha256)) {
|
||||||
|
throw new Error('Отсутствует обязательное поле вложения');
|
||||||
|
}
|
||||||
|
if (!/^(?:[^%]|%(?:25|3[bBcCdDeE]|0[aAdD]))*$/u.test(fields.nm)) {
|
||||||
|
// Неизвестные и неполные %-коды запрещаем; это исключает неоднозначное толкование.
|
||||||
|
throw new Error('Неканоническое экранирование имени файла');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fields;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function parseMessageAttachments(rawText) {
|
export function parseMessageAttachments(rawText) {
|
||||||
@@ -94,14 +117,20 @@ export function parseMessageAttachments(rawText) {
|
|||||||
while (true) {
|
while (true) {
|
||||||
const match = rest.match(ATTACH_BLOCK_RE);
|
const match = rest.match(ATTACH_BLOCK_RE);
|
||||||
if (!match) break;
|
if (!match) break;
|
||||||
const fields = parseFields(match[2]);
|
|
||||||
try {
|
try {
|
||||||
|
const fields = parseFields(match[2]);
|
||||||
const version = Number(fields.v || 0);
|
const version = Number(fields.v || 0);
|
||||||
if (version !== 1 && version !== 2) {
|
if (version !== 1 && version !== 2) {
|
||||||
throw new Error('unsupported attachment version');
|
throw new Error('unsupported attachment version');
|
||||||
}
|
}
|
||||||
|
if (version === 2 && (!fields.v || fields.v !== '2')) throw new Error('Неканоническая версия');
|
||||||
|
if (version === 2 && (/[<>=;]/u.test(fields.nm) || !/^[1-9][0-9]*$/u.test(fields.sz))) {
|
||||||
|
throw new Error('Неканонические поля вложения');
|
||||||
|
}
|
||||||
|
const name = decodeURIComponent(String(fields.nm || fields.name || 'file'));
|
||||||
|
if (version === 2 && /[\u0000-\u001f\u007f]/u.test(name)) throw new Error('Управляющий символ в имени файла');
|
||||||
attachments.push(normalizeAttachment({
|
attachments.push(normalizeAttachment({
|
||||||
nm: decodeURIComponent(String(fields.nm || fields.name || 'file')),
|
nm: name,
|
||||||
sz: fields.sz || fields.size,
|
sz: fields.sz || fields.size,
|
||||||
sha256: fields.sha256,
|
sha256: fields.sha256,
|
||||||
pr: fields.pr,
|
pr: fields.pr,
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import { verifyAns104DataItem } from './ans104-data-item.js';
|
||||||
|
import { base64ToBytes, bytesToBase64Url } from './crypto-utils.js';
|
||||||
|
import { readShineUserPda } from './shine-user-pda-service.js';
|
||||||
|
|
||||||
|
const HASH_RE = /^[0-9a-f]{64}$/iu;
|
||||||
|
const DATA_ITEM_ID_RE = /^[A-Za-z0-9_-]{43}$/u;
|
||||||
|
const MAX_SIGNED_BYTES = 8 * 1024 * 1024;
|
||||||
|
|
||||||
|
function hex(bytes) {
|
||||||
|
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
||||||
|
}
|
||||||
|
function equalBytes(left, right) {
|
||||||
|
return left.length === right.length && left.every((byte, index) => byte === right[index]);
|
||||||
|
}
|
||||||
|
export function arweaveBlockUrl(id) {
|
||||||
|
return DATA_ITEM_ID_RE.test(String(id || '')) ? `https://arweave.net/raw/${id}` : '';
|
||||||
|
}
|
||||||
|
export function signedDataItemFilename(chain, number) {
|
||||||
|
const safe = String(chain || 'block').replace(/[^a-z0-9@._-]/giu, '_').slice(0, 100);
|
||||||
|
return `SHiNE-${safe}-${Number(number)}.ans104`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Получаем полный оригинал по существующему публичному API (не «от Arweave»). */
|
||||||
|
export async function readSignedBlock({ authService, blockchainName, blockNumber, blockHash, dataItemId }) {
|
||||||
|
const resp = await authService.ws.request('GetBlockchainBlock', { blockchainName, blockNumber });
|
||||||
|
if (Number(resp?.status) !== 200) throw new Error('GetBlockchainBlock: блок недоступен');
|
||||||
|
const body = resp?.payload || resp;
|
||||||
|
if (!HASH_RE.test(String(body?.blockHash || '')) || String(body.blockHash).toLowerCase() !== String(blockHash).toLowerCase()) {
|
||||||
|
throw new Error('Сервер вернул другой хеш блока');
|
||||||
|
}
|
||||||
|
const rawText = String(body?.blockBytesB64 || '');
|
||||||
|
if (rawText.length > Math.ceil(MAX_SIGNED_BYTES * 4 / 3) + 8) throw new Error('Размер подписанного блока превышает лимит');
|
||||||
|
const bytes = base64ToBytes(rawText);
|
||||||
|
if (!bytes.length || bytes.length > MAX_SIGNED_BYTES) throw new Error('Некорректный размер блока');
|
||||||
|
const proof = await verifyAns104DataItem(bytes);
|
||||||
|
if (!proof.signatureValid) throw new Error('Недействительная подпись ANS-104');
|
||||||
|
if (hex(proof.frameHashBytes) !== String(blockHash).toLowerCase()) throw new Error('Хеш содержимого блока не совпал');
|
||||||
|
const actualId = bytesToBase64Url(proof.dataItemIdBytes);
|
||||||
|
if (dataItemId && actualId !== dataItemId) throw new Error('Идентификатор Arweave отличается от ожидаемого');
|
||||||
|
return { bytes, ...proof, actualId };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Вспомогательная независимая сверка: шлюз возвращает payload, а не ANS-104 оболочку. */
|
||||||
|
export async function checkArweavePayload(dataItemId, signedPayload) {
|
||||||
|
const url = arweaveBlockUrl(dataItemId);
|
||||||
|
if (!url) return { status: 'unavailable', reason: 'Нет идентификатора Arweave' };
|
||||||
|
try {
|
||||||
|
const response = await fetch(url, { cache: 'no-store', signal: AbortSignal.timeout(15000) });
|
||||||
|
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||||
|
const length = Number(response.headers.get('Content-Length') || 0);
|
||||||
|
if (length > MAX_SIGNED_BYTES) throw new Error('Слишком большой ответ шлюза');
|
||||||
|
const raw = new Uint8Array(await response.arrayBuffer());
|
||||||
|
if (raw.length > MAX_SIGNED_BYTES) throw new Error('Слишком большой ответ шлюза');
|
||||||
|
return equalBytes(raw, signedPayload)
|
||||||
|
? { status: 'valid' }
|
||||||
|
: { status: 'invalid', reason: 'Содержимое Arweave не совпадает с подписанным блоком' };
|
||||||
|
} catch (error) {
|
||||||
|
return { status: 'unavailable', reason: String(error?.message || error) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function checkSolanaAuthor({ authorLogin, blockchainName, owner32, solanaEndpoint }) {
|
||||||
|
const forkMatch = String(blockchainName || '').match(/-(\d{3})$/u);
|
||||||
|
const forkIndex = forkMatch ? Number(forkMatch[1]) - 1 : -1;
|
||||||
|
if (forkIndex < 0 || !authorLogin || !solanaEndpoint) {
|
||||||
|
return { status: 'unavailable', reason: 'Недостаточно данных для проверки Solana' };
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const pda = await readShineUserPda({ login: authorLogin, solanaEndpoint });
|
||||||
|
const key = pda?.forks?.[forkIndex]?.blockchainKey;
|
||||||
|
if (!key) return { status: 'unavailable', reason: 'Исторический ключ форка отсутствует в PDA' };
|
||||||
|
return equalBytes(new Uint8Array(key), owner32)
|
||||||
|
? { status: 'valid', reason: `Solana PDA, форк ${forkMatch[1]}` }
|
||||||
|
: { status: 'invalid', reason: 'Ключ подписанта не совпадает с ключом форка в Solana PDA' };
|
||||||
|
} catch (error) {
|
||||||
|
// FREE_CERT может не иметь PDA: это не доказательство подделки.
|
||||||
|
return { status: 'unavailable', reason: String(error?.message || error) };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -150,3 +150,43 @@
|
|||||||
/* Число лайков отдельно от действия: нажатие открывает статистику, а не меняет лайк. */
|
/* Число лайков отдельно от действия: нажатие открывает статистику, а не меняет лайк. */
|
||||||
.channel-action-like-stats { min-width: 28px; padding-inline: 4px; font-variant-numeric: tabular-nums; text-decoration: underline dotted; text-underline-offset: 3px; }
|
.channel-action-like-stats { min-width: 28px; padding-inline: 4px; font-variant-numeric: tabular-nums; text-decoration: underline dotted; text-underline-offset: 3px; }
|
||||||
.channel-message-card--owner .channel-action-like-stats { width: auto; min-width: 28px; padding-inline: 4px; }
|
.channel-message-card--owner .channel-action-like-stats { width: auto; min-width: 28px; padding-inline: 4px; }
|
||||||
|
|
||||||
|
/* Данные и проверка блока: единый диалог ленты и обсуждения. */
|
||||||
|
.block-proof-card { width: min(100%, 540px); max-height: min(90dvh, 920px); overflow-y: auto; gap: 14px; }
|
||||||
|
.block-proof-header { display: flex; align-items: center; gap: 14px; }
|
||||||
|
.block-proof-header .modal-title { margin: 0 0 4px; }
|
||||||
|
.block-proof-header .meta-muted { margin: 0; line-height: 1.4; }
|
||||||
|
.block-proof-icon { display: grid; place-items: center; width: 46px; height: 46px; flex: none; border-radius: 14px; color: var(--accent); background: color-mix(in srgb, var(--accent) 12%, var(--surface)); font-size: 1.4rem; }
|
||||||
|
.block-proof-facts { display: grid; border: 1px solid var(--border-subtle); border-radius: 14px; overflow: hidden; }
|
||||||
|
.block-proof-row { display: flex; justify-content: space-between; gap: 12px; align-items: center; padding: 10px 12px; font-size: .85rem; }
|
||||||
|
.block-proof-row + .block-proof-row { border-top: 1px solid var(--border-subtle); }
|
||||||
|
.block-proof-row > span, .block-proof-hash > span { color: var(--text-secondary); }
|
||||||
|
.block-proof-row > strong, .block-proof-row > code { text-align: right; overflow-wrap: anywhere; min-width: 0; font-size: inherit; font-weight: 600; }
|
||||||
|
.block-proof-status { display: inline-flex; width: fit-content; align-items: center; gap: 8px; padding: 6px 10px; border-radius: 20px; border: 1px solid var(--border-subtle); font-size: .8rem; font-weight: 600; }
|
||||||
|
.block-proof-status--success { color: #228b66; }
|
||||||
|
.block-proof-status--pending { color: #b47a1a; }
|
||||||
|
.block-proof-status--unknown { color: var(--text-secondary); }
|
||||||
|
.block-proof-dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
|
||||||
|
.block-proof-hash { display: flex; flex-direction: column; gap: 5px; padding: 10px 12px; border: 1px solid var(--border-subtle); border-radius: 12px; font-size: .8rem; }
|
||||||
|
.block-proof-hash > div { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||||
|
.block-proof-hash code { font-size: .84rem; overflow-wrap: anywhere; }
|
||||||
|
.block-proof-copy-icon { flex: none; min-width: 34px; min-height: 34px; border: 1px solid var(--border-subtle); background: var(--surface); border-radius: 10px; color: var(--text-secondary); cursor: pointer; }
|
||||||
|
.block-proof-actions { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
|
||||||
|
.block-proof-actions .secondary-btn { min-width: 0; padding: 10px 9px; text-align: center; font-size: .82rem; }
|
||||||
|
.block-proof-actions .block-proof-link { display: flex; justify-content: center; align-items: center; text-decoration: none; }
|
||||||
|
.block-proof-actions .block-proof-link[hidden] { display: none; }
|
||||||
|
.block-proof-actions .block-proof-verify { grid-column: 1 / -1; }
|
||||||
|
.block-proof-results { display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
.block-proof-results[hidden] { display: none; }
|
||||||
|
.block-proof-check { display: flex; gap: 10px; align-items: flex-start; padding: 9px 11px; border-radius: 10px; border: 1px solid var(--border-subtle); font-size: .82rem; }
|
||||||
|
.block-proof-check > span { font-weight: 800; font-size: 1rem; }
|
||||||
|
.block-proof-check--valid > span { color: #228b66; }
|
||||||
|
.block-proof-check--invalid > span { color: var(--danger); }
|
||||||
|
.block-proof-check > div { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
|
||||||
|
.block-proof-check small { overflow-wrap: anywhere; color: var(--text-secondary); }
|
||||||
|
.block-proof-raw { border-top: 1px solid var(--border-subtle); padding-top: 10px; }
|
||||||
|
.block-proof-raw summary { cursor: pointer; color: var(--text-secondary); font-size: .83rem; }
|
||||||
|
.block-proof-raw pre { margin: 10px 0; font-size: .72rem; }
|
||||||
|
@media (max-width: 380px) { .block-proof-actions { grid-template-columns: 1fr; } .block-proof-actions .block-proof-verify { grid-column: auto; } }
|
||||||
|
|
||||||
|
.block-proof-warning { margin: 0; padding: 8px 12px; border: 1px solid var(--danger); border-radius: 10px; font-size: .8rem; }
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { buildAttachmentBlock, parseMessageAttachments } from '../js/services/attachment-format.js';
|
||||||
|
|
||||||
|
const root = '4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi';
|
||||||
|
const source = (name) => ({ name, size: 1837243, pr: root, mm: 'video/mp4' });
|
||||||
|
test('v2: UTF-8 имена без лишних %-кодов', () => {
|
||||||
|
const marker = buildAttachmentBlock(source('Водопад.mp4'));
|
||||||
|
assert.match(marker, /^<S:att;v=2;nm=Водопад.mp4;sz=1837243;/u);
|
||||||
|
assert.equal(parseMessageAttachments(`${marker}\nцук`).attachments[0].name, 'Водопад.mp4');
|
||||||
|
assert.equal(parseMessageAttachments(`${marker}\nцук`).text, 'цук');
|
||||||
|
});
|
||||||
|
test('v2: только служебные символы экранируются; круговой обмен', () => {
|
||||||
|
for (const name of ['Лето;фильм=1%.mp4', 'Привет<мир>.mp4', '中文;عربي=тест%.mp4']) {
|
||||||
|
const marker = buildAttachmentBlock(source(name));
|
||||||
|
assert.equal(parseMessageAttachments(marker).attachments[0].name, name);
|
||||||
|
assert.equal(marker.includes('nm='+encodeURIComponent(name)), false);
|
||||||
|
assert.doesNotMatch(marker, /nm=[^;]*;фильм/u);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
test('v1: прежние URI-имена остаются читаемыми', () => {
|
||||||
|
const name = 'Водопад.mp4';
|
||||||
|
const marker = `<S:att;v=1;nm=${encodeURIComponent(name)};sz=10;pr=${root};mm=video/mp4>`;
|
||||||
|
assert.equal(parseMessageAttachments(marker).attachments[0].name, name);
|
||||||
|
});
|
||||||
|
test('v2: дубликаты, неизвестные поля и плохие escape не интерпретируются как вложение', () => {
|
||||||
|
for (const body of [
|
||||||
|
`v=2;nm=a;sz=10;sz=500;pr=${root}`,
|
||||||
|
`v=2;nm=foo;bad=value;sz=10;pr=${root}`,
|
||||||
|
`v=2;nm=abc%zz;sz=10;pr=${root}`,
|
||||||
|
`v=2;nm=abc%3;sz=10;pr=${root}`,
|
||||||
|
`v=2;nm=abc%0Aevil;sz=10;pr=${root}`,
|
||||||
|
`v=2;nm=abc;sz=-1;pr=${root}`,
|
||||||
|
`v=2;nm=abc;sz=01;pr=${root}`,
|
||||||
|
`v=2;nm=abc<b;sz=10;pr=${root}`,
|
||||||
|
`v=2;nm=abc=d;sz=10;pr=${root}`,
|
||||||
|
`v=2;nm=abc;sz=10;pr=${root};ar=wrong-id`,
|
||||||
|
]) {
|
||||||
|
assert.equal(parseMessageAttachments(`<S:att;${body}>`).attachments.length, 0, body);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { readFile } from 'node:fs/promises';
|
||||||
|
import { verifyAns104DataItem } from '../js/services/ans104-data-item.js';
|
||||||
|
import { arweaveBlockUrl, readSignedBlock } from '../js/services/blockchain-proof-service.js';
|
||||||
|
import { bytesToBase64Url } from '../js/services/crypto-utils.js';
|
||||||
|
import { webcrypto } from 'node:crypto';
|
||||||
|
|
||||||
|
if (!globalThis.crypto?.subtle) globalThis.crypto = webcrypto;
|
||||||
|
// Изолированный эталон ANS104 (файл взят из текущего тестового блока проекта).
|
||||||
|
const signedPath = new URL('./fixtures/block11.ans104', import.meta.url);
|
||||||
|
const expectedHash = '46db963eab3e9a9aeddba0b67bb2c44daf3be3472706c25a8035ad4ae914e99f';
|
||||||
|
const expectedId = 'T0dcFEjRymardqVuTEU5HdkPjkKm8ALU7nyf6LOzCXE';
|
||||||
|
test('подпись Ed25519 полного DataItem и SHA-256 полезного блока', async () => {
|
||||||
|
const bytes = new Uint8Array(await readFile(signedPath));
|
||||||
|
const proof = await verifyAns104DataItem(bytes);
|
||||||
|
assert.equal(bytes.length, 412);
|
||||||
|
assert.equal(proof.data.length, 274);
|
||||||
|
assert.equal(proof.signatureValid, true);
|
||||||
|
assert.equal(bytesToBase64Url(proof.dataItemIdBytes), expectedId);
|
||||||
|
assert.equal(Buffer.from(proof.frameHashBytes).toString('hex'), expectedHash);
|
||||||
|
});
|
||||||
|
test('подмена payload не проходит проверку подписи и SHA-256', async () => {
|
||||||
|
const bytes = new Uint8Array(await readFile(signedPath));
|
||||||
|
bytes[bytes.length - 1] ^= 0x01;
|
||||||
|
const proof = await verifyAns104DataItem(bytes);
|
||||||
|
assert.equal(proof.signatureValid, false);
|
||||||
|
assert.notEqual(Buffer.from(proof.frameHashBytes).toString('hex'), expectedHash);
|
||||||
|
});
|
||||||
|
test('по API нельзя скачать DataItem с подменённым хешем или ID', async () => {
|
||||||
|
const bytes = new Uint8Array(await readFile(signedPath));
|
||||||
|
const authService = { ws: { request: async () => ({ status: 200, payload: {
|
||||||
|
blockHash: expectedHash, blockBytesB64: Buffer.from(bytes).toString('base64'),
|
||||||
|
} }) } };
|
||||||
|
assert.equal((await readSignedBlock({authService, blockchainName:'wwwww@shine-001',blockNumber:11,blockHash:expectedHash,dataItemId:expectedId})).bytes.length, 412);
|
||||||
|
await assert.rejects(readSignedBlock({authService, blockchainName:'wwwww@shine-001',blockNumber:11,blockHash:expectedHash,dataItemId:'A'.repeat(43)}), /Arweave/);
|
||||||
|
assert.equal(arweaveBlockUrl('../evil'), '');
|
||||||
|
});
|
||||||
BIN
Binary file not shown.
Reference in New Issue
Block a user