Compare commits

..
107 changed files with 3194 additions and 684 deletions
@@ -10,6 +10,7 @@ import org.slf4j.LoggerFactory;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
import server.sync.BlockchainResyncGuard;
import shine.db.DbController;
import shine.db.KeyEncodingUtil;
import utils.config.AppConfig;
import shine.db.dao.ArweaveBlockImportDAO;
import shine.db.dao.BlockchainStateDAO;
@@ -19,6 +20,7 @@ import shine.db.dao.CanonicalChainResolver;
import shine.db.dao.ChannelReadStateDAO;
import shine.db.dao.BlockchainResyncCleanupDAO;
import shine.db.dao.SolanaUserPdaCurrentDAO;
import shine.db.dao.RegistrationIdentityDAO;
import shine.db.entities.BlockchainStateEntry;
import shine.db.entities.SolanaUserPdaCurrentEntry;
@@ -225,7 +227,7 @@ public final class ArweaveBlockSyncService {
if (pending.isEmpty()) break;
for (ArweaveBlockImportDAO.QueueItem q : pending) {
if (q.parsedLogin() == null || q.parsedForkNumber() == null || q.parsedBlockNumber() == null) continue;
SolanaUserPdaCurrentEntry activeUser = usersDAO.getByLogin(q.parsedLogin());
SolanaUserPdaCurrentEntry activeUser = resolveChainOwnerByLogin(q.parsedLogin());
if (activeUser == null || activeUser.getBlockchainName() == null || activeUser.getBlockchainName().isBlank()) {
importDAO.setPendingError(q.dataItemId(), "active_user_missing", System.currentTimeMillis());
continue;
@@ -257,7 +259,7 @@ public final class ArweaveBlockSyncService {
progress = true;
continue;
}
SolanaUserPdaCurrentEntry physicalUser = usersDAO.getByBlockchainKey(item.owner32());
SolanaUserPdaCurrentEntry physicalUser = resolveChainOwnerByBlockchainKey(item.owner32());
if (physicalUser == null || physicalUser.getBlockchainName() == null
|| !q.parsedLogin().equalsIgnoreCase(physicalUser.getLogin())
|| forkOf(physicalUser.getBlockchainName()) != q.parsedForkNumber()) {
@@ -335,7 +337,7 @@ public final class ArweaveBlockSyncService {
if (!item.verifySignature()) throw new IllegalArgumentException("bad ANS-104 signature");
BchBlockEntry b = new BchBlockEntry(raw);
SolanaUserPdaCurrentEntry owner = usersDAO.getByBlockchainKey(item.owner32());
SolanaUserPdaCurrentEntry owner = resolveChainOwnerByBlockchainKey(item.owner32());
if (owner == null || owner.getBlockchainName() == null || owner.getLogin() == null) {
importDAO.setPendingError(id, "unknown_owner", System.currentTimeMillis());
continue;
@@ -352,7 +354,7 @@ public final class ArweaveBlockSyncService {
if (fork <= 1) throw new IllegalArgumentException("TECH_FORK cannot belong to fork1");
if (b.blockNumber != fb.forkPointBlockNumber + 1)
throw new IllegalArgumentException("TECH_FORK block number/fork point mismatch");
SolanaUserPdaCurrentEntry parent = usersDAO.getByBlockchainKey(fb.parentBlockchainKey32);
SolanaUserPdaCurrentEntry parent = resolveChainOwnerByBlockchainKey(fb.parentBlockchainKey32);
if (parent == null || parent.getBlockchainName() == null
|| !owner.getLogin().equalsIgnoreCase(parent.getLogin()))
throw new IllegalArgumentException("TECH_FORK parent owner mismatch");
@@ -388,9 +390,64 @@ public final class ArweaveBlockSyncService {
}
}
/**
* Обычный пользователь подтверждается текущим Solana PDA. У бесплатной регистрации PDA
* намеренно отсутствует: её проверяемая идентичность хранится в сертификате. Для обеих
* моделей импортёр должен сопоставить ANS-104 owner с уже проверенной локальной записью,
* иначе блоки FREE_CERT никогда не смогут попасть на другой сервер.
*/
private SolanaUserPdaCurrentEntry resolveChainOwnerByLogin(String login) throws SQLException {
SolanaUserPdaCurrentEntry solana = usersDAO.getByLogin(login);
if (solana != null) return solana;
RegistrationIdentityDAO.ResolvedIdentity identity = RegistrationIdentityDAO.getInstance().get(login);
if (identity == null || !identity.isFree() || identity.blockchainKey() == null || identity.blockchainKey().isBlank()) {
return null;
}
return freeCertificateOwner(identity.fullLogin(), identity.blockchainKey());
}
private SolanaUserPdaCurrentEntry resolveChainOwnerByBlockchainKey(byte[] owner32) throws SQLException {
SolanaUserPdaCurrentEntry solana = usersDAO.getByBlockchainKey(owner32);
if (solana != null) return solana;
if (owner32 == null || owner32.length != 32) return null;
String blockchainKey = KeyEncodingUtil.encodeBase58(owner32);
try (Connection c = DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement("""
SELECT login, blockchain_key
FROM user_identity_current
WHERE registration_status='FREE_CERT' AND blockchain_key=?
LIMIT 1
""")) {
ps.setString(1, blockchainKey);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? freeCertificateOwner(rs.getString("login"), rs.getString("blockchain_key")) : null;
}
}
}
private SolanaUserPdaCurrentEntry resolveChainOwnerByBlockchainName(String blockchainName) throws SQLException {
SolanaUserPdaCurrentEntry solana = usersDAO.getByBlockchainName(blockchainName);
if (solana != null) return solana;
if (blockchainName == null || !blockchainName.endsWith("-001")) return null;
String login = blockchainName.substring(0, blockchainName.length() - 4);
SolanaUserPdaCurrentEntry free = resolveChainOwnerByLogin(login);
return free != null && blockchainName.equalsIgnoreCase(free.getBlockchainName()) ? free : null;
}
private static SolanaUserPdaCurrentEntry freeCertificateOwner(String login, String blockchainKey) {
SolanaUserPdaCurrentEntry owner = new SolanaUserPdaCurrentEntry();
owner.setLogin(login);
owner.setBlockchainName(login.toLowerCase(Locale.ROOT) + "-001");
owner.setBlockchainKey(KeyEncodingUtil.base58KeyToBase64_32(blockchainKey));
owner.setPaidLimitBytes(0L);
return owner;
}
private void ensureState(SolanaUserPdaCurrentEntry user, BchBlockEntry firstSeen) throws Exception {
int fork=forkOf(user.getBlockchainName()); BlockchainStateEntry s=new BlockchainStateEntry();
s.setBlockchainName(user.getBlockchainName());s.setLogin(user.getLogin());s.setBlockchainKey(user.getBlockchainKey());s.setSizeLimit(user.getPaidLimitBytes()>0?user.getPaidLimitBytes():100_000L);s.setFileSizeBytes(0L);
s.setBlockchainName(user.getBlockchainName());s.setLogin(user.getLogin());s.setBlockchainKey(user.getBlockchainKey());s.setSizeLimit(user.getPaidLimitBytes());s.setFileSizeBytes(0L);
BlockchainForkSegmentsDAO.Segment seg=segmentsDAO.get(user.getLogin(),fork);
BlockchainStateEntry existing=stateDAO.getByBlockchainName(user.getBlockchainName());
if(existing!=null && (seg==null || seg.parentForkNumber()==null || existing.getLastBlockNumber()>=seg.forkPointBlockNumber()))return;
@@ -414,7 +471,7 @@ public final class ArweaveBlockSyncService {
while(rs.next())logins.add(rs.getString(1));
}
for(String login:logins){
SolanaUserPdaCurrentEntry u=usersDAO.getByLogin(login);
SolanaUserPdaCurrentEntry u=resolveChainOwnerByLogin(login);
if(u==null||u.getBlockchainName()==null)continue;
replayDurableCanonicalStaging(login,forkOf(u.getBlockchainName()));
}
@@ -477,17 +534,17 @@ public final class ArweaveBlockSyncService {
if(last<0)throw new IllegalStateException("canonical staging is empty for "+login);
}
private void replayDurableCanonicalStaging(String login,int activeFork)throws Exception{
SolanaUserPdaCurrentEntry u=usersDAO.getByLogin(login);if(u==null)throw new IllegalStateException("user missing for canonical rebuild: "+login);
SolanaUserPdaCurrentEntry u=resolveChainOwnerByLogin(login);if(u==null)throw new IllegalStateException("user missing for canonical rebuild: "+login);
String activeName=u.getBlockchainName();boolean guard=BlockchainResyncGuard.tryBegin(activeName);if(!guard)throw new IllegalStateException("canonical rebuild already active: "+login);
try{
validateGenericStaging(login);
cleanupDAO.cleanupLoginForCanonicalReplay(login);
long limit=u.getPaidLimitBytes()>0?u.getPaidLimitBytes():100_000L,cumulative=0;int currentFork=-1,prevNumber=-1;byte[] prevHash=null;
long cumulative=0;int currentFork=-1,prevNumber=-1;byte[] prevHash=null;
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,physical_fork_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
int n=rs.getInt(1),f=rs.getInt(2);byte[] raw=rs.getBytes(3),hash=rs.getBytes(4);BchBlockEntry b=new BchBlockEntry(raw);
String bch=login+"-"+String.format("%03d",f);
if(f!=currentFork){BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
if(f!=currentFork){SolanaUserPdaCurrentEntry forkOwner=resolveChainOwnerByBlockchainName(bch);long limit=forkOwner==null?0L:forkOwner.getPaidLimitBytes();BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
Net_AddBlock_Handler.ArweaveImportResult r=addBlock.addBlockFromReplay(bch,raw);if(!r.ok())throw new IllegalStateException("canonical Arweave rebuild rejected #"+n+": "+r.reasonCode());
cumulative+=raw.length;prevNumber=n;prevHash=hash;
}}
@@ -33,7 +33,9 @@ public final class FreeRegistrationApiBootstrap {
FreeRegistrationPublisher publisher=null;
RegistrationEmailSender emailSender=null;
AllowedEmailDomains allowedEmailDomains=null;
if (cfg.getBoolean("freeRegistration.enabled",false)) {
String freeNamespace=cfg.getStringOrEmpty("freeRegistration.namespace").trim();
boolean freeRegistrationEnabled=cfg.getBoolean("freeRegistration.enabled",false) && !freeNamespace.isEmpty();
if (freeRegistrationEnabled) {
String domainsFile = cfg.getStringOrEmpty("freeRegistration.email.allowedDomainsFile");
if (domainsFile.isBlank()) domainsFile = "allowed-email-domains.txt";
// Относительный путь — от WorkingDirectory процесса Java.
@@ -44,6 +46,8 @@ public final class FreeRegistrationApiBootstrap {
if(transport.publishMode()!=ArweaveBlocksConfig.PublishMode.TURBO)
throw new IllegalStateException("Free registration requires Turbo transport");
newSigner=LocalRegistrarSigner.fromConfig(cfg);
FreeRegistrationIssuer.validateConfiguredNamespace(dbSource(), newSigner, freeNamespace,
cfg.getStringOrEmpty("server.SHiNE.login"));
issuer=new FreeRegistrationIssuer(dbSource(),newSigner,allowEmailReuse);
publisher=new FreeRegistrationPublisher(issuer,new TurboDataItemUploader(transport),
new VerifiedFreeRegistrationImporter(allowEmailReuse));
@@ -58,7 +62,8 @@ public final class FreeRegistrationApiBootstrap {
}
FreeRegistrationWorkflow newWorkflow=new FreeRegistrationWorkflow(issuer,publisher,emailSender,
cfg.getBoolean("freeRegistration.email.allowTestCode",false),
cfg.getBoolean("freeRegistration.email.allowReuse",false), allowedEmailDomains);
cfg.getBoolean("freeRegistration.email.allowReuse",false), allowedEmailDomains,
freeRegistrationEnabled ? freeNamespace : "");
RegistrationApiBridge.install((op,req)->dispatch(newWorkflow,op,req));
signer=newSigner; workflow=newWorkflow;
}
@@ -24,6 +24,30 @@ public final class FreeRegistrationIssuer {
this.allowEmailReuse = allowEmailReuse;
}
/** Проверяет привязку локального ключа и сервера до открытия бесплатной регистрации. */
static void validateConfiguredNamespace(DataSource db, RegistrarSigner signer, String namespace,
String localServerLogin) throws Exception {
if (localServerLogin == null || localServerLogin.isBlank())
throw new IllegalStateException("server.SHiNE.login is required for free registration");
try (Connection conn = db.getConnection();
PreparedStatement statement = conn.prepareStatement("""
SELECT namespace_type, registrar_pubkey, default_server_login
FROM shine_namespace_current WHERE namespace = ?
""")) {
statement.setString(1, namespace);
try (ResultSet rs = statement.executeQuery()) {
if (!rs.next() || rs.getInt("namespace_type") != 2)
throw new IllegalStateException("Configured free registration namespace is unavailable");
byte[] namespaceKey = Base58Util.decode(rs.getString("registrar_pubkey"));
if (!Arrays.equals(namespaceKey, signer.publicKey32()))
throw new IllegalStateException("Registrar public key does not match configured namespace");
String namespaceServer = rs.getString("default_server_login");
if (namespaceServer == null || !namespaceServer.equalsIgnoreCase(localServerLogin.trim()))
throw new IllegalStateException("Configured free namespace belongs to another access server");
}
}
}
/** Выдаётся только после успешной проверки challenge в FreeRegistrationWorkflow. */
synchronized byte[] issue(String fullLogin, byte[] root32, byte[] blockchain32,
byte[] client32, String email) throws Exception {
@@ -51,10 +51,12 @@ public final class FreeRegistrationWorkflow {
private final boolean allowTestCode;
private final boolean allowEmailReuse;
private final AllowedEmailDomains allowedEmailDomains;
/** Единственный type-2 namespace, для которого этот сервер является регистратором. */
private final String freeRegistrationNamespace;
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse,
AllowedEmailDomains allowedEmailDomains) {
AllowedEmailDomains allowedEmailDomains, String freeRegistrationNamespace) {
if ((issuer == null) != (publisher == null)) throw new IllegalArgumentException("Signer/publisher mismatch");
if (issuer != null && emailSender == null) throw new IllegalArgumentException("Email sender is required");
if (emailSender != null && allowedEmailDomains == null)
@@ -65,11 +67,24 @@ public final class FreeRegistrationWorkflow {
this.emailSender = emailSender;
this.allowTestCode = allowTestCode;
this.allowEmailReuse = allowEmailReuse;
this.freeRegistrationNamespace = normalizeConfiguredNamespace(freeRegistrationNamespace);
}
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse,
AllowedEmailDomains allowedEmailDomains) {
this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse, allowedEmailDomains, "");
}
private static String normalizeConfiguredNamespace(String value) {
String namespace = value == null ? "" : value.trim();
if (namespace.isEmpty()) return "";
if (!namespace.matches("[a-z0-9_]+"))
throw new IllegalArgumentException("Free registration namespace must use lowercase ASCII letters, digits or _");
return namespace;
}
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse) {
this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse,
emailSender == null ? null : loadDefaultEmailDomains());
emailSender == null ? null : loadDefaultEmailDomains(), "");
}
private static AllowedEmailDomains loadDefaultEmailDomains() {
try {
@@ -94,10 +109,15 @@ public final class FreeRegistrationWorkflow {
try (Connection c = DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement("""
SELECT namespace,namespace_type,min_localpart_len,registration_fee_lamports,currency_code,default_server_login
FROM shine_namespace_current ORDER BY namespace
"""); ResultSet rs = ps.executeQuery()) {
while (rs.next()) result.add(new NamespaceInfo(rs.getString(1),rs.getInt(2),rs.getInt(3),
rs.getString(4),rs.getInt(5),rs.getString(6)));
FROM shine_namespace_current
WHERE namespace_type = 1 OR (namespace_type = 2 AND namespace = ?)
ORDER BY namespace
""")) {
ps.setString(1, freeRegistrationNamespace);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) result.add(new NamespaceInfo(rs.getString(1),rs.getInt(2),rs.getInt(3),
rs.getString(4),rs.getInt(5),rs.getString(6)));
}
}
return List.copyOf(result);
}
@@ -111,6 +131,8 @@ public final class FreeRegistrationWorkflow {
try (ResultSet rs=p.executeQuery()) {
if (!rs.next()) throw new IllegalArgumentException("Namespace is unavailable");
type=rs.getInt(1); minimum=rs.getInt(2); fee=rs.getString(3); currencyCode=rs.getInt(4);
if (type == 2 && !namespace.equals(freeRegistrationNamespace))
throw new IllegalArgumentException("Free registration is unavailable for this namespace");
if (currencyCode != 1) throw new IllegalStateException("Unsupported namespace currency");
if (login.indexOf('@') < minimum) throw new IllegalArgumentException("Login shorter than namespace minimum");
}
@@ -122,9 +122,12 @@ public final class VerifiedFreeRegistrationImporter {
INSERT INTO blockchain_state_store (
login, fork_number, blockchain_key, size_limit, file_size_bytes,
last_block_number, last_block_hash, updated_at_ms)
VALUES (?, 1, ?, 100000, 0, -1, ?, ?)
VALUES (?, 1, ?, 0, 0, -1, ?, ?)
""")) {
insert.setString(1, login);
// blockchain_state — техническая проекция chain: её ключ
// совпадает с normalized_login и blockchain_name, а не с
// отображаемым написанием login в сертификате.
insert.setString(1, login.toLowerCase(java.util.Locale.ROOT));
// blockchain_state — runtime-слой: его ключ всегда Base64(32),
// как и у пользователей, импортированных из Solana PDA.
insert.setString(2, Base64.getEncoder().encodeToString(cert.blockchainKey()));
@@ -0,0 +1,20 @@
package server.archive.registration;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
class FreeRegistrationNamespaceConfigurationTest {
@Test
void acceptsLowercaseNamespaceForLocalFreeRegistration() {
assertDoesNotThrow(() -> new FreeRegistrationWorkflow(
null, null, null, false, false, null, "testfree"));
}
@Test
void rejectsMixedCaseNamespaceInsteadOfSilentlyServingAnotherNamespace() {
assertThrows(IllegalArgumentException.class, () -> new FreeRegistrationWorkflow(
null, null, null, false, false, null, "TestFree"));
}
}
@@ -33,6 +33,8 @@ public final class DatabaseInitializer {
public static final int SCHEMA_VERSION_40 = 40;
public static final int SCHEMA_VERSION_41 = 41;
public static final int SCHEMA_VERSION_42 = 42;
public static final int SCHEMA_VERSION_43 = 43;
public static final int SCHEMA_VERSION_44 = 44;
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql";
@@ -46,6 +48,8 @@ public final class DatabaseInitializer {
public static final String POSTGRES_MIGRATION_V40_RESOURCE = "postgres/migration_v40.sql";
public static final String POSTGRES_MIGRATION_V41_RESOURCE = "postgres/migration_v41.sql";
public static final String POSTGRES_MIGRATION_V42_RESOURCE = "postgres/migration_v42.sql";
public static final String POSTGRES_MIGRATION_V43_RESOURCE = "postgres/migration_v43.sql";
public static final String POSTGRES_MIGRATION_V44_RESOURCE = "postgres/migration_v44.sql";
private DatabaseInitializer() {}
@@ -185,9 +189,17 @@ public final class DatabaseInitializer {
runSqlScript(conn, POSTGRES_MIGRATION_V42_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion != SCHEMA_VERSION_42) {
if (currentVersion == SCHEMA_VERSION_42) {
runSqlScript(conn, POSTGRES_MIGRATION_V43_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_43) {
runSqlScript(conn, POSTGRES_MIGRATION_V44_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion != SCHEMA_VERSION_44) {
throw new SQLException(
"Unsupported SHiNE DB v2 schema version: expected 42, found " + currentVersion);
"Unsupported SHiNE DB v2 schema version: expected 44, found " + currentVersion);
}
normalizeBlockchainStateKeysToBase64(conn);
}
@@ -187,10 +187,27 @@ public final class BlockchainStateDAO {
}
}
/** Change ONLY the quota projection; 0 means unbounded. */
public void updateSizeLimit(String blockchainName, long limit) throws SQLException {
if (limit < 0L) throw new IllegalArgumentException("limit must be nonnegative");
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement("""
UPDATE blockchain_state_store SET size_limit = ?, updated_at_ms = ?
WHERE LOWER(login) = LOWER(?) AND fork_number = ?
""")) {
ChainRef r = chainRef(blockchainName);
ps.setLong(1, limit);
ps.setLong(2, System.currentTimeMillis());
ps.setString(3, r.login());
ps.setInt(4, r.fork());
ps.executeUpdate();
}
}
/**
* Атомарно увеличить file_size_bytes на deltaBytes, но только если НЕ превысим size_limit.
*/
public boolean tryIncreaseFileSizeWithinLimit(Connection c, String blockchainName, long deltaBytes, long nowMs) throws SQLException {
if (deltaBytes < 0L) throw new IllegalArgumentException("deltaBytes must be nonnegative");
String sql = """
UPDATE blockchain_state_store
SET
@@ -198,7 +215,8 @@ public final class BlockchainStateDAO {
updated_at_ms = ?
WHERE
LOWER(login) = LOWER(?) AND fork_number = ?
AND (file_size_bytes + ?) <= size_limit
AND file_size_bytes <= 9223372036854775807 - ?
AND (size_limit = 0 OR (file_size_bytes + ?) <= size_limit)
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -208,6 +226,7 @@ public final class BlockchainStateDAO {
ps.setString(3, r.login());
ps.setInt(4, r.fork());
ps.setLong(5, deltaBytes);
ps.setLong(6, deltaBytes);
return ps.executeUpdate() > 0;
}
}
@@ -73,10 +73,26 @@ public final class SolanaUserPdaCurrentDAO {
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, blockchainName);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) {
return null;
}
return mapRow(rs);
if (rs.next()) return mapRow(rs);
}
}
// Old forks remain valid separate blockchains even after root rotation.
String forkSql = """
SELECT u.login,
u.login || '-' || LPAD(((f.value ->> 'forkIndex')::integer + 1)::text, 3, '0') AS blockchain_name,
f.value ->> 'blockchainKey' AS blockchain_key,
(f.value ->> 'paidLimitBytes')::bigint AS paid_limit_bytes
FROM solana_user_pda_current u
CROSS JOIN LATERAL jsonb_array_elements(
COALESCE(NULLIF(u.blockchain_forks_json, ''), '[]')::jsonb
) AS f(value)
WHERE LOWER(u.login || '-' || LPAD(((f.value ->> 'forkIndex')::integer + 1)::text, 3, '0')) = LOWER(?)
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(forkSql)) {
ps.setString(1, blockchainName);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? mapRow(rs) : null;
}
}
}
@@ -10,6 +10,7 @@ import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public final class UserNotificationsStateDAO {
private static volatile UserNotificationsStateDAO instance;
@@ -45,7 +46,7 @@ public final class UserNotificationsStateDAO {
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
int i = 1;
ps.setString(i++, e.getOwnerLogin());
ps.setString(i++, normalizedLogin(e.getOwnerLogin()));
ps.setString(i++, e.getNotificationKind());
ps.setLong(i++, e.getCreatedAtMs());
ps.setString(i++, e.getSourceLogin());
@@ -74,7 +75,7 @@ public final class UserNotificationsStateDAO {
""";
List<UserNotificationEntry> out = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerLogin);
ps.setString(1, normalizedLogin(ownerLogin));
ps.setString(2, kind);
ps.setInt(3, Math.max(1, limit));
try (ResultSet rs = ps.executeQuery()) {
@@ -96,7 +97,7 @@ public final class UserNotificationsStateDAO {
""";
List<UserNotificationEntry> out = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerLogin); ps.setString(2, kind); ps.setLong(3, Math.max(0, seenAtMs));
ps.setString(1, normalizedLogin(ownerLogin)); ps.setString(2, kind); ps.setLong(3, Math.max(0, seenAtMs));
ps.setLong(4, Math.max(0, cutoffMs));
try (ResultSet rs = ps.executeQuery()) { while (rs.next()) out.add(mapRow(rs)); }
}
@@ -106,7 +107,7 @@ public final class UserNotificationsStateDAO {
public long countUnseen(Connection c, String ownerLogin, String kind, long seenAtMs) throws SQLException {
String sql = "SELECT COUNT(*) FROM user_notifications_state WHERE owner_login = ? AND notification_kind = ? AND created_at_ms > ?";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerLogin); ps.setString(2, kind); ps.setLong(3, Math.max(0, seenAtMs));
ps.setString(1, normalizedLogin(ownerLogin)); ps.setString(2, kind); ps.setLong(3, Math.max(0, seenAtMs));
try (ResultSet rs = ps.executeQuery()) { return rs.next() ? rs.getLong(1) : 0L; }
}
}
@@ -129,4 +130,12 @@ public final class UserNotificationsStateDAO {
e.setSourceText(rs.getString("source_text"));
return e;
}
/**
* owner_login — технический FK на normalized_login. Исходный регистр остаётся
* в полях подписанного блока и в отображаемых source/target login.
*/
private static String normalizedLogin(String login) {
return login == null ? null : login.trim().toLowerCase(Locale.ROOT);
}
}
@@ -1,6 +1,7 @@
package shine.db.entities;
import java.util.Base64;
import java.util.Locale;
/**
* Агрегатная сущность текущего состояния блокчейна.
@@ -42,14 +43,18 @@ public final class BlockchainStateEntry {
if (dash <= 0 || blockchainName.length()-dash-1 != 3) throw new IllegalArgumentException("Bad blockchainName: "+blockchainName);
int parsedFork=Integer.parseInt(blockchainName.substring(dash+1));
if (parsedFork < 1 || parsedFork > 999) throw new IllegalArgumentException("forkNumber must be 1..999");
this.login=blockchainName.substring(0,dash);
// Runtime-ключ цепочки всегда нормализован. Исходное написание
// зарегистрированного login хранится отдельно в user_identity_current.
this.login=blockchainName.substring(0,dash).trim().toLowerCase(Locale.ROOT);
this.forkNumber=parsedFork;
}
public int getForkNumber() { return forkNumber; }
public void setForkNumber(int forkNumber) { if (forkNumber < 1 || forkNumber > 999) throw new IllegalArgumentException("forkNumber must be 1..999"); this.forkNumber = forkNumber; }
public String getLogin() { return login; }
public void setLogin(String login) { this.login = login; }
public void setLogin(String login) {
this.login = login == null ? null : login.trim().toLowerCase(Locale.ROOT);
}
public String getBlockchainKey() { return blockchainKey; }
public void setBlockchainKey(String blockchainKey) { this.blockchainKey = blockchainKey; }
@@ -80,4 +85,4 @@ public final class BlockchainStateEntry {
public long getUpdatedAtMs() { return updatedAtMs; }
public void setUpdatedAtMs(long updatedAtMs) { this.updatedAtMs = updatedAtMs; }
}
}
@@ -0,0 +1,43 @@
-- v43: runtime-идентичность blockchain_state совпадает с normalized_login.
-- Исходный регистр зарегистрированного имени остаётся в user_identity_current.login
-- и никогда не переписывает подписанные сертификаты или блоки.
BEGIN;
-- blocks_store уже использует normalized_login. Временно снимаем составной FK,
-- чтобы привести родительские строки blockchain_state к тому же ключу.
ALTER TABLE blocks_store DROP CONSTRAINT IF EXISTS fk_blocks_physical_fork;
ALTER TABLE blockchain_state_store DROP CONSTRAINT IF EXISTS blockchain_state_login_fkey;
-- v36-совместимость подставляла display login, что несовместимо с blocks_store.
DROP TRIGGER IF EXISTS trg_canonical_identity_blockchain_state_store_login
ON blockchain_state_store;
UPDATE blockchain_state_store
SET login = LOWER(BTRIM(login))
WHERE login IS DISTINCT FROM LOWER(BTRIM(login));
ALTER TABLE blockchain_state_store
ADD CONSTRAINT blockchain_state_login_fkey
FOREIGN KEY (login) REFERENCES user_identity_current(normalized_login);
ALTER TABLE blocks_store
ADD CONSTRAINT fk_blocks_physical_fork
FOREIGN KEY (login, fork_number)
REFERENCES blockchain_state_store(login, fork_number);
CREATE OR REPLACE FUNCTION shine_normalize_blockchain_state_login()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
NEW.login := LOWER(BTRIM(NEW.login));
RETURN NEW;
END $$;
CREATE TRIGGER trg_normalize_blockchain_state_login
BEFORE INSERT OR UPDATE OF login ON blockchain_state_store
FOR EACH ROW EXECUTE FUNCTION shine_normalize_blockchain_state_login();
UPDATE db_schema_version
SET schema_version = 43,
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
WHERE id = 1;
COMMIT;
@@ -0,0 +1,29 @@
-- v44: owner_login уведомлений — технический ключ normalized_login.
-- Исходный регистр остаётся в содержимом подписанных блоков и полях source/target.
BEGIN;
UPDATE user_notifications_state
SET owner_login = LOWER(BTRIM(owner_login))
WHERE owner_login IS DISTINCT FROM LOWER(BTRIM(owner_login));
DROP TRIGGER IF EXISTS trg_canonical_identity_user_notifications_state_owner_login
ON user_notifications_state;
DROP TRIGGER IF EXISTS trg_normalize_user_notifications_state_owner_login
ON user_notifications_state;
CREATE OR REPLACE FUNCTION shine_normalize_user_notification_owner_login()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
NEW.owner_login := LOWER(BTRIM(NEW.owner_login));
RETURN NEW;
END $$;
CREATE TRIGGER trg_normalize_user_notifications_state_owner_login
BEFORE INSERT OR UPDATE OF owner_login ON user_notifications_state
FOR EACH ROW EXECUTE FUNCTION shine_normalize_user_notification_owner_login();
UPDATE db_schema_version
SET schema_version = 44,
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
WHERE id = 1;
COMMIT;
@@ -34,9 +34,14 @@ dependencies {
implementation project(':shine-server-db') // модуль для работы с БД содержит и сущности из БД и саму работу с БД
implementation project(':shine-server-geo') // модуль для определения геолокации по IP
testImplementation 'org.junit.jupiter:junit-jupiter:5.11.0'
}
test {
useJUnitPlatform()
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
@@ -143,7 +143,7 @@ public final class SolanaUserPdaImportService {
if (!MAGIC.equals(new String(raw, 0, 5, StandardCharsets.UTF_8))) return null;
int major = u8(raw, 5);
int minor = u8(raw, 6);
if (major != 1 || minor != 2) return null;
if (major != 1 || (minor != 2 && minor != 3)) return null;
return parseUserPdaV12(raw);
}
@@ -256,7 +256,7 @@ public final class SolanaUserPdaImportService {
if (!MAGIC.equals(new String(raw, 0, 5, StandardCharsets.UTF_8))) return null;
int major = u8(raw, 5);
int minor = u8(raw, 6);
if (major != 1 || minor != 2) return null;
if (major != 1 || (minor != 2 && minor != 3)) return null;
return parseServerProfileV12(raw);
}
@@ -38,6 +38,8 @@ import shine.db.dao.BlocksDAO;
import shine.db.dao.CanonicalChainResolver;
import shine.db.dao.ChannelNameStateDAO;
import shine.db.dao.CurrentUsersDAO;
import shine.db.dao.SolanaUserPdaCurrentDAO;
import shine.db.entities.SolanaUserPdaCurrentEntry;
import shine.db.dao.UserNotificationsStateDAO;
import shine.db.dao.UserParamsDAO;
import shine.db.entities.BlockchainStateEntry;
@@ -53,6 +55,7 @@ import java.util.List;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.locks.ReentrantLock;
/**
@@ -67,6 +70,11 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_AddBlock_Handler.class);
private static long resolveChainLimit(String blockchainName) throws SQLException {
SolanaUserPdaCurrentEntry current = SolanaUserPdaCurrentDAO.getInstance().getByBlockchainName(blockchainName);
return current == null ? 0L : current.getPaidLimitBytes();
}
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
private final CanonicalChainResolver canonicalChain = CanonicalChainResolver.getInstance();
private final BlockchainStateDAO stateDAO = BlockchainStateDAO.getInstance();
@@ -281,7 +289,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
recovered.setBlockchainName(user.getBlockchainName());
recovered.setLogin(user.getLogin());
recovered.setBlockchainKey(user.getBlockchainKey());
recovered.setSizeLimit(100_000L);
recovered.setSizeLimit(Math.max(0L, resolveChainLimit(user.getBlockchainName())));
recovered.setFileSizeBytes(0L);
recovered.setLastBlockNumber(-1);
recovered.setLastBlockHash(new byte[32]);
@@ -335,7 +343,12 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
// 3) лимит (оставляем как было)
try {
long oldSize = st.getFileSizeBytes();
long limit = st.getSizeLimit();
// Current synced Solana PDA is authoritative; free users have no PDA.
long limit = resolveChainLimit(blockchainName);
if (limit != st.getSizeLimit()) {
stateDAO.updateSizeLimit(blockchainName, limit);
st.setSizeLimit(limit);
}
long newSize = safeAdd(oldSize, blockBytes.length);
if (limit > 0 && newSize > limit) {
@@ -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;
}
}
@@ -5,6 +5,7 @@ import blockchain.body.BodyRecord;
import blockchain.body.CreateChannelBody;
import blockchain.body.TextLineBody;
import blockchain.body.TextReplyBody;
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetChannelMessages_Response;
import shine.db.channels.ChannelNameRules;
import shine.db.MsgSubType;
import shine.db.sql.CurrentUsersSql;
@@ -226,6 +227,7 @@ final class ChannelsReadSupport {
} else if (e.body instanceof blockchain.body.StatusActionBody sab) {
ti.text = sab.message;
}
ti.attachmentMetadataValid = AttachmentMarkerValidator.validateLeadingV2Markers(ti.text);
return ti;
} catch (Exception ex) {
return new TextInfo();
@@ -236,7 +238,7 @@ final class ChannelsReadSupport {
String order = asc ? "ASC" : "DESC";
boolean bounded = limit > 0;
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
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)
@@ -263,6 +265,9 @@ final class ChannelsReadSupport {
pb.blockNumber = rs.getInt("block_number");
pb.blockHash = rs.getBytes("block_hash");
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.toBlockNumber = (Integer) rs.getObject("to_block_number");
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 {
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
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type=?
AND to_block_number=? AND to_block_hash=?
@@ -309,6 +314,9 @@ final class ChannelsReadSupport {
pb.blockNumber = rs.getInt("block_number");
pb.blockHash = rs.getBytes("block_hash");
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);
}
return out;
@@ -703,12 +711,27 @@ final class ChannelsReadSupport {
|| 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 {
String login;
String bchName;
int blockNumber;
byte[] blockHash;
byte[] blockBytes;
byte[] dataItemId;
boolean arweavePublishPending;
Long arweavePublishedAtMs;
String toBchName;
Integer toBlockNumber;
byte[] toBlockHash;
@@ -717,6 +740,7 @@ final class ChannelsReadSupport {
}
static final class TextInfo {
boolean attachmentMetadataValid = true;
String text = "";
long createdAtMs = 0L;
}
@@ -152,7 +152,9 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
v1.setBlockNumber(post.blockNumber);
v1.setBlockHash(ChannelsReadSupport.toHex(post.blockHash));
v1.setText(postText.text);
v1.setAttachmentMetadataValid(postText.attachmentMetadataValid);
v1.setCreatedAtMs(postText.createdAtMs);
ChannelsReadSupport.setStorageInfo(v1, post.dataItemId, post.arweavePublishPending, post.arweavePublishedAtMs, post.blockBytes);
versionsOut.add(v1);
if (ChannelsReadSupport.supportsEditPostVersions(post.msgSubType)) {
@@ -164,13 +166,20 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
ve.setBlockNumber(edit.blockNumber);
ve.setBlockHash(ChannelsReadSupport.toHex(edit.blockHash));
ve.setText(editText.text);
ve.setAttachmentMetadataValid(editText.attachmentMetadataValid);
ve.setCreatedAtMs(editText.createdAtMs);
ChannelsReadSupport.setStorageInfo(ve, edit.dataItemId, edit.arweavePublishPending, edit.arweavePublishedAtMs, edit.blockBytes);
versionsOut.add(ve);
}
}
item.setVersions(versionsOut);
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);
item.setText(lastV.getText());
@@ -19,7 +19,6 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Comparator;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
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 {
String targetLogin = ChannelsReadSupport.loginFromChainName(toBchName);
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
WHERE msg_type=1
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 {
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
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)
@@ -172,7 +171,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
private PostRow findByNumber(Connection c, String bchName, int blockNumber) throws Exception {
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
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)
@@ -191,7 +190,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
private PostRow findByNumberAndHash(Connection c, String bchName, int blockNumber, byte[] blockHash) throws Exception {
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
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)
@@ -226,6 +225,9 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
row.blockNumber = rs.getInt("block_number");
row.blockHash = rs.getBytes("block_hash");
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.toBchName = rs.getString("to_bch_name");
row.toBlockNumber = (Integer) rs.getObject("to_block_number");
@@ -259,7 +261,13 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
first.setBlockNumber(row.blockNumber);
first.setBlockHash(ChannelsReadSupport.toHex(row.blockHash));
first.setText(base.text);
first.setAttachmentMetadataValid(base.attachmentMetadataValid);
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);
if (row.msgSubType == MsgSubType.TEXT_REPLY
@@ -275,19 +283,18 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
v.setBlockNumber(edit.blockNumber);
v.setBlockHash(ChannelsReadSupport.toHex(edit.blockHash));
v.setText(et.text);
v.setAttachmentMetadataValid(et.attachmentMetadataValid);
v.setCreatedAtMs(et.createdAtMs);
ChannelsReadSupport.setStorageInfo(v, edit.dataItemId, edit.arweavePublishPending, edit.arweavePublishedAtMs, edit.blockBytes);
versions.add(v);
}
}
node.setVersions(versions);
node.setVersionsTotal(versions.size());
node.setAttachmentMetadataValid(first.isAttachmentMetadataValid());
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);
node.setLikesCount(stats[0]);
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 {
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
WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND msg_sub_type=?
AND to_block_number=? AND to_block_hash=?
@@ -338,6 +345,9 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
int blockNumber;
byte[] blockHash;
byte[] blockBytes;
byte[] dataItemId;
boolean arweavePublishPending;
Long arweavePublishedAtMs;
String toLogin;
String toBchName;
Integer toBlockNumber;
@@ -159,6 +159,11 @@ public class Net_GetChannelMessages_Response extends Net_Response {
private int repliesCount;
private int ratingsCount;
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<>();
public BlockRef getMessageRef() { return messageRef; }
@@ -221,6 +226,17 @@ public class Net_GetChannelMessages_Response extends Net_Response {
public int getRatingsCount() { return 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 void setVersionsTotal(int versionsTotal) { this.versionsTotal = versionsTotal; }
@@ -234,6 +250,22 @@ public class Net_GetChannelMessages_Response extends Net_Response {
private String blockHash;
private String text;
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 void setVersionIndex(int versionIndex) { this.versionIndex = versionIndex; }
@@ -21,13 +21,10 @@ public class Net_GetMessageThread_Response extends Net_Response {
public static class MessageNode extends Net_GetChannelMessages_Response.MessageItem {
private ChannelInfo channelInfo;
private String rawBlockB64;
public ChannelInfo getChannelInfo() { return 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 {
@@ -13,6 +13,8 @@ import server.logic.ws_protocol.WireCodes;
import shine.db.dao.BlockchainStateDAO;
import shine.db.DbController;
import shine.db.dao.CurrentUsersDAO;
import shine.db.dao.SolanaUserPdaCurrentDAO;
import shine.db.entities.SolanaUserPdaCurrentEntry;
import shine.db.entities.BlockchainStateEntry;
import shine.db.entities.CurrentUserEntry;
@@ -26,6 +28,11 @@ public class Net_GetUser_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_GetUser_Handler.class);
private static long resolveChainLimit(String blockchainName) throws SQLException {
SolanaUserPdaCurrentEntry current = SolanaUserPdaCurrentDAO.getInstance().getByBlockchainName(blockchainName);
return current == null ? 0L : current.getPaidLimitBytes();
}
@Override
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
Net_GetUser_Request req = (Net_GetUser_Request) baseRequest;
@@ -80,7 +87,7 @@ public class Net_GetUser_Handler implements JsonMessageHandler {
st.setLastBlockNumber(-1);
st.setLastBlockHash(new byte[32]);
st.setFileSizeBytes(0);
st.setSizeLimit(1_000_000L);
st.setSizeLimit(Math.max(0L, resolveChainLimit(u.getBlockchainName())));
st.setUpdatedAtMs(System.currentTimeMillis());
stateDAO.upsert(st);
log.warn("GetUser: восстановлена запись blockchain_state для login={}, blockchainName={}",
@@ -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);
}
}
@@ -142,20 +142,17 @@ public final class ShineUsersCodec {
null
);
case IX_UPDATE_USERS_ECONOMY_CONFIG ->
new ParsedInstruction(
TxKind.UPDATE_USERS_ECONOMY_CONFIG,
false,
null,
null,
new EconomyConfigState(
1,
reader.readU64(),
reader.readU64(),
reader.readU64()
),
null
);
case IX_UPDATE_USERS_ECONOMY_CONFIG -> {
// Historical v1 transactions contain three u64s, v2 only update fee.
int payloadBytes = reader.remaining();
EconomyConfigState economy = switch (payloadBytes) {
case 8 -> new EconomyConfigState(2, 0L, 0L, 0L, reader.readU64());
case 24 -> new EconomyConfigState(1, reader.readU64(), reader.readU64(), reader.readU64(), 20_000L);
default -> throw new IllegalArgumentException("Invalid economy config instruction length");
};
yield new ParsedInstruction(TxKind.UPDATE_USERS_ECONOMY_CONFIG,
false, null, null, economy, null);
}
case IX_UPDATE_NAMESPACE_PRICE ->
new ParsedInstruction(
@@ -260,7 +257,7 @@ public final class ShineUsersCodec {
if (formatMajor != 1) {
throw new IllegalArgumentException("Unsupported PDA format " + formatMajor + "." + formatMinor);
}
if (formatMinor == 2) {
if (formatMinor == 2 || formatMinor == 3) {
return parseUserPdaAccountV12(pdaAddress, slot, rawDataBase64, lastTxSignature, raw);
}
if (formatMinor == 0) {
@@ -862,17 +859,13 @@ public final class ShineUsersCodec {
public record EconomyConfigState(
int version,
long registrationFeeLamports,
long lamportsPerLimitStep,
long startBonusLimit
long registrationFeeLamports, // legacy v1 only
long lamportsPerLimitStep, // legacy v1 only
long startBonusLimit, // legacy v1 only
long updateFeeLamports // v2 (v1 fallback 20_000)
) {
public static EconomyConfigState initial() {
return new EconomyConfigState(
1,
START_REGISTRATION_FEE_LAMPORTS,
START_LAMPORTS_PER_LIMIT_STEP,
START_BONUS_LIMIT
);
return new EconomyConfigState(2, 0L, 0L, 0L, 20_000L);
}
}
@@ -63,7 +63,7 @@ public final class PostgresStorageRepository
"last_error, economy_config_version, " +
"registration_fee_lamports, " +
"lamports_per_limit_step, " +
"start_bonus_limit, updated_at_ms " +
"start_bonus_limit, update_fee_lamports, updated_at_ms " +
"FROM solana_sync_state WHERE id = 1"
);
ResultSet resultSet =
@@ -106,7 +106,8 @@ public final class PostgresStorageRepository
),
resultSet.getLong(
"start_bonus_limit"
)
),
resultSet.getLong("update_fee_lamports")
);
}
@@ -274,6 +275,7 @@ public final class PostgresStorageRepository
connection,
snapshots
);
syncBlockchainStateLimits(connection, snapshots);
reconcileConfirmedKeyRotations(
connection,
@@ -314,6 +316,7 @@ public final class PostgresStorageRepository
connection,
snapshots
);
syncBlockchainStateLimits(connection, snapshots);
reconcileConfirmedKeyRotations(
connection,
@@ -337,6 +340,36 @@ public final class PostgresStorageRepository
}
}
/** Copy on-chain fork limits into the server's runtime state. 0 = unbounded.
* Never touch block tips, used bytes, or keys. Works after PDA updates even
* when record_number remains unchanged (future system-only limit mutation).
*/
private void syncBlockchainStateLimits(Connection connection,
List<ShineUsersCodec.UserPdaSnapshot> snapshots) throws SQLException {
if (snapshots == null || snapshots.isEmpty()) return;
try (PreparedStatement exists = connection.prepareStatement("SELECT to_regclass('public.blockchain_state_store')")) {
try (ResultSet rs = exists.executeQuery()) {
if (!rs.next() || rs.getString(1) == null) return;
}
}
try (PreparedStatement stmt = connection.prepareStatement("""
UPDATE blockchain_state_store SET size_limit = ?, updated_at_ms = ?
WHERE LOWER(login) = LOWER(?) AND fork_number = ?
""")) {
for (ShineUsersCodec.UserPdaSnapshot snapshot : snapshots) {
if (snapshot == null || snapshot.blockchainForks() == null) continue;
for (ShineUsersCodec.BlockchainForkSnapshot fork : snapshot.blockchainForks()) {
stmt.setLong(1, fork.paidLimitBytes());
stmt.setLong(2, System.currentTimeMillis());
stmt.setString(3, snapshot.login());
stmt.setInt(4, fork.forkIndex() + 1);
stmt.addBatch();
}
}
stmt.executeBatch();
}
}
private void upsertTxHistory(
Connection connection,
List<TxHistoryEntry> txEntries
@@ -862,8 +895,8 @@ public final class PostgresStorageRepository
"last_seen_slot, last_relevant_signature, " +
"last_relevant_slot, last_error, economy_config_version, " +
"registration_fee_lamports, lamports_per_limit_step, " +
"start_bonus_limit, updated_at_ms" +
") VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " +
"start_bonus_limit, update_fee_lamports, updated_at_ms" +
") VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " +
"ON CONFLICT (id) DO UPDATE SET " +
"status = EXCLUDED.status, " +
"ready = EXCLUDED.ready, " +
@@ -878,6 +911,7 @@ public final class PostgresStorageRepository
"registration_fee_lamports = EXCLUDED.registration_fee_lamports, " +
"lamports_per_limit_step = EXCLUDED.lamports_per_limit_step, " +
"start_bonus_limit = EXCLUDED.start_bonus_limit, " +
"update_fee_lamports = EXCLUDED.update_fee_lamports, " +
"updated_at_ms = EXCLUDED.updated_at_ms";
try (PreparedStatement statement =
@@ -898,14 +932,16 @@ public final class PostgresStorageRepository
statement.setNull(11, Types.BIGINT);
statement.setNull(12, Types.BIGINT);
statement.setNull(13, Types.BIGINT);
statement.setNull(14, Types.BIGINT);
} else {
statement.setInt(10, snapshot.economyConfigState().version());
statement.setLong(11, snapshot.economyConfigState().registrationFeeLamports());
statement.setLong(12, snapshot.economyConfigState().lamportsPerLimitStep());
statement.setLong(13, snapshot.economyConfigState().startBonusLimit());
statement.setLong(14, snapshot.economyConfigState().updateFeeLamports());
}
bindNullableLong(statement, 14, snapshot.updatedAtMs());
bindNullableLong(statement, 15, snapshot.updatedAtMs());
statement.executeUpdate();
}
}
@@ -934,10 +970,13 @@ public final class PostgresStorageRepository
"registration_fee_lamports BIGINT, " +
"lamports_per_limit_step BIGINT, " +
"start_bonus_limit BIGINT, " +
"update_fee_lamports BIGINT, " +
"updated_at_ms BIGINT" +
")"
);
statement.executeUpdate("ALTER TABLE solana_sync_state ADD COLUMN IF NOT EXISTS update_fee_lamports BIGINT");
statement.executeUpdate(
"INSERT INTO solana_sync_state (id, status, ready) " +
"VALUES (1, 'EMPTY', FALSE) " +
@@ -58,10 +58,10 @@ public final class KeyRotationRebuildService {
}
private void registerCandidateSegment(KeyRotationSessionEntry s)throws Exception{try(Connection c=DbController.getInstance().getConnection()){segments.upsert(c,new BlockchainForkSegmentsDAO.Segment(s.getLogin(),forkOf(s.getCandidateBlockchainName()),forkOf(s.getSourceBlockchainName()),s.getForkFromBlock(),s.getForkFromHash(),s.getForkFromBlock()+1,System.currentTimeMillis()));}}
private void replayStaging(KeyRotationSessionEntry s)throws Exception{
SolanaUserPdaCurrentEntry u=users.getByLogin(s.getLogin());long limit=u!=null&&u.getPaidLimitBytes()>0?u.getPaidLimitBytes():100_000L;long cumulative=0;int currentFork=-1;int prevNumber=-1;byte[] prevHash=null;
long cumulative=0;int currentFork=-1;int prevNumber=-1;byte[] prevHash=null;
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,physical_fork_number,blockchain_key,block_bytes,block_hash FROM key_rotation_rebuild_staging WHERE rotation_session_id=? ORDER BY logical_block_number ASC")){ps.setLong(1,s.getId());try(ResultSet rs=ps.executeQuery()){while(rs.next()){
int n=rs.getInt(1),f=rs.getInt(2);String key=rs.getString(3);byte[] raw=rs.getBytes(4),hash=rs.getBytes(5);String bch=s.getLogin()+"-"+String.format("%03d",f);
if(f!=currentFork){BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(s.getLogin());st.setBlockchainKey(key);st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());states.insertIfMissing(st);currentFork=f;}
if(f!=currentFork){SolanaUserPdaCurrentEntry forkOwner=users.getByBlockchainName(bch);long limit=forkOwner==null?0L:forkOwner.getPaidLimitBytes();BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(s.getLogin());st.setBlockchainKey(key);st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());states.insertIfMissing(st);currentFork=f;}
String target=bch;BlockchainResyncGuard.withBypass(target,()->{Net_AddBlock_Handler.ArweaveImportResult r=addBlock.addBlockFromReplay(target,raw);if(!r.ok())throw new IllegalStateException("canonical replay rejected #"+n+": "+r.reasonCode());});
cumulative+=raw.length;prevNumber=n;prevHash=hash;
}}}
@@ -370,7 +370,7 @@ public final class PeriodicBlockchainSyncService {
state.setBlockchainName(currentUser.getBlockchainName());
state.setLogin(currentUser.getLogin());
state.setBlockchainKey(currentUser.getBlockchainKey());
state.setSizeLimit(currentUser.getPaidLimitBytes() > 0 ? currentUser.getPaidLimitBytes() : 100_000L);
state.setSizeLimit(currentUser.getPaidLimitBytes());
state.setFileSizeBytes(existingState == null ? 0L : existingState.getFileSizeBytes());
state.setLastBlockNumber(existingState == null ? -1 : existingState.getLastBlockNumber());
state.setLastBlockHash(existingState == null ? null : existingState.getLastBlockHash());
+2 -2
View File
@@ -1,2 +1,2 @@
client.version=1.20.59
server.version=1.16.30
client.version=1.20.67
server.version=1.16.33
+2 -1
View File
@@ -5,7 +5,8 @@
- Все вопросы деплоя SHiNE решать через эту папку `deploy/`.
- Скрипты лежат в `deploy/scripts/`.
- Production-серверы: `shineup.me` и `server2.shineup.me`.
- Test/devnet серверы: `t1.shineup.me`, `t2.shineup.me`, `t3.shineup.me`, `t4.shineup.me`.
- Test/devnet серверы: `t1.shineup.me`, `t2.shineup.me`, `t3.shineup.me`.
- Отдельный общий тестовый сервер: `test.shineup.me`. На нём уже работают тестовые пользователи; не использовать его для очистки, пересоздания или экспериментального деплоя без отдельного подтверждения.
- TURN-серверы: `turn1.shineup.me`, `turn2.shineup.me`, `turn3.shineup.me`.
- В deploy-документах и скриптах использовать домены, а не IP.
+2 -4
View File
@@ -12,7 +12,7 @@ Production:
- `t1.shineup.me`;
- `t2.shineup.me`;
- `t3.shineup.me`;
- `t4.shineup.me`.
- `test.shineup.me` — общий рабочий тестовый сервер с тестовыми пользователями; не очищать и не пересоздавать без отдельного подтверждения.
В документации и скриптах использовать домены, а не IP. SSH-пользователь — `player`.
@@ -46,8 +46,6 @@ bash deploy/scripts/test_t2_server.sh
bash deploy/scripts/test_t2_ui.sh
bash deploy/scripts/test_t3_server.sh
bash deploy/scripts/test_t3_ui.sh
bash deploy/scripts/test_t4_server.sh
bash deploy/scripts/test_t4_ui.sh
```
Не путать `server2.shineup.me` и `t2.shineup.me`.
@@ -65,6 +63,6 @@ bash deploy/scripts/test_t4_ui.sh
| `t1.shineup.me` | `player@t1.shineup.me` | `/home/player/t1/server` | `shine-t1` | 7101 |
| `t2.shineup.me` | `player@t2.shineup.me` | `/home/player/t2/server` | `shine-t2` | 7102 |
| `t3.shineup.me` | `player@t3.shineup.me` | `/home/player/t3/server` | `shine-t3` | 7103 |
| `t4.shineup.me` | `player@t4.shineup.me` | `/home/player/t4/server` | `shine-t4` | 7104 |
| `test.shineup.me` | `player@t4.shineup.me` | `/home/player/t4/server` | `shine-test` | 7104 |
Источники истины для деталей и backup: `deploy/AGENTS.md`, `deploy/README.md`, `deploy/backup/README.md` и сами скрипты `deploy/scripts/`.
+1 -1
View File
@@ -6,7 +6,7 @@
- целевой стандарт для SHiNE: `PostgreSQL 18.x`;
- текущий факт на production `shineup.me` и `server2.shineup.me` на дату `2026-07-28`: `PostgreSQL 18.4`;
- текущий факт на test/devnet `t1` / `t2` / `t3` / `t4` на дату `2026-07-28`: `PostgreSQL 18.4`.
- текущий факт на test/devnet `t1` / `t2` / `t3` / `test.shineup.me` на дату `2026-07-28`: `PostgreSQL 18.4`.
## Цель
+3 -4
View File
@@ -13,12 +13,13 @@
- Основной production: `shineup.me`.
- Второй production: `server2.shineup.me`.
- Test/devnet стенд: `t1.shineup.me`, `t2.shineup.me`, `t3.shineup.me`, `t4.shineup.me`.
- Test/devnet стенд: `t1.shineup.me`, `t2.shineup.me`, `t3.shineup.me`.
- Общий рабочий тестовый сервер: `test.shineup.me`. На нём уже работают тестовые пользователи; не очищать и не пересоздавать без отдельного подтверждения.
Краткое текущее состояние на `2026-07-28`:
- оба production уже на `PostgreSQL 18.4` в отдельных Docker-контейнерах `shine-postgres`;
- весь test/devnet стенд `t1`-`t4` тоже уже на `PostgreSQL 18.4`;
- test/devnet стенд `t1`-`t3` и общий `test.shineup.me` уже на `PostgreSQL 18.4`;
- тестовые контуры используют общий Docker-контейнер `shine-test-postgres`;
- production использует Helius mainnet, test/devnet использует Helius devnet;
- актуальные подробности по всем шести серверам смотреть в `PRODUCTION_SERVERS.md` и `TEST_SERVERS.md`.
@@ -82,8 +83,6 @@ Test/devnet wrappers:
- `scripts/test_t2_ui.sh`
- `scripts/test_t3_server.sh`
- `scripts/test_t3_ui.sh`
- `scripts/test_t4_server.sh`
- `scripts/test_t4_ui.sh`
## Примеры
+2 -1
View File
@@ -7,7 +7,8 @@
Создать DNS-запись домена:
- production: `shineup.me` или `server2.shineup.me`;
- test/devnet: `t1.shineup.me` ... `t4.shineup.me`.
- test/devnet: `t1.shineup.me`, `t2.shineup.me`, `t3.shineup.me`.
- общий рабочий тестовый сервер: `test.shineup.me`; не очищать и не пересоздавать без отдельного подтверждения.
После смены физического сервера достаточно обновить DNS.
+1 -1
View File
@@ -9,6 +9,6 @@ handle @solana_rpc {
}
```
Порт `7070` приведён для основного сервера из резервной конфигурации. У t1/t2/t3/t4 используйте фактический локальный Java-порт (например, 7102). Не заменяйте существующие настройки сервера целиком этой вставкой.
Порт `7070` приведён для основного сервера из резервной конфигурации. У t1/t2/t3 и `test.shineup.me` используйте фактический локальный Java-порт (например, 7102). Не заменяйте существующие настройки сервера целиком этой вставкой.
Далее: `caddy validate --config /etc/caddy/Caddyfile`, перезагрузите Caddy и проверьте `POST https://<ваш-сервер>/solana-rpc` с JSON-RPC `getVersion`.
+14 -11
View File
@@ -1,17 +1,20 @@
# Test/devnet серверы SHiNE
Отдельный test/devnet стенд состоит из четырёх независимых SHiNE-инстансов:
Основной test/devnet стенд состоит из трёх независимых SHiNE-инстансов:
- `t1.shineup.me`
- `t2.shineup.me`
- `t3.shineup.me`
- `t4.shineup.me`
Отдельно работает общий тестовый сервер:
- `test.shineup.me` — бывший T4, с уже работающими тестовыми пользователями. Не очищать и не пересоздавать без отдельного подтверждения.
Это не production. Все deploy-цели задаются через домены.
Текущее фактическое состояние на `2026-07-28`:
- все четыре тестовых контура `t1` / `t2` / `t3` / `t4` уже работают без `SQLite`;
- `t1`, `t2`, `t3` и `test.shineup.me` работают без `SQLite`;
- все четыре контура используют `PostgreSQL 18.4`;
- PostgreSQL на test-хосте общий для всех четырёх контуров и запущен в Docker-контейнере `shine-test-postgres`;
- все четыре контура используют один и тот же Helius devnet RPC/WS endpoint;
@@ -44,7 +47,7 @@
| `t1.shineup.me` | `server_t1` | `/home/player/t1/server` | `/home/player/t1/UI` | `7101` | `shine-t1.service` | `shine_t1_db` | `shine_t1` |
| `t2.shineup.me` | `server_t2` | `/home/player/t2/server` | `/home/player/t2/UI` | `7102` | `shine-t2.service` | `shine_t2_db` | `shine_t2` |
| `t3.shineup.me` | `server_t3` | `/home/player/t3/server` | `/home/player/t3/UI` | `7103` | `shine-t3.service` | `shine_t3_db` | `shine_t3` |
| `t4.shineup.me` | `server_t4` | `/home/player/t4/server` | `/home/player/t4/UI` | `7104` | `shine-t4.service` | `shine_t4_db` | `shine_t4` |
| `test.shineup.me` | `test_server@shine` | `/home/player/t4/server` | `/home/player/t4/UI` | `7104` | `shine-test.service` | `shine_test_db` | `shine_t2` |
## Deploy
@@ -58,7 +61,7 @@
DEPLOY_SOLANA_ENDPOINT="https://t1.shineup.me/solana-rpc" bash deploy/scripts/test_t1_ui.sh
```
Для остальных стендов замените `t1` на `t2`, `t3`, `t4`. Не вставляйте URL с личным ключом Helius в `DEPLOY_SOLANA_ENDPOINT`: значение будет опубликовано в `shine-UI/js/deploy-config.js` на сайте.
Для остальных стендов замените `t1` на `t2` или `t3`. Для общего тестового сервера используйте `test.shineup.me`; не выполняйте на нём очистку или пересоздание. Не вставляйте URL с личным ключом Helius в `DEPLOY_SOLANA_ENDPOINT`: значение будет опубликовано в `shine-UI/js/deploy-config.js` на сайте.
```bash
bash deploy/scripts/test_t1_server.sh
@@ -70,8 +73,8 @@ DEPLOY_SOLANA_ENDPOINT="https://t2.shineup.me/solana-rpc" bash deploy/scripts/te
bash deploy/scripts/test_t3_server.sh
DEPLOY_SOLANA_ENDPOINT="https://t3.shineup.me/solana-rpc" bash deploy/scripts/test_t3_ui.sh
bash deploy/scripts/test_t4_server.sh
DEPLOY_SOLANA_ENDPOINT="https://t4.shineup.me/solana-rpc" bash deploy/scripts/test_t4_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
```
## Проверка
@@ -80,13 +83,13 @@ DEPLOY_SOLANA_ENDPOINT="https://t4.shineup.me/solana-rpc" bash deploy/scripts/te
curl -I https://t1.shineup.me
curl -I https://t2.shineup.me
curl -I https://t3.shineup.me
curl -I https://t4.shineup.me
curl -I https://test.shineup.me
```
На сервере:
```bash
sudo systemctl --no-pager --full status caddy shine-t1 shine-t2 shine-t3 shine-t4
sudo systemctl --no-pager --full status caddy shine-t1 shine-t2 shine-t3 shine-test
sudo docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}'
```
@@ -96,6 +99,6 @@ sudo docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}'
Отдельный нюанс по web push:
- у `t1`, `t2`, `t3`, `t4` в UI уже есть одинаковый встроенный `VAPID` public key;
- то есть `t3` и `t4` используют тот же web push клиентский код, что и `t1` / `t2`;
- у `t1`, `t2`, `t3` и `test.shineup.me` в UI уже есть одинаковый встроенный `VAPID` public key;
- то есть `t3` и `test.shineup.me` используют тот же web push клиентский код, что и `t1` / `t2`;
- если позже понадобится разделить push-ключи по тестовым контурам, это нужно делать отдельным UI deploy с новым `DEPLOY_WEBPUSH_VAPID_PUBLIC`.
+27
View File
@@ -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 перезапущен"
+6 -7
View File
@@ -2,20 +2,19 @@
set -euo pipefail
# Use an explicit public RPC gateway URL. Never commit an Helius API key.
# Recommended: https://t4.shineup.me/solana-rpc (only if the proxy is configured).
if [[ -z "${DEPLOY_SOLANA_ENDPOINT:-}" ]]; then
echo "ERROR: DEPLOY_SOLANA_ENDPOINT is required for t4 UI deploy." >&2
echo "Set it to a working public RPC gateway (prefer your /solana-rpc proxy)." >&2
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="t4.shineup.me" \
DEPLOY_SERVER_LOGIN="server_t4" \
DEPLOY_SERVER_ADDRESS="t4.shineup.me" \
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://t4.shineup.me" \
TARGET_URL="https://test.shineup.me" \
bash "$(dirname "$0")/deploy_ui.sh"
+24 -8
View File
@@ -1,11 +1,27 @@
#!/usr/bin/env bash
set -euo pipefail
REMOTE_HOST="player@t2.shineup.me" \
TARGET_DOMAIN="t2.shineup.me" \
REMOTE_SERVER_DIR="/home/player/t2/server" \
REMOTE_DM_FILES_DIR="/home/player/test-dm-files" \
REMOTE_PUBLIC_FILES_DIR="/home/player/test-public-files" \
REMOTE_SERVICE_NAME="shine-t2" \
SERVER_PORT="7102" \
bash "$(dirname "$0")/deploy_server.sh"
# t2.shineup.me использует /etc/shine/shine-t2.env. Не вызываем
# deploy_server.sh: тот пересоздаёт unit без EnvironmentFile.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
REMOTE_HOST="player@t2.shineup.me"
REMOTE_SERVER_DIR="/home/player/t2/server"
REMOTE_SERVICE_NAME="shine-t2"
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 t2.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 "Всё хорошо: сервер t2.shineup.me обновлён и сервис $REMOTE_SERVICE_NAME перезапущен"
-11
View File
@@ -1,11 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
REMOTE_HOST="player@t4.shineup.me" \
TARGET_DOMAIN="t4.shineup.me" \
REMOTE_SERVER_DIR="/home/player/t4/server" \
REMOTE_DM_FILES_DIR="/home/player/test-dm-files" \
REMOTE_PUBLIC_FILES_DIR="/home/player/test-public-files" \
REMOTE_SERVICE_NAME="shine-t4" \
SERVER_PORT="7104" \
bash "$(dirname "$0")/deploy_server.sh"
+4 -3
View File
@@ -275,9 +275,10 @@
### MessageNode (дополнение)
- `MessageNode` расширяет формат сообщения из `GetChannelMessages` и дополнительно содержит:
- `channelInfo` — мета-информация о канале (если применимо);
- `rawBlockB64` — сырой `block_bytes` текущего блока в Base64.
- Поле `rawBlockB64` присутствует у узлов во всех частях ответа `GetMessageThread`: `focus`, `ancestors[]`, `descendants[]`.
- В `GetChannelMessages` поле `rawBlockB64` **не добавляется** (лента канала без сырого блока, чтобы не раздувать ответ).
- `channelInfo` не содержит бинарной записи. Для полного оригинала используется существующая публичная операция `GetBlockchainBlock` (поля `blockchainName`, `blockNumber`, ответ `blockBytesB64`).
- `rawBlockB64` больше **не отправляется** в обычном `GetMessageThread` — ни для focus, ни для ancestors/descendants, что экономит трафик.
- В `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` каждое сообщение теперь содержит:
- `repliesCount` — число дочерних сообщений типа `TEXT_REPLY`;
- `ratingsCount` — число дочерних сообщений типа `TEXT_RATING`.
+5 -3
View File
@@ -103,7 +103,7 @@ Login/fork для edit не подписываются: edit может ссыл
- Такой edit трактуется как логическое удаление содержимого сообщения.
- Для удаления отдельного сообщения используется именно 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`.
@@ -127,8 +127,8 @@ Arweave-вложение:
Обязательные поля:
- `v=1`
- `nm` - имя файла, закодированное через `encodeURIComponent`
- `v=1` для исторических записей, `v=2` для новых
- `nm` - имя файла: для `v=1` старое `encodeURIComponent`, для `v=2` UTF-8 с экранированием только `%`, `<`, `>`, `=`, `;`
- `sz` - размер файла в байтах
- `sha256` - SHA-256 исходного файла в hex
@@ -151,4 +151,6 @@ Arweave-вложение:
- старые клиенты без поддержки вложений могут показывать технические строки как обычный текст;
- пустой пользовательский текст допустим, если перед ним есть хотя бы один валидный attach-блок.
В `v=2` при структурированном чтении проверяется уникальность полей, допустимость кодирования и значений. Безопасное текстовое представление и файловые URL должны дополнительно валидироваться на клиенте и сервере.
Сам файл всегда хранится вне блокчейна. В блокчейне остаются имя, размер, SHA-256 и, только для Arweave-вложения, `ar`.
+9 -7
View File
@@ -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 вложений в начале сообщения, затем обычный текст; порядок сохраняется.
## Канонический формат (2026-11)
## Канонический формат (2026-11, v=2)
```text
<S:att;v=1;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=photo.jpg;sz=248193;pr=BASE58_ROOT;mm=image/jpeg>
<S:att;v=2;nm=video.mp4;sz=15000000;pr=BASE58_ROOT;mm=video/mp4;ar=TXID>
Текст публикации
```
- `v` — версия (1).
- `nm` — имя файла в `encodeURIComponent`.
- `v` — версия: **2** для новых публикаций, старые `v=1` остаются читаемыми.
- `nm` — UTF-8 имя файла без массового URL-кодирования. В `v=2` только служебные символы кодируются однобайтовыми ASCII-последовательностями: `%`→`%25`, `;`→`%3B`, `=`→`%3D`, `<`→`%3C`, `>`→`%3E`. Управляющие символы в именах не допускаются. Фактическая нормализация клиента заменяет `\` и `/` на `_` (старое правило).
- Пример: `Водопад.mp4` записывается как `Водопад.mp4`; `Лето;фильм=1.mp4` — как `Лето%3Bфильм%3D1.mp4`.
- Парсер v=2 отвергает неизвестные и повторные ключи, неверное экранирование, ошибочный MIME, некорректную длину/идентификатор. Сервер/импортёр не должны доверять метаданным клиента и обязаны проверять формат при структурированном чтении. Блокчейн и исходный `text` хранятся побайтово неизменными.
- `sz` — размер подготовленных байтов в десятичном виде.
- `pr` — **BitTorrent v2 Pieces Root (32 байта), Base58**, не SHA-256 целого файла; текущий стандарт новых вложений.
- `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` не входят в протокол.
+5
View File
@@ -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
- Для создания блока `TECH_CREATE_CHANNEL (type=0/subType=1/version=1)` введён протокольный минимум `channelName`: **4 символа**; максимум остаётся 32.
+1 -1
View File
@@ -40,7 +40,7 @@ blockchain.sync.enabled=false
Дополнительно каждый сервер может независимо включить `ArweaveBlockSyncScheduler`.
Он ищет child DataItems по тестовому тегу `App=test5592`, проверяет их и импортирует через ту же бизнес-проверку AddBlock. Импортированные блоки не публикуются повторно.
Он ищет child DataItems по тестовому тегу `App=test5592`, проверяет их и импортирует через ту же бизнес-проверку AddBlock. Импортированные блоки не публикуются повторно. Владелец DataItem сверяется либо с актуальным Solana PDA, либо с уже проверенным локальным сертификатом бесплатной регистрации (`FREE_CERT`); для `FREE_CERT` допустима только chain `login-001` с ключом из сертификата.
Если блоки обнаружены не по порядку, persistent queue оставляет более поздние блоки pending до появления предыдущих.
+17
View File
@@ -41,6 +41,23 @@
Обычный `Enter` в поле ввода личного сообщения отправляет непустой текст через существующий обработчик формы (включая ответы и редактирование); `Shift+Enter`, `Ctrl+Enter`, `Alt+Enter` и `Meta+Enter` вставляют перенос строки. Во время композиции IME отправка по Enter отключена. Это изменение относится только к UI; формат контейнера `SHiNE_DM` и серверный API не изменяются.
### Внешние ссылки и уведомления о переводах
Обычные `http://`, `https://` и `www.` ссылки в тексте DM остаются частью обычного
текста и не меняют формат `SHiNE_DM`. При обычном нажатии UI предлагает скопировать
ссылку или открыть её во внешнем браузере; внутренние ссылки SHiNE продолжают
обрабатываться роутером приложения.
При переводе SOL/USDT собеседнику отправляется уведомление с подписью транзакции и
ссылкой на Solana Explorer. Ссылка строится с текущим кластером (`devnet` или
`mainnet-beta`), поэтому проверка открывает правильную сеть. Это также только UI-текст
DM: серверный API, подпись и бинарный контейнер не изменяются.
При открытии личного чата UI прокручивает ленту к линии непрочитанных сообщений,
если такие сообщения есть; при отсутствии непрочитанных — к последнему сообщению.
При первичной загрузке истории это правило применяется после ответа сервера, а не
только к сообщениям, уже находящимся в локальном кэше.
## Информационное сообщение о шифровании в начале DM (13.11.2026)
Экран `shine-UI/js/pages/chat-view.js` добавляет в самое начало визуальной ленты каждого личного диалога серое пояснение по центру о сквозном шифровании, ключах, открытом коде и последствиях потери пароля. Текст локализован для RU/EN через `screens.chat_view.security_notice.*`, стили — в `shine-UI/styles/features/chat.css`.
@@ -0,0 +1,43 @@
# SHiNE User PDA 1.3 — Root-signature, system limits, economy v2
## Canonical binary record
* Outer record layout and fork size **remain unchanged** from PDA 1.2; `paid_limit_bytes` remains `u32` (4 bytes) in **every fork**.
* The new `format_minor = 3`. On create every fork limit is `0`. No `additional_limit` instruction argument or paid top-up.
* `0` means **unlimited total blockchain bytes**, positive `N` means maximum `N` bytes. This does not remove per-block/request limits.
* Canonical signing preimage = **exact serialized unsigned PDA bytes**, omitting **only four quota bytes in each fork**. Keep original physical `record_len` and variable-block `payload_len` fields unchanged in the canonical preimage; changing length values would change hashes.
* `SHA256(canonical signing bytes)` is verified by an Ed25519 instruction from the Root Key. The 64-byte signature stored in PDA is **Root Key's signature**. The contract verifies signatures; it never signs for the user.
* Normal update: one root Ed25519 instruction. Full key rotation: old root Ed25519 followed by new root Ed25519; stored signature is from new root. New root/client/blockchain keys must be rotated together. Blockchain Key remains for signing user-blockchain content, not User PDA.
* Changes to on-chain limits are **not implemented** in this patch. Future privileged instruction must mutate ONLY the 4 bytes and have explicit authorization/audit. It must not permit untrusted PDA input to override the limit.
* Every new fork starts with `paid_limit_bytes = 0` (unlimited), regardless of the previous fork's limit. Historical forks retain their own values. The existing fork cooldown is retained for ordinary forks.
* `prev_record_hash` for a predecessor v1.2 is SHA256(physical v1.2 unsigned bytes). For v1.3 it is SHA256(canonical unsigned bytes without limit bytes). The first signed update migrates v1.2 -> 1.3 at the same PDA address.
* Old v1.2 accounts remain readable and usable for Stars support operations. Their record signatures follow the old v1.2 rule until the first root-authorized migration to 1.3.
## Economy PDA v2
The on-chain state contains **only** `version=2:u8` and `update_fee_lamports:u64` (9 useful bytes; old allocated space may remain padded). No registration fee or quota price in this PDA. Registration fee lives in the namespace PDA. User PDA update fee comes from this economy PDA.
For existing v1 economy PDA, the program temporarily reads the legacy state and uses the previous fixed update fee 20,000 lamports; submit the authorized `IX_UPDATE_USERS_ECONOMY_CONFIG` with **only** 8-byte LE `update_fee_lamports` to migrate the existing economy PDA to v2. Its PDA address does not change.
## Wire changes
* `IX_CREATE_USER_PDA(3)`: removed `additional_limit:u64` after `created_at_ms`.
* `IX_UPDATE_USER_PDA(4)`: removed `additional_limit:u64` after `updated_at_ms`; retained `auth_mode:u8` with **only 1 (root)** supported. The normal update requires the old root; rotation requires both old/new root signatures.
* `IX_UPDATE_USERS_ECONOMY_CONFIG(2)`: now **only** `update_fee_lamports:u64`; same authority and account list as v1.
## Server
* Keep `size_limit=0` in runtime `blockchain_state_store` as unlimited, and `size_limit>0` as the active block-size total quota.
* Both the optimistic handler check and the atomic SQL file-size update must treat zero as unlimited.
* Synchronize limits for all historical forks from `solana_user_pda_current` into existing runtime blockchain states without resetting tips, size, or key material; use current fork value when accepting a block. If a valid free user has no Solana PDA yet, default to 0.
* Limit mutation is not yet exposed; future change will require sync by slot/signature even without a changed `record_number`.
## Deployment order
1. Deploy server and client handling v1.2 + 1.3, economy v2 and zero-unlimited semantics together.
2. Upgrade Solana `shine_users` program with the existing Program ID using authorized upgrade procedures; do **not** rotate seeds or PDA addresses.
3. Migrate economy PDA v1 -> v2 through the authorized update instruction (default 20,000 lamports or chosen value).
4. Create a new v1.3 account and verify stored root signature, first zero quota, added blocks >100 KB, Stars support, old v1.2 read, first v1.2 -> v1.3 root migration.
5. Test full root/client/blockchain rotation requiring signatures from **both roots**, old fork read, and paid namespace creation.
Deployment and live signed chain transactions have **not** been performed by this source patch.
+3 -1
View File
@@ -139,7 +139,9 @@
Исходное сообщение остаётся наверху, ниже — счётчик и ответы в последовательном порядке. Не предлагать «Популярные» до подтверждения алгоритма и источника данных.
Для вложенных ответов показывать «В ответ …» и короткий контекст. Не уменьшать ширину текстовой колонки бесконечными отступами: после одного уровня показывать связь подписью или открывать подветку, используя имеющуюся маршрутизацию. Тонкая линия допустима только для обозначения реальной связи, не вокруг каждого комментария. Плотность ответов сохраняется близкой к Ночному SHiNE; выбор полноэкранного редактора из Клуба не означает переноса всей его плотности.
Шапка автора — отдельная компактная полоса: фотография, отображаемые имя и фамилия, затем логин и относительное время без знака минус. Нажатие на шапку не уводит со страницы сразу, а открывает меню с действием «Показать профиль».
Прямые ответы исходному сообщению показываются отдельными блоками, разделёнными тонкой линией. Внутри блока виден только один вложенный уровень: не более двух комментариев сразу, остальные раскрываются кнопкой «Показать ещё». Более глубокие ответы не добавляются в этот блок; их можно открыть как отдельную подветку выбранного комментария. На карточке комментария счётчик означает только число его прямых ответов. Для вложенных ответов показывать «В ответ …» и короткий контекст. Не уменьшать ширину текстовой колонки бесконечными отступами. Тонкая линия допустима только для обозначения реальной связи, не вокруг каждого комментария. Плотность ответов сохраняется близкой к Ночному SHiNE; выбор полноэкранного редактора из Клуба не означает переноса всей его плотности.
Возврат ведёт в тот же канал и на прежнюю позицию. После отправки новый ответ появляется в ветке; при ошибке остаются текст и вложения. Длинные ветки потребуют отдельной проверки пагинации, состояния загрузки и перехода к конкретному ответу.
+7
View File
@@ -103,3 +103,10 @@ await confirmDialog({
Английские формулировки являются первым черновым переводом и требуют редакторской вычитки. Часть русских строк в служебном коде и отдельных нестандартных сценариях остаётся вне словарей; данные пользователей и протокольные значения переводить нельзя. При отсутствии ключа сохраняется русский fallback.
Проверка `node --test shine-UI/tests/i18n-completeness.test.mjs` требует одинаковых ключей и параметров в двух словарях и проверяет статические обращения `t()`/`th()` в JavaScript. После правок запускать также весь набор `node --test shine-UI/tests/*.test.mjs`, проверку синтаксиса JS и `python3 scripts/check_docs.py`.
## Пароль и генерация ключей в регистрации и входе (21.11.2026)
- На экране регистрации показывается разъяснение, что логин и пароль используются для локальной генерации криптографических ключей, а сервер не хранит пароль или приватные ключи. Пользователю рекомендуются 12–16+ символов или длинная парольная фраза. В тестовом периоде обязательный минимум **1 символ**, максимум **256**. Счётчик символов (`N / 256`) находится **только на регистрации**.
- Для ввода пароля и при регистрации, и при входе используется расширяющееся поле до **трёх строк** (дальше прокрутка), по умолчанию видимое. В каждой строке на достаточно широком экране помещается **32 моноширинных символа**, на узких экранах длина строки адаптивна (приоритет — читаемость и отсутствие горизонтального выхода за экран). Автоматический перенос визуальный и не вставляет `\n` в пароль. Кнопка-глаз скрывает содержимое даже в многострочном поле; обычный Enter отправляет форму, Shift+Enter вставляет перенос строки. Перенос строки, введённый вручную, является частью пароля и влияет на ключи. После успешной генерации ключей при регистрации и после успешной авторизации при входе видимое поле сразу очищается, включая маску (секрет для следующих шагов регистрации остаётся в оперативном состоянии до окончания процесса). При возврате на шаг пароля ранее введённое значение не подставляется обратно.
- Пока вычисляются ключи, оба экрана используют один экран ожидания с анимацией и подписями «Генерируем ваши цифровые ключи…» / «Генерируем их из вашего логина и пароля непосредственно на этом устройстве.». Проценты и индикатор хода работы **не показываются**; алгоритмы получения ключей и запросы API не изменены.
- Подписи находятся в словарях `ru.json` и `en.json` (`components.secret_generation_overlay.*`, `screens.register_view.*`).
+5 -2
View File
@@ -45,13 +45,16 @@
`shine-network-explorer-v3`. Запись хранит ответ `getUserConnectionsGraph`,
идентификатор сервера/аккаунта/логина и отметку времени. Время жизни — 24 часа;
просроченное повторно запрашивается при обращении, а просроченные рёбра исключаются
из исследованного графа. При открытии страницы до 1000 свежих изученных графов
из исследованного графа. При переключении версий внутри уже открытой вкладки до 1000 свежих изученных графов
восстанавливаются без сетевых запросов; память ограничена 800 горячими записями.
Если IndexedDB недоступен, работает временное кэширование в памяти.
Пока вкладка V3 открыта, раз в пять минут проверяется актуальность выбранного центра.
Подтверждённое изменение дружеских связей через UI также сбрасывает кэш V3, если
этот экран открыт. Операция очистки инвалидирует незавершённые загрузки.
этот экран открыт. Операция очистки инвалидирует незавершённые загрузки. **При каждом нажатии нижней
кнопки «Связи»** исследованный граф V3/V4, координаты и IndexedDB-кэш графа
сбрасываются, центр снова — собственный пользователь; X2 и фильтры выключены.
При смене V3 ↔ V4 внутри открытого экрана сброса нет. Кэш изображений не затрагивается.
## Проверка
+90
View File
@@ -0,0 +1,90 @@
# Связи V4 — статический Canvas 2D
Вводится отдельный вариант **V4 · Canvas** в селекторе версий «Связи». V1, V2 и V3 остаются доступны.
Ни сервер, ни API, ни блокчейн не меняются.
## Данные и управление
V4 использует ту же страницу `network-explorer/network-view.js` через `renderExplorer(context, { canvas: true })`:
передача `graph-model.js`, кэш IndexedDB, загрузка X2, глубина 0–4, фильтры «Близкие»/«Сияющие»,
поиск, сброс кэша и хранение координат являются общими для V3 и V4. Если пользователь перемещает
узел, координаты сохраняются точно так же, как в V3. Разрешено перерисовать весь граф при приходе
новых данных; перерасчёт модели не превращается в бесконечную анимацию.
V4 поддерживает мышь/сенсорный экран: перетаскивание сцены и узлов, масштабирование колесом
и щипком, короткое и долгое нажатие, контекстное меню правой кнопкой. Групповое перетаскивание
исторических центров из общего движка V1 для модели V3 не применяется.
`ZOOM_MIN = 0.55`, `ZOOM_MAX = 2.2`, `DIVE_ZOOM = 1.7`. Параметр `DIVE_ZOOM`
используется в методе `recenter` движка; обычный выбор пользователя, как и V3, обрабатывается
страницей с обновлением центра исследуемой сети.
## Рисование
- Слой №1 Canvas — связи; слой №2 — сияние, аватары, значки официальных пользователей, подписи.
- Для каждой вершины изображение собирается в спрайт: внешняя стеклянная кромка V3
(`/assets/glass_overlay_faithful.png`) рисуется под круглой **непрозрачной** фотографией/инициалами.
Дополнительных цветных ободков V2 нет. Непрозрачная подложка под кромкой закрывает концы линий.
- У сияющих есть **статическая** аура. Фотография остаётся поверх стекла и сияния;
типы отношений кодируются цветами самих связей.
- Подписи V2: округлая полупрозрачная плашка, компактное «Имя Ф.» (кроме центра),
приоритет важных узлов, проверка пересечений и перенос плашки над узлом при необходимости.
- Взаимная связь со встречными разными типами получает градиент от первого цвета ко второму.
Для односторонней связи яркость плавно падает в сторону адресата.
- Между двумя сияющими пользователями рисуется трёхслойный неон V3 на кривой:
размытое поле, размытая трубка и светлая сердцевина. Для остальных пар — тонкая
двухпроходная цветная линия. Односторонние сияющие линии сохраняют статичный пунктир V3.
Пульсация и бегущие штрихи отсутствуют.
- **Все вершины направляются на отрисовку**, даже если они за кадром. Для читабельности
пересекающиеся текстовые плашки могут пропускаться. Связи также не отсекаются по viewport.
- Спрайты повторно используются при движении карты и пересоздаются только при изменении фото,
вида/разрешения или темы. Размер кэшированных спрайтов подстраивается под zoom и DPR,
а общий расчётный бюджет изображений ограничен примерно 96 МБ.
- После завершения ввода, загрузки изображений и пакетного построения спрайтов `requestAnimationFrame`
больше не запрашивается; в состоянии покоя расхода кадров на эффекты нет.
- В V4 старый анимированный псевдо-фон `.fg-stage::before` отключён; фон остаётся статичным.
## Повторное открытие вкладки «Связи»
Каждое нажатие **нижней кнопки «Связи»** сбрасывает исследованный граф V3/V4:
очищает графы в памяти и в IndexedDB, забывает раскрытые ветви и координаты, возвращает
к собственному профилю, отключает X2 и дополнительные фильтры. После окончания
очистки загружаются собственные непосредственные связи. Новый запрос ждёт завершения
очистки — старые данные не восстанавливаются наперегонки из IndexedDB.
Переключение версий V1/V2/V3/V4 в селекторе внутри открытого экрана **не** сбрасывает
исследованный граф. Кэш изображений браузера, фотографии и другие данные приложения не стираются.
Верхнее меню «Очистить кэш» остаётся отдельным действием внутри уже открытой карты.
## Файлы
- `shine-UI/js/pages/network-canvas-v4/graph-renderer.js` — рендер и жесты.
- `shine-UI/js/pages/network-canvas-v4/graph-style.js` — палитры и геометрия направленных линий.
- `shine-UI/js/pages/network-canvas-v4/network-view.js` — адаптер страницы V4.
- `shine-UI/js/pages/network-explorer/network-view.js` — общая страница V3/V4.
- `shine-UI/js/pages/network-version-switcher.js` — выбор V4 и обработчик входа во вкладку.
- `shine-UI/js/components/toolbar.js` — сигнал повторного входа по нижней кнопке.
- `shine-UI/index.html` — обновлённый build hash загрузки UI.
- `shine-UI/styles/features/network.css` — Canvas-слои, выключение старой анимации.
- `shine-UI/tests/network-explorer-v4.test.mjs` — проверки градиентов, затухания, геометрии и модели.
## Проверка и ограничения
Команды в корне репозитория:
```bash
node --test shine-UI/tests/network-explorer-v3.test.mjs shine-UI/tests/network-explorer-v4.test.mjs
```
Базовые тесты проверяют градиенты и затухание линий, геометрию и BFS-модель, а также
инварианты порядка рисования стекла/фото, стиля неона/подписей и механизма сброса вкладки.
Они не заменяют полноценный браузерный тест страницы с авторизацией и реальными запросами к серверу.
Для финальной проверки на устройстве стоит сравнить FPS/память V3 и V4 на одном исследованном графе,
проверить фото из Arweave и R2, долгий тап и пересечения подписей на узком экране.
### Canvas V4c — стекло и неон как в V3 (19.11.2026)
- Цветные красно-синие кольца аватаров удалены. Возвращена стеклянная PNG-кромка V3 (`glass_overlay_faithful.png`, 119% размера узла).
- Фото/инициалы рисуются **после** стекла, непрозрачно, поверх бликов; диск под стеклом закрывает окончания линий нижнего Canvas. Сияющие ауры остались статичными.
- Сияющие связи рисуются в стиле V3: поле 16px с размытием 6px, трубка 6px с размытием 2px и тонкое светлое ядро 2px, всё с `screen`-композитингом. Blur выполняется один раз для слоя всех связей. Сине-красные градиенты и затухание односторонних связей сохранены.
- Система подписей V2, масштаб 0.55–2.2 и сброс исследованной карты при входе в «Связи» без изменений. Никаких пульсаций и фоновых циклов рендера.
+1
View File
@@ -10,6 +10,7 @@
- [Поддержка SHiNE в меню кошельков](WALLET_SHINE_SUPPORT.md) — отдельный пункт пожертвования, старые экраны кошельков и билетов.
- [Локализация UI (этап 1)](I18N.md) — языковой движок, приоритет системного языка и глобальные настройки.
- [Связи V3: исследование графа](NETWORK_EXPLORER_V3.md) — BFS-глубина, X2, размеры аватарок, кэш 24 часа.
- [Связи V4: Canvas](NETWORK_EXPLORER_V4.md) — та же логика V3, аватары и подписи V2, статичная аура и неоновые линии.
- [PWA: масштабирование и аватар профиля](PWA_VIEWPORT_AND_AVATAR_PREVIEW.md) — поведение полноэкранного интерфейса и просмотра фотографии.
- [Заявления о статусах и предупреждения о блокчейне](PROFILE_DECLARATIONS_AND_CONSENT.md) — действующие сценарии профиля, лайков и подтверждений на 06.11.2026.
@@ -4,7 +4,8 @@
## Конфигурация
- `freeRegistration.enabled=false` по умолчанию. Включается только на тестовом сервере после проверки соответствия namespace.
- `freeRegistration.enabled=false` по умолчанию. Для включения обязательно одновременно задать `freeRegistration.namespace=<namespace>`: это единственный type-2 namespace, в котором данный сервер выдаёт бесплатные аккаунты. Если namespace не задан или `enabled=false`, сервер публикует только платные namespace и не показывает в UI вариант бесплатной регистрации.
- При включении сервер до начала работы сверяет, что указанный namespace имеет type 2, его `default_server_login` совпадает с `server.SHiNE.login`, а `registrar_pubkey` — с публичным ключом из seed. При несовпадении запуск прекращается; чужой namespace нельзя случайно обслужить.
- `freeRegistration.registrarSeedFile` — абсолютный путь к файлу вне Git, внутри одна Base64-строка **32-byte Ed25519 seed**. Пример имени `/var/lib/shine/secrets/registrar-seed.b64`; не создавать файл с тестовым ключом внутри репозитория.
- `LocalRegistrarSigner.fromConfig(AppConfig)` проверяет enabled и наличие пути, не печатает секрет или bytes в лог.
- Публичный ключ signer должен совпадать с `shine_namespace_current.registrar_pubkey` (из on-chain namespace), иначе `FreeRegistrationIssuer.issue` отказывает.
@@ -13,7 +13,7 @@
| `ConfirmFreeRegistration` | `challengeId,code` (случайный шестизначный код из письма) | `fullLogin,dataItemId,publicationStatus,chainConfirmed:false` | выпуск+Turbo ACK+локальный импорт |
| `GetRegistrationStatus` | `fullLogin` | `registrationStatus,dataItemId,publicationStatus`; для FREE_CERT дополнительно `innerSignature64B64,rootPublicKey,blockchainPublicKey,clientPublicKey,defaultServerLogin` | retry/upgrade |
`registrationFeeLamports` — строка десятичного целого u64. `currencyCode` — числовой код: `1` = SOL; `2` зарезервирован, сервер не принимает его до реализации USDT. Сервер отдаёт актуальный кэш namespace после sync Solana, UI перед платной транзакцией дополнительно читает значение напрямую из Solana. Публичные ключи запроса — Base64 от ровно 32 байт (не PKCS#8). `innerSignature64B64` — Base64 внутренней подписи Ed25519, публичная информация сертификата; PRIVATE-ключ регистратора никогда не отдаётся.
`registrationFeeLamports` — строка десятичного целого u64. `currencyCode` — числовой код: `1` = SOL; `2` зарезервирован, сервер не принимает его до реализации USDT. Сервер отдаёт актуальный кэш namespace после sync Solana, UI перед платной транзакцией дополнительно читает значение напрямую из Solana. `GetNamespaces` всегда содержит платные namespace и содержит type-2 namespace только когда на этом access-сервере явно включён и проверен `freeRegistration.namespace`; другие type-2 namespace не возвращаются и не принимаются в `CheckRegistrationLogin`. Публичные ключи запроса — Base64 от ровно 32 байт (не PKCS#8). `innerSignature64B64` — Base64 внутренней подписи Ed25519, публичная информация сертификата; PRIVATE-ключ регистратора никогда не отдаётся.
**Ошибки:** `REGISTRATION_UNAVAILABLE` 503, `INVALID_REGISTRATION_INPUT` 400, `REGISTRATION_CONFLICT` 409, `RATE_LIMITED` 429, прочие 500 требуют анализа логов без раскрытия секретов. Проверка логина и email *не резервирует* их; перед подписью и перед импортом делается повторная проверка.
@@ -35,3 +35,9 @@ payload = identity_fields || inner_signature64 || email_sha256:32
Детерминированные фикстуры: `shine-solana/shine/tests/fixtures/registration-v2.json` (в том числе ранее подписанный ANS-104 DataItem с историческим `App=test5591`, его ID и подписи). Этот вектор сохранён **исключительно для проверки криптографического формата**, он НЕ является актуальным тегом выпуска. Актуальный `App=test5592` проверяется выпуском нового сертификата через Java `FreeRegistrationCertificateV1Check`. Векторные ключи предназначены только для тестов. Java-подписание и проверка сертификата присутствуют в этапе 7; загрузка через Turbo и доверенный импорт — этап 8.
Адрес PDA при upgrade вычисляется от **ASCII lowercase** полного логина, но строка логина в сертификате, его подпись и поле `login` в PDA остаются в исходном регистре. Пароль/Argon2id также используют lowercase полного логина.
Исходное написание — это отображаемое зарегистрированное имя. Runtime-идентификаторы
(`normalized_login`, `blockchain_name`, ключи `blocks_store` и `blockchain_state_store`)
используют ASCII lowercase. Поэтому уже выпущенные сертификаты с заглавными буквами
остаются валидными: сервер не меняет их подписанные байты, а приводит к lowercase
только несигнатурные ключи хранения и поиска.
+1 -1
View File
@@ -39,7 +39,7 @@
}());
</script>
<script>
window.__SHINE_BUILD_HASH__ = '20261117-jupiter-swap-beta-v1';
window.__SHINE_BUILD_HASH__ = '20261119-graph-v4c';
window.__SHINE_CLIENT_VERSION__ = '1.20.9';
</script>
<script>
+1 -1
View File
@@ -137,7 +137,7 @@ import * as channelDonateView from './pages/channel-donate-view.js';
import * as channelThreadView from './pages/channel-thread-view.js';
import * as addChannelView from './pages/add-channel-view.js';
import * as addPersonalPublicChatView from './pages/add-personal-public-chat-view.js';
import * as networkView from './pages/network-version-switcher.js?v=202610170100';
import * as networkView from './pages/network-version-switcher.js?v=20261119-graph-v4b';
import * as notificationsView from './pages/notifications-view.js?v=202610130400';
const CONVERSATION_CLEAR_NOTICE_TEXT = 'История переписки очищена с этого места';
@@ -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();
}
+5 -1
View File
@@ -10,5 +10,9 @@ export function attachMessageMenu(card, head, items) {
trigger.setAttribute('aria-label', t('screens.message_menu.text_001'));
head.append(trigger);
const menu = createDropdownMenu({ anchorEl: trigger, items });
card.cleanup = () => menu.destroy();
const previousCleanup = card.cleanup;
card.cleanup = () => {
previousCleanup?.();
menu.destroy();
};
}
@@ -0,0 +1,33 @@
import { t } from '../i18n/index.js';
/** Общий экран ожидания локальной генерации ключей. Без ложного процента выполнения. */
export function createSecretGenerationOverlay() {
const overlay = document.createElement('div');
overlay.className = 'secret-generation-overlay';
overlay.hidden = true;
overlay.setAttribute('role', 'status');
overlay.setAttribute('aria-live', 'polite');
const card = document.createElement('div');
card.className = 'secret-generation-card stack';
const spinner = document.createElement('div');
spinner.className = 'secret-generation-spinner';
spinner.setAttribute('aria-hidden', 'true');
const title = document.createElement('div');
title.className = 'secret-generation-title';
title.textContent = t('components.secret_generation_overlay.title');
const description = document.createElement('p');
description.className = 'secret-generation-description';
description.textContent = t('components.secret_generation_overlay.description');
card.append(spinner, title, description);
overlay.append(card);
return {
overlay,
show() { overlay.hidden = false; },
hide() { overlay.hidden = true; },
};
}
+7
View File
@@ -154,6 +154,13 @@ export function renderToolbar(currentPageId, navigate) {
if (isNotifications) renderBadge(btn, counters.notificationsUnreadCount, t('screens.toolbar.text_014'), 'notification-toolbar-badge');
if (item.pageId === 'channels-list') {
btn.addEventListener('click', () => navigate('channels-list'));
} else if (isNetwork) {
btn.addEventListener('click', () => {
// Каждый вход через основную вкладку начинает новое исследование сети.
// Переключение между V1–V4 внутри вкладки этот сброс не вызывает.
if (state.session.isAuthorized) window.dispatchEvent(new Event('shine:network-tab-enter'));
navigateWithGuestRules(item.pageId, navigate);
});
} else {
btn.addEventListener('click', () => navigateWithGuestRules(item.pageId, navigate));
}
@@ -1,30 +1,101 @@
import { t } from '../i18n/index.js';
import { iconHtml } from './ui-icon.js';
/** The password is intentionally visible initially on both auth screens. */
/**
* Native password inputs are single-line only. A textarea allows long phrases to
* wrap across up to three lines. Masking uses a non-interactive bullet mirror so
* it also works in browsers without CSS text-security support.
*/
export function createExpandablePasswordTextarea() {
const input = document.createElement('textarea');
input.className = 'input auth-password-field__textarea';
input.rows = 1;
// 32 visible monospace characters per line on screens wide enough.
// Soft wrap only: never add newline characters to the actual password.
input.cols = 32;
input.wrap = 'soft';
input.autocapitalize = 'off';
input.spellcheck = false;
input.setAttribute('autocorrect', 'off');
const resize = () => {
const computed = window.getComputedStyle(input);
const lineHeight = Number.parseFloat(computed.lineHeight) || 24;
const extras = (Number.parseFloat(computed.paddingTop) || 0)
+ (Number.parseFloat(computed.paddingBottom) || 0)
+ (Number.parseFloat(computed.borderTopWidth) || 0)
+ (Number.parseFloat(computed.borderBottomWidth) || 0);
input.style.height = `${lineHeight + extras}px`;
input.style.height = `${Math.min(input.scrollHeight, 3 * lineHeight + extras)}px`;
};
input.addEventListener('input', resize);
// Initial value may be restored from a registration draft before mounting.
input.resizePasswordField = resize;
input.clearPasswordField = () => {
input.value = '';
input.updatePasswordMask?.();
resize();
};
return input;
}
/** Passwords are deliberately visible initially on registration and sign-in. */
export function createVisiblePasswordField(input) {
input.type = 'text';
const multiline = input.tagName === 'TEXTAREA';
if (!multiline) input.type = 'text';
const wrap = document.createElement('div');
wrap.className = 'auth-password-field';
wrap.className = multiline ? 'auth-password-field auth-password-field--multiline' : 'auth-password-field';
let mask = null;
let visible = true;
if (multiline) {
mask = document.createElement('div');
mask.className = 'auth-password-field__mask';
mask.setAttribute('aria-hidden', 'true');
mask.hidden = true;
const updateMask = () => {
// Preserve explicit line breaks while not copying actual password text.
mask.textContent = Array.from(input.value, char => char === '\n' ? '\n' : '•').join('');
mask.scrollTop = input.scrollTop;
mask.scrollLeft = input.scrollLeft;
};
input.addEventListener('input', updateMask);
input.addEventListener('scroll', () => {
mask.scrollTop = input.scrollTop;
mask.scrollLeft = input.scrollLeft;
});
input.updatePasswordMask = updateMask;
}
const toggle = document.createElement('button');
toggle.type = 'button';
toggle.className = 'auth-password-field__toggle';
function updateToggle() {
const visible = input.type !== 'password';
toggle.innerHTML = iconHtml(visible ? 'eyeOff' : 'eye', false, 'key-toggle-icon');
toggle.setAttribute('aria-label', visible ? t('screens.visible_password_field.text_001') : t('screens.visible_password_field.text_002'));
toggle.setAttribute('title', visible ? t('screens.visible_password_field.text_003') : t('screens.visible_password_field.text_004'));
toggle.setAttribute('aria-pressed', String(!visible));
const isVisible = multiline ? visible : input.type !== 'password';
toggle.innerHTML = iconHtml(isVisible ? 'eyeOff' : 'eye', false, 'key-toggle-icon');
toggle.setAttribute('aria-label', isVisible ? t('screens.visible_password_field.text_001') : t('screens.visible_password_field.text_002'));
toggle.setAttribute('title', isVisible ? t('screens.visible_password_field.text_003') : t('screens.visible_password_field.text_004'));
toggle.setAttribute('aria-pressed', String(!isVisible));
}
toggle.addEventListener('click', () => {
const start = input.selectionStart;
const end = input.selectionEnd;
input.type = input.type === 'password' ? 'text' : 'password';
if (multiline) {
visible = !visible;
wrap.classList.toggle('auth-password-field--masked', !visible);
mask.hidden = visible;
input.updatePasswordMask();
input.resizePasswordField();
} else {
input.type = input.type === 'password' ? 'text' : 'password';
}
updateToggle();
input.focus();
try { if (start !== null && end !== null) input.setSelectionRange(start, end); } catch { /* unsupported input method */ }
});
updateToggle();
wrap.append(input, toggle);
wrap.append(input);
if (mask) wrap.append(mask);
wrap.append(toggle);
return wrap;
}
+69 -9
View File
@@ -22,11 +22,23 @@
"notice_failed": "Transfer succeeded, but notification failed",
"dm_prefix": "💸 You have received a transfer:",
"dm_signature": "Solana transaction",
"dm_explorer": "Check in Solana Explorer",
"balance_unavailable": "USDT balance unavailable",
"test_mint_missing": "Token is not configured on Devnet",
"devnet_disclaimer": "Official USDT does not exist on Devnet. Testing requires a separate 6-decimal SPL token.",
"jupiter_external": "Swap on Jupiter ↗",
"jupiter_warning": "Jupiter opens externally. Your built-in SHiNE wallet is not automatically connected; swapping requires an external compatible wallet. Real USDT swaps are unavailable on Devnet."
"jupiter_warning": "Jupiter opens externally. Your built-in SHiNE wallet is not automatically connected; swapping requires an external compatible wallet. Real USDT swaps are unavailable on Devnet.",
"uncertain": "Transfer status is uncertain; it may have succeeded. Check Solana history before sending again.",
"receive_hint": "This address receives SOL and USDT on Solana. Do not send tokens from other blockchains."
},
"chat_links": {
"title": "External link",
"description": "Choose what to do with this internet link.",
"copy": "Copy link",
"open": "Open in browser",
"cancel": "Cancel",
"copied": "Link copied",
"copy_failed": "Could not copy the link"
},
"language": {
"menu": "Language / Language",
@@ -999,6 +1011,9 @@
}
}
},
"components": {
"secret_generation_overlay": {"title": "Generating your digital keys…", "description": "Generating them from your login and password directly on this device."}
},
"screens": {
"dm_attachments": {
"text_001": "Download",
@@ -1531,7 +1546,7 @@
"text_018": "There's no namespace available yet.",
"text_019": "In a free account, password change is not available. After switching to a full account, it will be possible to change it.",
"text_016": "Create a password",
"text_017": "On your device, cryptographic access keys are created from the username and password. Private keys are not stored on the server.",
"text_017": "Your password is the foundation of your digital keys.",
"text_022": "Your username changed. Press “Continue” again.",
"text_023": "That login's already taken. Try another one.",
"text_015": "This name will remain forever and will be displayed exactly as you choose now. You can't change it later.",
@@ -1546,11 +1561,12 @@
"text_030": "Minimum login length: {value1} characters.",
"text_031": "Password (from 1 to {value1} characters)",
"text_032": "Enter a password between 1 and {value1} characters.",
"text_034": "The best password is the one you remember.",
"text_037": "Don't lose your password!",
"text_038": "We cannot recover it or your keys. If access to keys on all devices is lost, encrypted personal correspondence may not be available.",
"text_035": "Any non-empty password will do. For reliability, it is better to choose your long phrase or random code. Do not use known quotes or obvious sequences.",
"text_036": "On a familiar device, you usually do not have to enter a password every time you sign in: work keys are stored locally. To sign in from a new device, the password is your backup access method.",
"text_034": "🔐 Your password is your digital key",
"text_037": "🔒 Your keys belong to you alone.",
"text_038": "Our server does not store your password or private keys and cannot recover them. If you lose your password, access to your keys and encrypted conversations will be lost forever. Keep your password somewhere safe!",
"text_035": "Private cryptographic keys are generated from your username and password directly on your device. They are stored only on your devices and provide access to your account, private messages, and digital wallets.",
"text_036": "Choose a strong password: we recommend 12–16 characters or more. You can use a long, memorable phrase combining words, numbers, and special characters.",
"password_counter": "Characters: {value1} / {value2}",
"text_039": "Warning: The wallet is already full. Changing your login or password will create a different wallet! The funds will remain at the old address, and the old password will be required to access them. Continue?"
},
"network_view": {
@@ -2203,7 +2219,9 @@
"text_066": "Subscribed",
"text_067": "Subscribed.",
"text_070": "Signed.",
"text_071": "Category of notifications"
"text_071": "Category of notifications",
"text_072": "Add close friend in return",
"text_073": "You are close friends now"
},
"user_profile_list_view": {
"text_002": "Message",
@@ -2915,7 +2933,8 @@
"text_303": "When the current queue limit is filled, a new limit with a lower coefficient will open.",
"text_300": "Tickets are tied to queue 1 and the recipient’s address you specify when you purchase.",
"text_301": "The payment is considered in USD, and the write-off goes to SOL at the USDT/SOL rate, which is checked at the time of the transaction.",
"text_305": "Refresh balance"
"text_305": "Refresh balance",
"unlimited": "Unlimited"
},
"device_view": {
"text_008": "Are you sure you want to close the other sessions?",
@@ -4685,6 +4704,9 @@
},
"app": {
"error_sent_to_server_login_time": "Error sent to server · {login} · {time}",
"error_report_pending": "Sending error report…",
"error_report_received": "Error report received · {id}",
"error_report_not_sent": "Could not send error report",
"message_from_login": "Message from {login}",
"connecting": "Connecting…",
"connecting_tap_to_retry_now": "Connecting… Tap to retry now",
@@ -4843,5 +4865,43 @@
"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_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."
}
}
+79 -19
View File
@@ -22,11 +22,23 @@
"notice_failed": "Перевод выполнен, но сообщение не отправлено",
"dm_prefix": "💸 Вам отправлен перевод:",
"dm_signature": "Транзакция Solana",
"dm_explorer": "Проверить в Solana Explorer",
"balance_unavailable": "Баланс USDT недоступен",
"test_mint_missing": "Токен не настроен в Devnet",
"devnet_disclaimer": "На Devnet настоящий USDT отсутствует. Для тестирования нужен отдельный SPL-токен с 6 знаками.",
"jupiter_external": "Обменять на Jupiter ↗",
"jupiter_warning": "Jupiter откроется на внешнем сайте. Встроенный кошелёк SHiNE там не подключается автоматически: для обмена потребуется совместимый внешний кошелёк. На Devnet реального обмена USDT нет."
"jupiter_warning": "Jupiter откроется на внешнем сайте. Встроенный кошелёк SHiNE там не подключается автоматически: для обмена потребуется совместимый внешний кошелёк. На Devnet реального обмена USDT нет.",
"uncertain": "Не удалось однозначно подтвердить перевод. Он мог пройти! Проверьте историю Solana перед повторной отправкой.",
"receive_hint": "Этот адрес используется для SOL и USDT в сети Solana. Не отправляйте сюда токены из других блокчейнов."
},
"chat_links": {
"title": "Внешняя ссылка",
"description": "Выберите действие с интернет-ссылкой.",
"copy": "Скопировать ссылку",
"open": "Открыть в браузере",
"cancel": "Отмена",
"copied": "Ссылка скопирована",
"copy_failed": "Не удалось скопировать ссылку"
},
"language": {
"menu": "Язык / Language",
@@ -999,6 +1011,9 @@
}
}
},
"components": {
"secret_generation_overlay": {"title": "Генерируем ваши цифровые ключи…", "description": "Генерируем их из вашего логина и пароля непосредственно на этом устройстве."}
},
"screens": {
"dm_attachments": {
"text_001": "Скачать",
@@ -1529,7 +1544,7 @@
"text_014": "Введите логин",
"text_015": "Это имя навсегда сохранится и будет отображаться именно так, как вы выберете сейчас. Позже изменить его нельзя.",
"text_016": "Придумайте пароль",
"text_017": "На вашем устройстве из логина и пароля создаются криптографические ключи доступа. Приватные ключи не хранятся на сервере.",
"text_017": "Ваш пароль — основа ваших цифровых ключей.",
"text_018": "Пока нет доступного пространства имён",
"text_019": "В бесплатном аккаунте смена пароля недоступна. После перехода на полноценный аккаунт появится возможность его менять.",
"text_020": "Для полноценного аккаунта поддерживается смена пароля: необходимые зашифрованные сообщения перешифровываются на вашем устройстве, а не на сервере.",
@@ -1546,11 +1561,12 @@
"text_031": "Пароль (от 1 до {value1} символов)",
"text_032": "Введите пароль длиной от 1 до {value1} символов.",
"text_033": "Не удалось загрузить пространства имён: {value1}",
"text_034": "Лучший пароль — тот, который вы точно помните.",
"text_035": "Подойдёт любой непустой пароль. Для надёжности лучше выбрать свою длинную фразу или случайный код. Не используйте известные цитаты и очевидные последовательности.",
"text_036": "На привычном устройстве обычно не придётся вводить пароль при каждом входе: рабочие ключи сохраняются локально. Для входа с нового устройства пароль — ваш резервный способ доступа.",
"text_037": "Не теряйте пароль!",
"text_038": "Мы не можем восстановить его или ваши ключи. Если доступ к ключам на всех устройствах утрачен, зашифрованная личная переписка может оказаться недоступна.",
"text_034": "🔐 Ваш пароль — ваш цифровой ключ",
"text_035": "Из вашего логина и пароля прямо на устройстве генерируются приватные криптографические ключи. Они хранятся только на ваших устройствах и обеспечивают доступ к аккаунту, личной переписке и цифровым кошелькам.",
"text_036": "Придумайте надёжный пароль: рекомендуем 12–16 символов или больше. Можно использовать длинную запоминающуюся фразу со словами, цифрами и специальными символами.",
"text_037": "🔒 Ваши ключи принадлежат только вам.",
"text_038": "Наш сервер не хранит ваш пароль и приватные ключи и не может восстановить их. Если вы потеряете пароль, доступ к вашим ключам и зашифрованной переписке будет утрачен навсегда. Сохраните пароль в надёжном месте!",
"password_counter": "Символов: {value1} / {value2}",
"text_039": "Внимание: кошелёк уже пополнен. Изменение логина или пароля создаст другой кошелёк! Средства останутся на старом адресе, и для доступа к ним потребуется прежний пароль. Продолжить?"
},
"network_view": {
@@ -2336,7 +2352,9 @@
"text_068": "Подписался",
"text_069": "Подписалась",
"text_070": "Подписался(-ась)",
"text_071": "Категория уведомлений"
"text_071": "Категория уведомлений",
"text_072": "Добавить в близкие друзья в ответ",
"text_073": "Теперь вы близкие друзья"
},
"user_profile_list_view": {
"text_001": "Список",
@@ -2381,15 +2399,15 @@
},
"chat_view": {
"security_notice": {
"title": "Безопасность личной переписки",
"encryption": "Сообщения в этом чате шифруются на устройствах участников.",
"servers": "Сервер доставляет зашифрованные данные, но не должен видеть содержимое переписки.",
"derivation": "Ключи переписки производятся из ключей аккаунта и хранятся на устройствах.",
"rotation": "При смене ключей часть сообщений может потребовать повторного получения ключей.",
"source": "Перед отправкой проверьте, что вы общаетесь с нужным пользователем и сервером.",
"title": "Ваша переписка защищена сквозным шифрованием",
"encryption": "Все личные сообщения шифруются с использованием современных криптографических алгоритмов. Ключи шифрования хранятся ТОЛЬКО на устройствах участников переписки.",
"servers": "Сервера SHiNE не имеют ваших приватных ключей и даже технически никак не могут прочитать ваши сообщения.",
"derivation": "Ваш ключ шифрования высчитывается из вашего логина и пароля",
"rotation": "При смене пароля перекодирование всех ваших сообщений со старого пароля на новый происходит на устройстве пользователя.",
"source": "Код наших приложений полностью открыт и вы легко можете проверить всё это сами.",
"warning_label": "Важно:",
"warning": "не передавайте приватные ключи и пароль аккаунта другим людям.",
"recovery": "Восстановление доступа зависит от сохранённых ключей и пароля. Храните их безопасно."
"warning": "если вы забудете свой пароль, восстановить доступ к вашей зашифрованной переписке будет невозможно.",
"recovery": "SHiNE не хранит ваши секретные ключи и никак не сможет помочь вам восстановить вашу переписку"
},
"text_001": "Чат",
"text_002": "Без звука",
@@ -2734,8 +2752,8 @@
"text_006": "Ваши публикации, сообщения и лайки хранятся вечно.",
"text_007": "Начать регистрацию",
"text_008": "Сияние",
"text_009": "Ваши публикации — надолго",
"text_010": "Публичные сообщения сохраняются в децентрализованном хранилище Arweave.",
"text_009": "Ваши публикации — навечно",
"text_010": "Публичные сообщения сохраняются в децентрализованной сети «Сияние» и хранилище Arweave.",
"text_011": "Прозрачные оценки",
"text_012": "Публичные реакции и оценки можно проверять, а не просто доверять скрытым счётчикам.",
"text_013": "Настоящий социальный граф",
@@ -3101,7 +3119,8 @@
"text_302": "Если курс уезжает слишком далеко, покупка отклоняется. Для интерфейса заложен допуск 3%.",
"text_303": "Когда текущий лимит очереди заполнится, откроется новый лимит с более низким коэффициентом.",
"text_304": "Номер билета нужно сохранить отдельно: именно по нему удобно отслеживать, когда он дойдет до выплаты.",
"text_305": "Скопировать адрес в буфер обмена"
"text_305": "Скопировать адрес в буфер обмена",
"unlimited": "Без ограничений"
},
"solana_users_init_view": {
"text_001": "Подключите кошелёк и выполните init_users_economy_config.",
@@ -4685,6 +4704,9 @@
},
"app": {
"error_sent_to_server_login_time": "Ошибка отправлена на сервер · {login} · {time}",
"error_report_pending": "Отправляем отчёт об ошибке…",
"error_report_received": "Отчёт об ошибке получен · {id}",
"error_report_not_sent": "Не удалось отправить отчёт об ошибке",
"message_from_login": "Сообщение от {login}",
"connecting": "Соединяюсь…",
"connecting_tap_to_retry_now": "Соединяюсь… Нажмите, чтобы попробовать сразу",
@@ -4843,5 +4865,43 @@
"usdt_limit": "Бета-лимит: до 5 USDT за обмен. Нужен запас SOL на комиссии.",
"wallet_hint": "🧪 Тестовый обмен SOL ↔ USDT через 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 недоступна."
}
}
+8 -1
View File
@@ -482,10 +482,12 @@ export function render({navigate, chrome}) {
saved = null;
}
const savedRoot = String(saved?.rootKey || '').trim();
const savedBlockchain = String(saved?.blockchainKey || '').trim();
const savedClient = String(saved?.clientKey || '').trim();
if (savedBlockchain && savedClient) {
if (savedRoot && savedBlockchain && savedClient) {
return {
rootPrivatePkcs8B64: savedRoot,
blockchainPrivatePkcs8B64: savedBlockchain,
clientPrivatePkcs8B64: savedClient,
payerAddress: await clientAddressFromPrivatePkcs8(savedBlockchain),
@@ -513,10 +515,14 @@ export function render({navigate, chrome}) {
if (!equalBytes(derivedClientPublic, currentPda.clientKey)) {
throw new Error(t('screens.access_servers_view.text_013'));
}
if (!equalBytes(base64ToBytes(keyBundle.rootPair.publicKeyB64), currentPda.rootKey)) {
throw new Error('Root Key не соответствует PDA');
}
await authService.persistSelectedKeys(sessionLogin, storagePwd, keyBundle);
return {
rootPrivatePkcs8B64: keyBundle.rootPair.privatePkcs8B64,
blockchainPrivatePkcs8B64: keyBundle.blockchainPair.privatePkcs8B64,
clientPrivatePkcs8B64: keyBundle.clientPair.privatePkcs8B64,
payerAddress: clientAddressFromPublicB64(keyBundle.blockchainPair.publicKeyB64),
@@ -546,6 +552,7 @@ export function render({navigate, chrome}) {
const tx = await updateShineUserPdaOnSolana({
login: sessionLogin,
solanaEndpoint,
rootPrivatePkcs8B64: signingMaterial.rootPrivatePkcs8B64,
blockchainPrivatePkcs8B64: signingMaterial.blockchainPrivatePkcs8B64,
clientPrivatePkcs8B64: signingMaterial.clientPrivatePkcs8B64,
accessServers: normalizedList,
+51 -90
View File
@@ -4,6 +4,7 @@ import { formatDateTime } from '../i18n/format.js';
import { t, th } from '../i18n/index.js';
import { appendShineMessageLinks } from '../services/shine-message-links.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 { iconHtml } from '../components/ui-icon.js';
import { consumeReplyEditorOnOpen, rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js';
@@ -38,7 +39,7 @@ import {
escapeHtml,
parseMessageAttachments,
} from '../services/attachment-format.js';
import { loadProfileSnapshot } from '../services/user-profile-params.js';
import { loadProfileSnapshot, profileDisplayName } from '../services/user-profile-params.js';
import { extractLoginFromBlockchainName, formatChannelAddress, makeProfileRoute, makeShineChannelRoute, makeShineMessageRoute } from '../services/shine-routes.js';
import { parsePublicationOrdinal, publicationAtOrdinal, ordinalForPublication } from '../services/channel-message-ordinals.js';
import { dropPageData, pageDataAge, readPageData, writePageData } from '../services/page-data-cache.js';
@@ -460,56 +461,10 @@ function buildBlockchainDetails({ target, authorLogin, timestampMs, text, raw, l
msgSubType: msgSubType ?? source.msgSubType ?? '',
createdAtMs: timestampMs || source.createdAtMs || '',
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,
};
}
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) {
return firstNonEmptyText(
latestVersionText(node?.versions),
@@ -736,6 +691,17 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
if (node?.createdAtMs) timestamp.title = formatDateTime(new Date(node.createdAtMs));
authorBlock.append(title, timestamp);
authorTile.append(avatar, authorBlock);
const profileMenu = createDropdownMenu({
anchorEl: authorTile,
minWidth: 190,
dimBackground: false,
items: [{ label: t('screens.chat_view.text_004'), iconHtml: iconHtml('profile'), action: () => handlers.navigate(makeProfileRoute(author)) }],
});
authorTile.addEventListener('click', (event) => { event.stopPropagation(); profileMenu.toggle(); });
void loadThreadAvatarSnapshot(author).then((snapshot) => {
if (!loginEl.isConnected || (threadsLayout && isOwnerPost)) return;
loginEl.textContent = profileDisplayName(snapshot, author);
});
// Запись канала в обсуждении – как открытый пост в Threads: аватар и название канала в шапке, текст на всю ширину.
const threadsLayout = focusPost && (!isOwnerPost || Boolean(channel));
if (isOwnerPost) authorTile.hidden = !threadsLayout;
@@ -1009,7 +975,7 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
raw: node,
localNumber,
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() });
if (isOwnMessage) {
@@ -1057,12 +1023,8 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
if (!headRow.querySelector('.channel-message-type-button')) headRow.hidden = true;
}
card.append(actions);
authorTile.addEventListener('click', (event) => {
event.stopPropagation();
const login = String(node?.authorLogin || '').trim();
if (!login) return;
handlers.navigate(makeProfileRoute(login));
});
const priorCleanup = card.cleanup;
card.cleanup = () => { priorCleanup?.(); profileMenu.destroy(); };
return card;
}
@@ -1110,6 +1072,10 @@ function replyCountOf(node) {
return Number(node?.totalReplies ?? node?.repliesCount ?? 0);
}
function directReplyCountOf(node) {
return Number(node?.repliesCount || 0);
}
function nodeKey(node) {
return messageRefKey(buildTargetFromNode(node));
}
@@ -1132,8 +1098,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
who.type = 'button';
who.className = 'thread-comment__who';
who.setAttribute('aria-label', t('screens.channel_thread_view.text_105', { value1: author }));
who.append(identity?.avatar || renderUserAvatar({ login: author, size: nested ? 'xs' : 'sm', className: 'thread-comment__avatar avatar-plain' }));
who.addEventListener('click', () => handlers.navigate(makeProfileRoute(author)));
who.append(identity?.avatar || createThreadAvatar(author));
const main = document.createElement('div');
main.className = 'thread-comment__main';
@@ -1144,8 +1109,11 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
name.type = 'button';
name.className = 'thread-comment__name';
name.textContent = identity?.title || author;
name.addEventListener('click', () => handlers.navigate(makeProfileRoute(author)));
head.append(name);
const login = document.createElement('span');
login.className = 'thread-comment__login';
login.textContent = `@${author.replace(/^@/, '')}`;
head.append(login);
if (!identity && channelOwner && author.toLowerCase() === channelOwner.toLowerCase()) {
const badge = document.createElement('span');
badge.className = 'thread-comment__badge';
@@ -1158,6 +1126,19 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
head.append(time);
main.append(head);
const profileMenu = createDropdownMenu({
anchorEl: who,
minWidth: 190,
dimBackground: false,
items: [{ label: t('screens.chat_view.text_004'), iconHtml: iconHtml('profile'), action: () => handlers.navigate(makeProfileRoute(author)) }],
});
who.addEventListener('click', (event) => { event.stopPropagation(); profileMenu.toggle(); });
name.addEventListener('click', (event) => { event.stopPropagation(); profileMenu.toggle(); });
void loadThreadAvatarSnapshot(author).then((snapshot) => {
if (!name.isConnected || identity) return;
name.textContent = profileDisplayName(snapshot, author);
});
if (mention && parent && parent !== focus) {
const to = document.createElement('button');
to.type = 'button';
@@ -1209,7 +1190,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
commentLikeStats.setAttribute('aria-label', t('screens.channel_thread_view.text_107', { value1: likes }));
commentLikeStats.addEventListener('click', () => { void showLikeStatistics({ counts: node }); });
const replies = replyCountOf(node);
const replies = directReplyCountOf(node);
const reply = document.createElement('button');
reply.type = 'button';
reply.className = 'channel-action-item thread-comment__reply';
@@ -1229,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')); }
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 (isOwn) {
@@ -1248,7 +1229,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
} });
}
const menu = createDropdownMenu({ anchorEl: more, items: menuItems });
item.cleanup = () => menu.destroy();
item.cleanup = () => { profileMenu.destroy(); menu.destroy(); };
head.append(more);
const share = document.createElement('button');
@@ -1287,46 +1268,27 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
return item;
}
// Сколько ответов внутри ветки видно сразу; остальные – по «Ещё N ответов».
// Ветка прямого ответа: сам комментарий и не более одного вложенного уровня.
// Ответы глубже открываются как отдельное обсуждение вложенного комментария.
const THREAD_GROUP_VISIBLE_REPLIES = 2;
// Ветка ответа верхнего уровня: сам ответ и всё дерево под ним одной колонкой с линией, как в Threads.
// Ответы глубже, чем отдал сервер, открываются отдельным обсуждением этого ответа.
function renderReplyGroup(branch, { focus, channelOwner, handlers }) {
const group = document.createElement('div');
group.className = 'thread-group';
group.append(renderComment({ node: branch.node, parent: focus, focus, channelOwner, handlers }));
const nested = [];
const walk = (children, parent) => {
(Array.isArray(children) ? children : []).forEach((child) => {
if (!child?.node) return;
nested.push({ node: child.node, parent, loaded: Array.isArray(child.children) ? child.children.length : 0 });
walk(child.children, child.node);
});
};
walk(branch.children, branch.node);
const nested = (Array.isArray(branch.children) ? branch.children : [])
.filter((child) => child?.node)
.map((child) => ({ node: child.node, parent: branch.node }));
if (!nested.length) return group;
group.classList.add('has-replies');
const list = document.createElement('div');
list.className = 'thread-replies';
let previous = branch.node;
nested.forEach(({ node, parent, loaded }, index) => {
const comment = renderComment({ node, parent, focus, channelOwner, handlers, nested: true, mention: parent !== previous });
nested.forEach(({ node, parent }, index) => {
const comment = renderComment({ node, parent, focus, channelOwner, handlers, nested: true });
if (index >= THREAD_GROUP_VISIBLE_REPLIES) comment.classList.add('is-collapsed');
list.append(comment);
const unloaded = Number(node?.repliesCount || 0) - loaded;
if (unloaded > 0) {
const deeper = document.createElement('button');
deeper.type = 'button';
deeper.className = 'thread-more thread-more--deeper';
if (index >= THREAD_GROUP_VISIBLE_REPLIES) deeper.classList.add('is-collapsed');
deeper.textContent = t('screens.channel_thread_view.text_110', { value1: unloaded });
deeper.addEventListener('click', () => handlers.onOpenThread(buildTargetFromNode(node)));
list.append(deeper);
}
previous = node;
});
const hidden = nested.length - THREAD_GROUP_VISIBLE_REPLIES;
if (hidden > 0) {
@@ -1352,7 +1314,6 @@ function pluralRu(n, one, few, many) {
return many;
}
function renderDescendants(items, handlers, nextNumber, depth = 0, parent = null) {
const wrap = document.createElement('div');
wrap.className = 'stack';
@@ -1427,8 +1388,8 @@ function setThreadMuted(key, muted) {
try { localStorage.setItem(THREAD_MUTE_KEY, JSON.stringify(all)); } catch { /* приватный режим */ }
}
// Глубина дерева ответов за один запрос; что глубже – открывается обсуждением конкретного ответа.
const THREAD_LOAD_DEPTH = 8;
// Фокус, его прямые ответы и один вложенный уровень для каждой ветки.
const THREAD_LOAD_DEPTH = 2;
// Загрузка обсуждения без привязки к экрану: её же использует подгрузка заранее, по касанию записи.
async function loadThreadData(sel, cacheKey, isCurrent) {
@@ -1887,7 +1848,7 @@ export function render({ navigate, route, chrome }) {
const modalRoot = document.getElementById('modal-root');
if (!modalRoot) return;
if (modalRoot.querySelector([
'#thread-blockchain-details-modal',
'#blockchain-details-modal',
'#thread-edit-modal',
'#thread-history-modal',
'#thread-reply-modal',
+23 -56
View File
@@ -5,6 +5,7 @@ import { formatDateTime, getIntlLocale } from '../i18n/format.js';
import { t, th } from '../i18n/index.js';
import { appendShineMessageLinks } from '../services/shine-message-links.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 { iconHtml } from '../components/ui-icon.js';
import { createOverflowDots } from '../components/overflow-dots.js';
@@ -39,6 +40,7 @@ import {
softHaptic,
} from '../services/channels-ux.js';
import { renderAvatar, renderUserAvatar } from '../components/avatar-image.js';
import { createDropdownMenu } from '../components/dropdown-menu.js';
import { avatarReferenceToRenderModel, parseAvatarReference } from '../services/avatar-reference.js';
import { openChannelEditor } from '../components/channel-editor.js';
import { markArweaveAttachmentPlaced, openArweaveAttachmentManager } from '../components/arweave-attachment-manager.js';
@@ -50,7 +52,7 @@ import {
MAX_MESSAGE_ATTACHMENTS,
parseMessageAttachments,
} from '../services/attachment-format.js';
import { loadProfileSnapshot } from '../services/user-profile-params.js';
import { loadProfileSnapshot, profileDisplayName } from '../services/user-profile-params.js';
import {
extractLoginFromBlockchainName,
makeProfileRoute,
@@ -849,56 +851,10 @@ function buildBlockchainDetails({ messageRef, authorLogin, timestampMs, text, ra
msgSubType: msgSubType ?? source.msgSubType ?? '',
createdAtMs: timestampMs || source.createdAtMs || '',
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,
};
}
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) {
if (!container) return;
container.innerHTML = '';
@@ -1849,17 +1805,16 @@ function renderPostCard(post, {
const title = document.createElement('div');
title.className = 'channel-message-title author-line';
const displayNameEl = document.createElement('span');
displayNameEl.className = 'author-line-name';
displayNameEl.textContent = post.authorLogin;
const titleMain = document.createElement('div');
titleMain.className = 'author-line-main';
const loginEl = document.createElement('span');
loginEl.className = 'author-line-login';
loginEl.textContent = post.authorLogin;
const numberEl = document.createElement('span');
numberEl.className = 'author-line-num';
numberEl.textContent = `· #${post.localNumber}`;
titleMain.append(loginEl, numberEl);
title.append(titleMain);
loginEl.textContent = `@${String(post.authorLogin || '').replace(/^@/, '')}`;
titleMain.append(loginEl);
title.append(displayNameEl, titleMain);
const timestamp = document.createElement('div');
timestamp.className = 'channel-message-time';
@@ -1912,7 +1867,19 @@ function renderPostCard(post, {
event.stopPropagation();
const cleanLogin = String(post.authorLogin || '').trim();
if (!cleanLogin) return;
navigate(makeProfileRoute(cleanLogin));
profileMenu.toggle();
});
const profileMenu = createDropdownMenu({
anchorEl: authorTile,
minWidth: 190,
dimBackground: false,
items: [{ label: t('screens.chat_view.text_004'), iconHtml: iconHtml('profile'), action: () => navigate(makeProfileRoute(String(post.authorLogin || '').trim())) }],
});
const existingCleanup = card.cleanup;
card.cleanup = () => { existingCleanup?.(); profileMenu.destroy(); };
void loadMessageAvatarSnapshot(post.authorLogin).then((snapshot) => {
if (!authorTile.isConnected) return;
displayNameEl.textContent = profileDisplayName(snapshot, post.authorLogin);
});
const isOwnerPost = !!selector
@@ -2247,7 +2214,7 @@ function renderPostCard(post, {
raw: post.rawMessage,
localNumber: post.localNumber,
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() });
if (post.isOwnMessage) {
+52 -2
View File
@@ -285,6 +285,43 @@ function openChatConfirmModal({
});
}
function openExternalLinkModal(href) {
const root = document.getElementById('modal-root');
const url = String(href || '').trim();
if (!root || !/^https?:\/\//i.test(url)) return;
root.innerHTML = `
<div class="modal" id="chat-external-link-modal">
<div class="modal-card stack" role="dialog" aria-modal="true" aria-labelledby="chat-external-link-title">
<h3 class="modal-title" id="chat-external-link-title">${t('chat_links.title')}</h3>
<p class="meta-muted">${t('chat_links.description')}</p>
<p class="chat-external-link-url"></p>
<div class="form-actions-grid">
<button class="secondary-btn" type="button" id="chat-external-link-copy">${t('chat_links.copy')}</button>
<button class="primary-btn" type="button" id="chat-external-link-open">${t('chat_links.open')}</button>
<button class="secondary-btn" type="button" id="chat-external-link-cancel">${t('chat_links.cancel')}</button>
</div>
</div>
</div>
`;
root.querySelector('.chat-external-link-url').textContent = url;
const close = () => { root.innerHTML = ''; };
root.querySelector('#chat-external-link-cancel')?.addEventListener('click', close);
root.querySelector('#chat-external-link-open')?.addEventListener('click', () => {
window.open(url, '_blank', 'noopener,noreferrer');
close();
});
root.querySelector('#chat-external-link-copy')?.addEventListener('click', async () => {
try {
if (!navigator?.clipboard?.writeText) throw new Error('clipboard_unavailable');
await navigator.clipboard.writeText(url);
close();
showToast(t('chat_links.copied'), { timeoutMs: 1200 });
} catch {
showToast(t('chat_links.copy_failed'), { kind: 'error', timeoutMs: 1600 });
}
});
}
// Календарь «перейти к дате»: активны только дни, в которые была переписка.
// days – Map dayKey → { timeMs, count }; список можно обновить, пока догружается история.
// «октябрь 2026 г.» → «Октябрь 2026 г.» (CSS capitalize сделал бы «Г.»)
@@ -965,6 +1002,7 @@ function renderMessageText(textNode, messageText, chatNavigate) {
}
appendShineMessageLinks(textNode, text, {
navigate: chatNavigate,
onExternalLink: ({ href }) => openExternalLinkModal(href),
appendText: (root, part) => {
const fragment = document.createDocumentFragment();
if (appendTwemojiText(fragment, part, { className: 'chat-twemoji chat-twemoji--inline' })) {
@@ -2811,18 +2849,30 @@ export function render({ navigate, route, chrome }) {
// Вся история уже в памяти (её загрузил поиск или «Медиа и файлы») – листать сервер дальше незачем.
if (isDmHistoryFullyLoaded(chatId)) historyHasMore = false;
else if (!historyHasMore) markDmHistoryFullyLoaded(chatId);
let scrollModeAfterLoad = isBootstrap ? 'latest' : (preserveScroll ? 'preserve' : 'latest');
if (isBootstrap) {
const firstUnread = getChatMessages(chatId).find((msg) => msg?.from === 'in' && msg?.unread);
if (firstUnread?.messageKey) {
unreadSeparatorVisible = true;
unreadSeparatorAnchorMessageKey = String(firstUnread.messageKey);
stickToBottom = false;
scrollModeAfterLoad = 'unread';
}
}
// Страница уже была в памяти: перерисовка не нужна, лента не дёргается.
if (messagesBefore === JSON.stringify(getChatMessages(chatId))) {
pageAddedNothing = true;
void sendReadReceiptsForVisible(chatId);
return;
}
renderChatLog({ markAsRead: false, scrollMode: preserveScroll ? 'preserve' : 'latest' });
if (preserveScroll) {
renderChatLog({ markAsRead: false, scrollMode: scrollModeAfterLoad });
if (scrollModeAfterLoad === 'preserve') {
window.requestAnimationFrame(() => {
const nextHeight = Number(scrollContainer?.scrollHeight || 0);
scrollContainer.scrollTop = Math.max(0, prevScrollTop + (nextHeight - prevScrollHeight));
});
} else if (scrollModeAfterLoad === 'unread') {
window.requestAnimationFrame(() => scrollToUnreadSeparator(log));
} else {
window.requestAnimationFrame(() => scrollToLatestMessage(log));
}
+14 -42
View File
@@ -1,6 +1,7 @@
import { t } from '../i18n/index.js';
import { createTopBar } from '../components/topbar.js';
import { createVisiblePasswordField } from '../components/visible-password-field.js';
import { createVisiblePasswordField, createExpandablePasswordTextarea } from '../components/visible-password-field.js';
import { createSecretGenerationOverlay } from '../components/secret-generation-overlay.js';
import {
authService,
authorizeSession,
@@ -24,31 +25,6 @@ function setStatus(statusEl, message) {
statusEl.style.display = message ? '' : 'none';
}
function createSecretOverlay() {
const overlay = document.createElement('div');
overlay.className = 'secret-generation-overlay';
overlay.style.display = 'none';
const card = document.createElement('div');
card.className = 'secret-generation-card stack';
const spinner = document.createElement('div');
spinner.className = 'secret-generation-spinner';
spinner.setAttribute('aria-hidden', 'true');
const title = document.createElement('div');
title.className = 'secret-generation-title';
title.textContent = t('screens.login_password_view.text_002');
const progress = document.createElement('div');
progress.className = 'secret-generation-progress';
progress.textContent = '';
card.append(spinner, title, progress);
overlay.append(card);
return { overlay, progress };
}
export function render({ navigate }) {
const screen = document.createElement('section');
screen.className = 'stack auth-screen auth-screen--lower';
@@ -70,9 +46,7 @@ export function render({ navigate }) {
const passwordField = document.createElement('label');
passwordField.className = 'stack';
const passwordInput = document.createElement('input');
passwordInput.className = 'input';
passwordInput.type = 'text';
const passwordInput = createExpandablePasswordTextarea();
passwordInput.name = 'shine-login-password';
passwordInput.autocomplete = 'current-password';
passwordInput.autocapitalize = 'off';
@@ -96,7 +70,7 @@ export function render({ navigate }) {
actions.className = 'auth-footer-actions';
actions.append(enterButton);
const { overlay, progress } = createSecretOverlay();
const keyGeneration = createSecretGenerationOverlay();
const submit = async () => {
const currentLogin = String(state.loginDraft.login || '').trim();
@@ -131,14 +105,10 @@ export function render({ navigate }) {
return;
}
overlay.style.display = 'grid';
const keyBundle = await authService.derivePasswordKeyBundle(currentLogin, password, {
onProgress: ({ percent }) => {
const value = Math.max(0, Math.min(100, Number(percent) || 0));
progress.textContent = value > 0 && value < 100 ? `${Math.round(value)}%` : '';
},
});
overlay.style.display = 'none';
keyGeneration.show();
await new Promise(resolve => setTimeout(resolve, 40));
const keyBundle = await authService.derivePasswordKeyBundle(currentLogin, password);
keyGeneration.hide();
enterButton.textContent = t('screens.login_password_view.text_006');
const result = await authService.createAuthSession(currentLogin, keyBundle);
@@ -156,6 +126,8 @@ export function render({ navigate }) {
});
state.loginDraft.login = result.login;
state.loginDraft.password = '';
// Clear the actual textarea as soon as login succeeds, before route change.
passwordInput.clearPasswordField();
state.loginDraft.passwordMode = 'single';
state.loginDraft.passwordWords = emptyPasswordWords();
resetRegistrationFlow();
@@ -164,7 +136,7 @@ export function render({ navigate }) {
setAuthInfo(t('screens.login_password_view.text_010', { value1: result.login }));
navigate(consumeAuthReturnPage('profile-view'));
} catch (error) {
overlay.style.display = 'none';
keyGeneration.hide();
const message = toUserMessage(error, t('screens.login_password_view.text_008'));
setAuthError(message);
setStatus(status, message);
@@ -178,7 +150,7 @@ export function render({ navigate }) {
enterButton.addEventListener('click', submit);
passwordInput.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
event.preventDefault();
void submit();
}
@@ -192,9 +164,9 @@ export function render({ navigate }) {
back: { label: '←', onClick: () => navigate('login-view') },
}),
panel,
overlay,
keyGeneration.overlay,
);
window.setTimeout(() => passwordInput.focus(), 0);
window.setTimeout(() => { passwordInput.resizePasswordField(); passwordInput.focus(); }, 0);
return screen;
}
@@ -0,0 +1,582 @@
// SHiNE Explorer V4: та же модель V3, но две статические Canvas 2D-плоскости.
// В простое нет requestAnimationFrame, физики, SVG-фильтров и CSS-анимаций.
import { buildAvatarInitials } from '../../components/avatar-image.js';
import { state } from '../../state.js';
import { buildArweaveDataUrl } from '../../services/arweave-file-service.js';
import { resolvePublicFileUrl } from '../../services/public-file-service.js';
import { PALETTES, ORB_DIAMETER, clamp, rgba, color, keyOf, edgeGradient, edgeCoreGradient, geometryFor } from './graph-style.js';
export const ZOOM_MIN = 0.55;
export const ZOOM_MAX = 2.2;
export const DIVE_ZOOM = 1.7;
// V4: стеклянная внешняя кромка V3 под непрозрачной фотографией; неон V3 на Canvas.
const LONG_PRESS_MS = 480;
const DRAG_SLOP = 8;
const MAX_SPRITES_PER_FRAME = 16;
const SPRITE_MEMORY_BUDGET = 96 * 1024 * 1024;
const GLASS_URL = '/assets/glass_overlay_faithful.png';
const GLASS_SCALE = 1.19; // V3 .fg-pngorb: размер накладки 119% от узла
const PHOTO_RATIO = 0.78; // фотография 78% от стеклянного бокса, но рисуется ПОВЕРХ
const BADGE_URL = '/assets/shine-official-badge.svg?v=2';
function makeSpriteCanvas(size) {
const canvas = document.createElement('canvas');
canvas.width = size; canvas.height = size;
return canvas;
}
function loadImage(src, notify) {
const img = new Image();
img.decoding = 'async';
img.referrerPolicy = 'no-referrer';
// Не устанавливаем crossOrigin: не все внешние Arweave/R2 шлюзы возвращают CORS.
// Canvas используется только для отображения, а не для экспорта/readback.
img.onload = () => notify(true, img);
img.onerror = () => notify(false, img);
img.src = src;
return img;
}
function avatarSource(node) {
const direct = String(node.photo || '').trim();
if (direct) return direct;
if (typeof node.avatar === 'string') return node.avatar.trim();
const txId = String(node.avatar?.ar || '').trim();
if (!txId) return '';
try {
return buildArweaveDataUrl({ gateway: state?.entrySettings?.arweaveServer, txId }) || '';
} catch { return ''; }
}
export function createExplorerCanvasGraph({ stage, model, onCenterTap, onNodeTap, onNodeLongPress, onNodeMoveEnd } = {}) {
if (!stage) throw new Error('createExplorerCanvasGraph: stage обязателен');
const edgesCanvas = document.createElement('canvas');
edgesCanvas.className = 'fg-canvas-v4 fg-canvas-v4--edges';
edgesCanvas.setAttribute('aria-hidden', 'true');
const canvas = document.createElement('canvas');
canvas.className = 'fg-canvas-v4 fg-canvas-v4--nodes';
canvas.setAttribute('role', 'img');
const ectx = edgesCanvas.getContext('2d');
const ctx = canvas.getContext('2d');
if (!ectx || !ctx) throw new Error('Canvas 2D недоступен');
stage.append(edgesCanvas, canvas);
const a11y = document.createElement('div');
a11y.className = 'fg-a11y';
a11y.setAttribute('role', 'region');
stage.append(a11y);
let destroyed = false;
let nodes = [];
let nodeById = new Map();
let focusId = '';
let width = 1, height = 1, dpr = 1;
let zoom = 1, camX = 0, camY = 0;
let frame = 0;
let edgesDirty = true;
let palette = PALETTES.dark;
let spriteScale = 1;
let auraSprite = null;
const spriteCache = new Map(); // id -> { key, scale, canvas }, меняется только при смене фотографии/LOD
const photos = new Map(); // id -> { key, image, ready }
let badge = null, glass = null;
let badgeReady = false, glassReady = false;
const requestDraw = (redrawEdges = true) => {
if (redrawEdges) edgesDirty = true;
if (destroyed || frame) return;
frame = requestAnimationFrame(() => { frame = 0; if (!destroyed) draw(); });
};
badge = loadImage(BADGE_URL, (ok) => { badgeReady = ok; requestDraw(false); });
glass = loadImage(GLASS_URL, (ok) => { glassReady = ok; spriteCache.clear(); requestDraw(false); });
function setupPhoto(node) {
const id = keyOf(node.id);
const key = JSON.stringify([node.avatar || null, node.photo || '', node.login || '']);
if (photos.get(id)?.key === key) return;
const entry = { key, image: null, ready: false };
photos.set(id, entry);
spriteCache.delete(id);
let url = avatarSource(node);
if (!url && node.avatar?.pr && !node.avatar?.ar) {
void resolvePublicFileUrl({ pr: String(node.avatar.pr), authorLogin: String(node.login || '') })
.then((resolved) => { if (!destroyed && photos.get(id) === entry && resolved) start(resolved); })
.catch(() => {});
} else if (url) start(url);
function start(src) {
entry.image = loadImage(src, (ok, image) => {
if (destroyed || photos.get(id) !== entry) return;
entry.ready = ok && image.naturalWidth > 0;
spriteCache.delete(id);
requestDraw(false);
});
}
}
function makeAura() {
const c = makeSpriteCanvas(160);
const a = c.getContext('2d');
const g = a.createRadialGradient(80, 80, 15, 80, 80, 80);
g.addColorStop(0, rgba(palette.shine, .50));
g.addColorStop(.45, rgba(palette.shine, .23));
g.addColorStop(1, rgba(palette.shine, 0));
a.fillStyle = g; a.fillRect(0, 0, 160, 160);
return c;
}
function desiredSpriteScale() {
const need = Math.max(1, dpr * zoom * 1.15);
// Подготавливаем всех пользователей, поэтому масштаб также ограничен общим бюджетом памяти.
const bytesPerScale = Math.max(1, nodes.length) * (ORB_DIAMETER * GLASS_SCALE) ** 2 * 4;
const budgetScale = Math.max(1, Math.sqrt(SPRITE_MEMORY_BUDGET / bytesPerScale));
const maxScale = Math.min(8, budgetScale);
let candidate = 1;
while (candidate * 2 <= maxScale && candidate < need) candidate *= 2;
return candidate;
}
function spriteKey(node, photo) {
return JSON.stringify([node.id, node.name, node.login, photo?.key, photo?.ready, glassReady, palette === PALETTES.light]);
}
function buildSprite(node) {
const photo = photos.get(keyOf(node.id));
const key = spriteKey(node, photo);
// Единый спрайт: стеклянная кромка снизу, полностью непрозрачный аватар сверху.
// Отдельного красного/синего кольца категории НЕ рисуем.
const side = Math.max(2, Math.ceil(ORB_DIAMETER * GLASS_SCALE * spriteScale));
const sprite = makeSpriteCanvas(side);
const g = sprite.getContext('2d');
const center = side / 2;
const photoRadius = center * PHOTO_RATIO;
const diameter = photoRadius * 2;
// Непрозрачный фон между фотографией и стеклянным краем:
// неон нижнего canvas не просвечивает через стеклянную сферу.
g.fillStyle = palette.bg;
g.beginPath(); g.arc(center, center, center - .5 * spriteScale, 0, Math.PI * 2); g.fill();
if (glassReady && glass?.naturalWidth) {
g.drawImage(glass, 0, 0, side, side);
} else {
// Минимальный резервный стеклянный край, если файл пока не загрузился.
g.strokeStyle = rgba(palette.shine, .33);
g.lineWidth = Math.max(1, spriteScale * 1.2);
g.beginPath(); g.arc(center, center, center - g.lineWidth * 1.4, 0, 2 * Math.PI); g.stroke();
}
// Фото В ПОСЛЕДНЮЮ ОЧЕРЕДЬ поверх самого стекла, без затенения бликами.
g.save();
g.beginPath(); g.arc(center, center, photoRadius, 0, Math.PI * 2); g.clip();
g.fillStyle = palette.bg;
g.fillRect(center - photoRadius, center - photoRadius, diameter, diameter);
if (photo?.ready && photo.image?.naturalWidth) {
const img = photo.image;
const crop = Math.min(img.naturalWidth, img.naturalHeight);
g.drawImage(img, (img.naturalWidth - crop) / 2, (img.naturalHeight - crop) / 2,
crop, crop, center - photoRadius, center - photoRadius, diameter, diameter);
} else {
const initials = buildAvatarInitials({ login: node.login || node.id, firstName: node.name || '' });
g.fillStyle = palette.text;
g.textAlign = 'center'; g.textBaseline = 'middle';
g.font = `600 ${Math.round(side * .24)}px system-ui, sans-serif`;
g.fillText(initials, center, center, side * .58);
}
g.restore();
const result = { key, scale: spriteScale, canvas: sprite };
spriteCache.set(keyOf(node.id), result);
return result;
}
function screenPoint(node) {
return { x: width / 2 + camX + node.x * zoom, y: height / 2 + camY + node.y * zoom };
}
function nodeScreenPoint(node) {
const p = screenPoint(node);
const size = ORB_DIAMETER * (node.visualSmall ? .5 : 1) * zoom;
const box = canvas.getBoundingClientRect();
const rect = { left: box.left + p.x - size / 2, top: box.top + p.y - size / 2,
width: size, height: size, right: box.left + p.x + size / 2, bottom: box.top + p.y + size / 2 };
return { x: box.left + p.x, y: rect.top, rect };
}
// Неоновый композит из V3: мягкое размытое поле (16px / blur6),
// размытая трубка (6px / blur2), сверху чёткое светлое ядро (2px).
// Каждое размытие выполняется ОДИН раз для всех сияющих связей, а не для каждого ребра.
const flareCanvas = makeSpriteCanvas(1);
const tubeCanvas = makeSpriteCanvas(1);
const flareCtx = flareCanvas.getContext('2d');
const tubeCtx = tubeCanvas.getContext('2d');
function drawStroke(g, path, widthPx, strokeStyle, alpha, dash = null) {
g.save();
g.globalAlpha = alpha;
g.lineWidth = widthPx;
g.strokeStyle = strokeStyle;
g.lineCap = 'round';
g.lineJoin = 'round';
if (dash) g.setLineDash(dash.map((v) => v * zoom));
g.stroke(path);
g.restore();
}
function drawNormalEdge(g, path, geo, ref) {
// V3: две аккуратные нити вместо двух тяжёлых цветных полос.
const gradient = edgeGradient(g, geo, ref, palette);
const strength = clamp(Number(ref.strength) || .5, 0, 1);
drawStroke(g, path, (2.6 + strength * 1.4) * zoom, gradient, .22);
drawStroke(g, path, 1.2 * zoom, gradient, .70);
}
function edgePath(geo, shining, directed) {
const path = new Path2D();
path.moveTo(geo.x1, geo.y1);
if (shining && !directed) {
const dx = geo.x2 - geo.x1, dy = geo.y2 - geo.y1;
const perpX = -geo.uy, perpY = geo.ux;
const amp = Math.min(13, 5 + Math.hypot(dx, dy) * .05);
const bowX = geo.cpx - geo.mx, bowY = geo.cpy - geo.my;
path.bezierCurveTo(geo.x1 + dx / 3 + bowX + perpX * amp,
geo.y1 + dy / 3 + bowY + perpY * amp,
geo.x1 + dx * 2 / 3 + bowX - perpX * amp,
geo.y1 + dy * 2 / 3 + bowY - perpY * amp,
geo.x2, geo.y2);
} else path.quadraticCurveTo(geo.cpx, geo.cpy, geo.x2, geo.y2);
return path;
}
function paintEdges() {
// Вспомогательные холсты создаются один раз и переиспользуются; анимации нет.
for (const g of [flareCtx, tubeCtx]) {
g.setTransform(dpr, 0, 0, dpr, 0, 0);
g.clearRect(0, 0, width, height);
}
const origin = { x: width / 2 + camX, y: height / 2 + camY };
const shiningEdges = [];
for (const node of nodes) {
for (const ref of node.edgeParents || []) {
const parent = nodeById.get(keyOf(ref?.id));
if (!parent || parent === node) continue;
const geo = geometryFor(parent, node, zoom, origin, origin);
const shining = Boolean(node.shining && parent.shining);
const directed = ref.mutual === false;
const path = edgePath(geo, shining, directed);
if (!shining) {
drawNormalEdge(ectx, path, geo, ref);
continue;
}
shiningEdges.push({ path, geo, ref, directed });
const dash = directed ? [20, 4] : null; // V3: только направленная сияющая связь пунктирная.
drawStroke(flareCtx, path, 16 * zoom, edgeGradient(flareCtx, geo, ref, palette), .42, dash);
drawStroke(tubeCtx, path, 6 * zoom, edgeGradient(tubeCtx, geo, ref, palette), .85, dash);
}
}
if (!shiningEdges.length) return;
// screen-подсветка и двухслойное размытие соответствуют CSS .fg-plasma-* в V3.
// Нет резкой непрозрачной 14px-полосы — только светлая узкая сердцевина.
ectx.save();
ectx.globalCompositeOperation = 'screen';
ectx.filter = `blur(${(6 * zoom).toFixed(2)}px)`;
ectx.drawImage(flareCanvas, 0, 0, width, height);
ectx.filter = `blur(${(2 * zoom).toFixed(2)}px)`;
ectx.drawImage(tubeCanvas, 0, 0, width, height);
ectx.filter = 'none';
for (const { path, geo, ref, directed } of shiningEdges) {
drawStroke(ectx, path, 2 * zoom, edgeCoreGradient(ectx, geo, ref, palette), 1,
directed ? [20, 4] : null);
}
ectx.restore();
}
function paintNodes() {
if (!auraSprite) auraSprite = makeAura();
let built = 0, needsBuild = false;
// Весь свет под всеми аватарками, а не поверх соседних фотографий.
for (const node of nodes) {
if (!node.shining) continue;
const { x, y } = screenPoint(node);
const size = ORB_DIAMETER * (node.visualSmall ? .5 : 1) * zoom * 1.95;
ctx.drawImage(auraSprite, x - size / 2, y - size / 2, size, size);
}
// Все пользователи рисуются, в том числе за пределами экрана — по решению для V4.
for (const node of nodes) {
const { x, y } = screenPoint(node);
const size = ORB_DIAMETER * (node.visualSmall ? .5 : 1) * zoom;
const id = keyOf(node.id);
const cached = spriteCache.get(id);
const photo = photos.get(id);
const currentKey = spriteKey(node, photo);
let sprite = cached;
if (!cached || cached.key !== currentKey || cached.scale !== spriteScale) {
if (built < MAX_SPRITES_PER_FRAME) { sprite = buildSprite(node); built += 1; }
else needsBuild = true;
}
if (sprite) {
const imageSize = size * GLASS_SCALE;
ctx.drawImage(sprite.canvas, x - imageSize / 2, y - imageSize / 2, imageSize, imageSize);
} else {
ctx.fillStyle = rgba(color(palette, node.relationType), .8);
ctx.beginPath(); ctx.arc(x, y, size / 2, 0, 2 * Math.PI); ctx.fill();
}
if (badgeReady && node.official) {
const badgeSize = Math.max(12, size * .32);
ctx.drawImage(badge, x - size / 2, y + size / 2 - badgeSize, badgeSize, badgeSize);
}
}
// Подписи V2: компактные округлённые плашки без толстого контура текста.
// Приоритет центра и близких, защита от пересечений и резервная позиция сверху.
ctx.save();
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
const fontFamily = getComputedStyle(stage).fontFamily || 'sans-serif';
const occupied = nodes.map((node) => {
const { x, y } = screenPoint(node);
const r = ORB_DIAMETER * (node.visualSmall ? .25 : .5) * zoom;
return { left: x - r - 2, right: x + r + 2, top: y - r - 2, bottom: y + r + 2 };
});
const collides = (r) => occupied.some((other) =>
r.left < other.right && r.right > other.left && r.top < other.bottom && r.bottom > other.top);
const priority = (node) => node.id === focusId ? 0 :
(node.relationType === 'close_friend' ? 1 : node.relationType === 'friend' ? 2 : 3) +
Math.max(0, Number(node.distance) || 0) * 5;
const ordered = [...nodes].sort((a, b) => priority(a) - priority(b) || a.id.localeCompare(b.id));
const MAX_LABEL_CHARS = 18;
for (const node of ordered) {
const { x, y } = screenPoint(node);
const isFocus = node.id === focusId;
const r = ORB_DIAMETER * (node.visualSmall ? .25 : .5) * zoom;
if (!isFocus && r < 6.5) continue;
const original = String(node.name || node.login || node.id).trim();
const words = original.split(/\s+/).filter(Boolean);
// Вторая версия показывает «Имя Ф.» для обычных участников и полное имя центра.
const short = !isFocus && words.length >= 2 ? `${words[0]} ${words[1][0]}.` : original;
const label = short.length > MAX_LABEL_CHARS ? `${short.slice(0, MAX_LABEL_CHARS - 1)}…` : short;
const fontSize = Math.round(clamp((isFocus ? 13 : node.visualSmall ? 10.5 : 12) * zoom,
isFocus ? 12.5 : node.visualSmall ? 10 : 11, isFocus ? 16 : node.visualSmall ? 13 : 15) * 2) / 2;
ctx.font = `${isFocus ? 700 : 500} ${fontSize}px ${fontFamily}`;
const labelW = ctx.measureText(label).width;
const padX = fontSize * .5;
const w = labelW + padX * 2;
const h = Math.round(fontSize * 1.5);
const gap = isFocus ? 5 : 3;
let y0 = y + r + gap;
let bounds = { left: x - w / 2 - 2, right: x + w / 2 + 2, top: y0 - 1, bottom: y0 + h + 1 };
if (collides(bounds)) {
const above = y - r - gap - h;
const alternate = { ...bounds, top: above - 1, bottom: above + h + 1 };
if (!collides(alternate)) { y0 = above; bounds = alternate; }
else if (!isFocus) continue;
}
occupied.push(bounds);
const x0 = x - w / 2;
ctx.fillStyle = palette === PALETTES.light ? 'rgba(230,237,243,.88)' : 'rgba(23,36,49,.82)';
ctx.beginPath();
if (ctx.roundRect) ctx.roundRect(x0, y0, w, h, h / 2);
else ctx.rect(x0, y0, w, h);
ctx.fill();
ctx.fillStyle = palette.text;
ctx.fillText(label, x, y0 + h / 2 + .5);
}
ctx.restore();
return needsBuild;
}
function draw() {
if (width <= 0 || height <= 0) return;
if (edgesDirty) {
ectx.setTransform(dpr, 0, 0, dpr, 0, 0);
ectx.clearRect(0, 0, width, height);
paintEdges();
edgesDirty = false;
}
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
if (paintNodes()) requestDraw(false);
}
function updateSize() {
const rect = stage.getBoundingClientRect();
const w = Math.max(1, Math.round(rect.width || stage.clientWidth || 1));
const h = Math.max(1, Math.round(rect.height || stage.clientHeight || 1));
const ratio = clamp(window.devicePixelRatio || 1, 1, 2.5);
if (w === width && h === height && ratio === dpr) return;
width = w; height = h; dpr = ratio;
for (const element of [canvas, edgesCanvas, flareCanvas, tubeCanvas]) {
element.width = Math.ceil(w * dpr); element.height = Math.ceil(h * dpr);
if (element === canvas || element === edgesCanvas) {
element.style.width = `${w}px`; element.style.height = `${h}px`;
}
}
const nextScale = desiredSpriteScale();
if (nextScale !== spriteScale) spriteScale = nextScale;
requestDraw();
}
function setModel(next) {
const oldFocus = focusId;
focusId = keyOf(next?.focusId);
const seen = new Set();
nodes = (Array.isArray(next?.nodes) ? next.nodes : []).map((raw) => {
const id = keyOf(raw.id);
seen.add(id);
const node = { ...raw, id, x: Number(raw.layoutX) || 0, y: Number(raw.layoutY) || 0 };
setupPhoto(node);
return node;
});
nodeById = new Map(nodes.map((n) => [n.id, n]));
for (const id of photos.keys()) if (!seen.has(id)) { photos.delete(id); spriteCache.delete(id); }
for (const id of spriteCache.keys()) if (!seen.has(id)) spriteCache.delete(id);
if (oldFocus && focusId !== oldFocus) { camX = 0; camY = 0; }
spriteScale = desiredSpriteScale();
a11y.textContent = `Граф связей: ${nodes.length} пользователей. Центр: ${nodes.find((n) => n.id === focusId)?.name || focusId}.`;
requestDraw();
}
function updateZoom(next, sx = width / 2, sy = height / 2) {
const value = clamp(next, ZOOM_MIN, ZOOM_MAX);
if (Math.abs(value - zoom) < .00001) return;
const factor = value / zoom;
camX = sx - width / 2 - (sx - width / 2 - camX) * factor;
camY = sy - height / 2 - (sy - height / 2 - camY) * factor;
zoom = value;
spriteScale = desiredSpriteScale();
requestDraw();
}
function hitNode(clientX, clientY) {
const rect = canvas.getBoundingClientRect();
const sx = clientX - rect.left, sy = clientY - rect.top;
for (let i = nodes.length - 1; i >= 0; i -= 1) {
const node = nodes[i];
const p = screenPoint(node);
const r = Math.max(8, ORB_DIAMETER / 2 * (node.visualSmall ? .5 : 1) * zoom);
if (Math.hypot(sx - p.x, sy - p.y) <= r) return node;
}
return null;
}
const pointers = new Map();
let gesture = null, pinchDistance = 0, longTimer = 0;
const clearLong = () => { if (longTimer) window.clearTimeout(longTimer); longTimer = 0; };
function pointerDown(e) {
if (e.button !== undefined && e.button !== 0) return;
e.preventDefault();
try { canvas.setPointerCapture(e.pointerId); } catch {}
pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
clearLong();
if (pointers.size >= 2) {
const pts = [...pointers.values()];
pinchDistance = Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y) || 1;
gesture = { pinching: true };
return;
}
const node = hitNode(e.clientX, e.clientY);
gesture = { id: e.pointerId, x: e.clientX, y: e.clientY, camX, camY,
node, nodeX: node?.x || 0, nodeY: node?.y || 0, moved: false, longFired: false };
if (node && typeof onNodeLongPress === 'function') {
longTimer = window.setTimeout(() => {
if (!gesture || gesture.moved || gesture.pinching || destroyed) return;
gesture.longFired = true;
onNodeLongPress(node, nodeScreenPoint(node));
}, LONG_PRESS_MS);
}
}
function pointerMove(e) {
if (pointers.has(e.pointerId)) pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
if (pointers.size >= 2 && gesture?.pinching) {
const pts = [...pointers.values()];
const dist = Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y) || 1;
const rect = canvas.getBoundingClientRect();
updateZoom(zoom * dist / (pinchDistance || dist), (pts[0].x + pts[1].x) / 2 - rect.left,
(pts[0].y + pts[1].y) / 2 - rect.top);
pinchDistance = dist;
return;
}
if (!gesture || gesture.id !== e.pointerId || gesture.longFired) {
canvas.classList.toggle('is-over-node', Boolean(hitNode(e.clientX, e.clientY)));
return;
}
const dx = e.clientX - gesture.x, dy = e.clientY - gesture.y;
if (Math.hypot(dx, dy) > DRAG_SLOP) { gesture.moved = true; clearLong(); }
if (!gesture.moved) return;
if (gesture.node) {
gesture.node.x = gesture.nodeX + dx / zoom;
gesture.node.y = gesture.nodeY + dy / zoom;
} else { camX = gesture.camX + dx; camY = gesture.camY + dy; }
requestDraw();
}
function pointerUp(e) {
pointers.delete(e.pointerId);
clearLong();
try { canvas.releasePointerCapture(e.pointerId); } catch {}
if (gesture?.pinching) { if (pointers.size < 2) gesture = null; return; }
if (!gesture || gesture.id !== e.pointerId) return;
const completed = gesture;
gesture = null;
if (completed.longFired) return;
if (completed.moved) {
if (completed.node) onNodeMoveEnd?.(completed.node, { x: completed.node.x, y: completed.node.y });
return;
}
if (!completed.node) return;
if (completed.node.id === focusId) onCenterTap?.(completed.node, nodeScreenPoint(completed.node));
else onNodeTap?.(completed.node);
}
function onCancel(e) { pointers.delete(e.pointerId); clearLong(); gesture = null; }
function onWheel(e) {
e.preventDefault();
const rect = canvas.getBoundingClientRect();
updateZoom(zoom * Math.exp(-e.deltaY * .0016), e.clientX - rect.left, e.clientY - rect.top);
}
function onContextMenu(e) {
e.preventDefault();
const node = hitNode(e.clientX, e.clientY);
if (node) onNodeLongPress?.(node, nodeScreenPoint(node));
}
function onTheme() {
const next = document.documentElement.dataset.theme === 'light' ? PALETTES.light : PALETTES.dark;
if (palette === next) return;
palette = next; spriteCache.clear(); auraSprite = null; requestDraw();
}
canvas.addEventListener('pointerdown', pointerDown);
canvas.addEventListener('pointermove', pointerMove);
canvas.addEventListener('pointerup', pointerUp);
canvas.addEventListener('pointercancel', onCancel);
canvas.addEventListener('lostpointercapture', onCancel);
canvas.addEventListener('wheel', onWheel, { passive: false });
canvas.addEventListener('contextmenu', onContextMenu);
const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(updateSize) : null;
observer?.observe(stage);
window.addEventListener('resize', updateSize);
const themeObserver = typeof MutationObserver === 'function' ?
new MutationObserver(onTheme) : null;
themeObserver?.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
onTheme();
updateSize();
setModel(model);
return {
setModel, nodeScreenPoint,
getFocusNode: () => nodeById.get(focusId) || null,
recenter: () => { camX = 0; camY = 0; updateZoom(DIVE_ZOOM); requestDraw(); },
destroy: () => {
if (destroyed) return;
destroyed = true;
clearLong(); pointers.clear();
if (frame) cancelAnimationFrame(frame);
observer?.disconnect(); themeObserver?.disconnect();
window.removeEventListener('resize', updateSize);
canvas.removeEventListener('pointerdown', pointerDown);
canvas.removeEventListener('pointermove', pointerMove);
canvas.removeEventListener('pointerup', pointerUp);
canvas.removeEventListener('pointercancel', onCancel);
canvas.removeEventListener('lostpointercapture', onCancel);
canvas.removeEventListener('wheel', onWheel);
canvas.removeEventListener('contextmenu', onContextMenu);
photos.clear(); spriteCache.clear();
edgesCanvas.remove(); canvas.remove(); a11y.remove();
},
// Диагностика без зависимости от структуры canvas.
debugState: () => ({ nodeCount: nodes.length, zoom, spriteScale, cachedSprites: spriteCache.size, frameQueued: !!frame }),
};
}
@@ -0,0 +1,63 @@
// Цвета и геометрия V4: чистые функции без DOM и загрузки картинок.
export const ORB_DIAMETER = 58;
export const PALETTES = {
dark: {
family: [255, 159, 94], friend: [120, 179, 255], close_friend: [255, 76, 92],
business: [190, 150, 255], contact: [170, 190, 220], self: [140, 240, 255],
shine: [0, 229, 255], text: '#e7ebf3', shadow: 'rgba(0, 0, 0, .78)', bg: '#172431',
},
light: {
family: [184, 92, 20], friend: [38, 96, 196], close_friend: [214, 38, 55],
business: [108, 62, 200], contact: [92, 98, 121], self: [6, 86, 122],
shine: [10, 127, 179], text: '#202332', shadow: 'rgba(255, 255, 255, .86)', bg: '#e6edf3',
},
};
export const clamp = (v, min, max) => Math.max(min, Math.min(max, v));
export const rgba = (rgb, alpha = 1) => `rgba(${rgb[0]},${rgb[1]},${rgb[2]},${alpha})`;
export const color = (palette, type) => palette[type] || palette.contact;
export const keyOf = (id) => String(id ?? '').toLowerCase();
export function hash01(value) {
let h = 2166136261;
for (const ch of String(value)) { h ^= ch.charCodeAt(0); h = Math.imul(h, 16777619); }
return (h >>> 0) / 4294967296;
}
// Градиент на концах кривой: исходящий тип -> обратный тип (если он известен).
// У одностороннего отношения линия затухает к адресату, без бегущих штрихов.
export function edgeGradient(ctx, geometry, ref, palette) {
const forward = color(palette, ref.relationType || 'friend');
const reverse = color(palette, ref.reverseRelationType || ref.relationType || 'friend');
const grad = ctx.createLinearGradient(geometry.x1, geometry.y1, geometry.x2, geometry.y2);
grad.addColorStop(0, rgba(forward, 0.98));
grad.addColorStop(1, rgba(reverse, ref.mutual === false ? 0.035 : 0.98));
return grad;
}
// V3 рисует светлую сердцевину, а не ещё один толстый насыщенный цветной слой.
// Здесь слегка высветляем цвет для сохранения сине-красного перехода взаимной связи.
export function edgeCoreGradient(ctx, geometry, ref, palette) {
const tint = (rgb, alpha) => rgba(rgb.map((v) => Math.round(v * .36 + 255 * .64)), alpha);
const forward = color(palette, ref.relationType || 'friend');
const reverse = color(palette, ref.reverseRelationType || ref.relationType || 'friend');
const grad = ctx.createLinearGradient(geometry.x1, geometry.y1, geometry.x2, geometry.y2);
grad.addColorStop(0, tint(forward, .98));
grad.addColorStop(1, tint(reverse, ref.mutual === false ? .035 : .98));
return grad;
}
export function geometryFor(parent, child, zoom, cx, cy) {
const fx = cx.x + parent.x * zoom, fy = cx.y + parent.y * zoom;
const tx = cx.x + child.x * zoom, ty = cx.y + child.y * zoom;
const dx = tx - fx, dy = ty - fy;
const len = Math.hypot(dx, dy) || 1;
const ux = dx / len, uy = dy / len;
const startR = ORB_DIAMETER * (parent.visualSmall ? .25 : .5) * zoom;
const endR = ORB_DIAMETER * (child.visualSmall ? .25 : .5) * zoom;
const x1 = fx + ux * startR, y1 = fy + uy * startR;
const x2 = tx - ux * endR, y2 = ty - uy * endR;
const mx = (x1 + x2) / 2, my = (y1 + y2) / 2;
const bow = clamp(Math.hypot(x2 - x1, y2 - y1) * .10, 7, 22) *
(hash01(`${parent.id}|${child.id}|edge`) > .5 ? 1 : -1);
const cpx = mx - uy * bow * 2, cpy = my + ux * bow * 2;
return { x1, y1, x2, y2, cpx, cpy, ux, uy, mx, my, bow };
}
@@ -0,0 +1,6 @@
// Экран V4 использует ту же модель/состояние/фильтры, что и V3.
import { pageMeta, renderExplorer } from '../network-explorer/network-view.js';
export { pageMeta };
export function render(context = {}) {
return renderExplorer(context, { canvas: true });
}
@@ -5,6 +5,7 @@ import { authService, state } from '../../state.js';
import { makeProfileRoute, makeProfileLinksRoute } from '../../services/shine-routes.js';
import { CONNECTIONS_GRAPH_CHANGED } from '../../services/connections-graph-cache.js';
import { createForceGraph } from '../network-legacy/force-graph.js';
import { createExplorerCanvasGraph } from '../network-canvas-v4/graph-renderer.js';
import { openNodeMenu } from '../network-legacy/node-menu.js';
import { createExplorerGraph, keyOf, EXPLORER_DEFAULT_DEPTH, EXPLORER_MAX_DEPTH } from './graph-model.js';
import { getExplorerGraph, readExplorerCachedGraphs, clearExplorerGraphCache, explorerCacheScope, explorerGraphSavedAt } from './graph-cache.js';
@@ -33,12 +34,24 @@ function hash01(value) {
return (h >>> 0) / 4294967296;
}
// V3 state survives switching between tabs; long-term graph responses reside in IndexedDB.
// V3/V4 сохраняют исследование при переключении версий внутри вкладки.
// Новый вход через нижнюю кнопку «Связи» очищает карту и IndexedDB-графы.
let retained = null;
let resetBarrier = Promise.resolve();
export function resetExplorerOnTabEntry() {
retained = null;
// Новые загрузки обязаны дождаться очистки, иначе IndexedDB вернёт старую карту.
resetBarrier = resetBarrier.catch(() => {}).then(() => clearExplorerGraphCache());
}
export function render({ navigate, route, chrome } = {}) {
export function render(context = {}) {
return renderExplorer(context);
}
// Общие для V3 и V4 поиск, кэш, BFS, фильтры и жизненный цикл страницы.
export function renderExplorer({ navigate, route, chrome } = {}, { canvas = false } = {}) {
const screen = document.createElement('section');
screen.className = 'network-screen network-explorer';
screen.className = `network-screen network-explorer${canvas ? ' network-explorer--canvas' : ''}`;
const stage = document.createElement('div');
stage.className = 'network-stage';
const board = document.createElement('div');
@@ -137,7 +150,7 @@ export function render({ navigate, route, chrome } = {}) {
layoutY: session.positions.get(node.id)?.y || 0, fixedLayout: true,
}));
if (engine) engine.setModel(model);
else engine = createForceGraph({
else engine = (canvas ? createExplorerCanvasGraph : createForceGraph)({
stage: board, model, explorerMode: true,
onNodeTap: (node) => { void load(node.login, true); },
onCenterTap: (node) => nodeMenu(node, false),
@@ -157,11 +170,12 @@ export function render({ navigate, route, chrome } = {}) {
});
}
function nodeMenu(node, long = false, point = null) {
const rect = node?.el?.getBoundingClientRect?.();
const canvasPoint = canvas ? engine?.nodeScreenPoint?.(node) : null;
const rect = node?.el?.getBoundingClientRect?.() || canvasPoint?.rect;
openNodeMenu({
login: normalizeLogin(node?.login), displayName: String(node?.name || '').trim(),
relationType: node?.relationType,
point: point || (rect ? { x: rect.left + rect.width / 2, y: rect.top, rect } : undefined),
point: point || canvasPoint || (rect ? { x: rect.left + rect.width / 2, y: rect.top, rect } : undefined),
actions: [
{ label: t(long ? 'screens.network_view.text_006' : 'screens.network_view.text_004'), onClick: () => navigate?.(profileRoute(node?.login)) },
{ label: t(long ? 'screens.network_view.text_007' : 'screens.network_view.text_005'), onClick: () => navigate?.(`chat/${encodeURIComponent(normalizeLogin(node?.login))}`) },
@@ -446,17 +460,21 @@ export function render({ navigate, route, chrome } = {}) {
searchClose?.();
// TopBar lifetime owned by AppShell, not this screen.
};
// Восстановление уже открытых веток из IndexedDB (без сетевых запросов).
// Первую карту показываем сразу, восстановление идёт параллельно.
void readExplorerCachedGraphs(scope).then((entries) => {
// Кэш графов восстанавливаем только после завершения возможного сброса вкладки.
// Фотографии и кэш изображений сброс не затрагивает.
void resetBarrier.then(async () => {
if (disposed || session !== retained) return;
const entries = await readExplorerCachedGraphs(scope);
if (disposed || cacheWasCleared || session !== retained) return;
entries.forEach((entry) => {
const login = entry?.graph?.login || entry?.key?.slice(scope.length + 1);
if (login && !session.graph.isFresh(login)) session.graph.add(entry.graph, login, entry.savedAt);
});
scheduleDraw();
if (centerLogin) void load(centerLogin);
else window.setTimeout(() => { if (!disposed) openSearchModal(); }, 0);
}).catch((error) => {
if (!disposed) { console.warn('[Network explorer] Cache reset/read failed', error); if (centerLogin) void load(centerLogin); }
});
if (centerLogin) void load(centerLogin);
else window.setTimeout(() => { if (!disposed) openSearchModal(); }, 0);
return screen;
}
+11 -5
View File
@@ -2,18 +2,23 @@ import { t, th } from '../i18n/index.js';
import * as modernNetworkView from './network-view.js';
import * as legacyNetworkView from './network-legacy/network-view.js';
import * as explorerNetworkView from './network-explorer/network-view.js';
import * as explorerCanvasView from './network-canvas-v4/network-view.js';
const NETWORK_VERSION_STORAGE_KEY = 'shine.network.version';
const MODES = new Set(['legacy', 'modern', 'explorer']);
const MODES = new Set(['legacy', 'modern', 'explorer', 'explorer-canvas']);
const DEFAULT_MODE = 'explorer-canvas';
// Нижняя вкладка сбрасывает только исследованный граф V3/V4, не изображения и не V1/V2.
window.addEventListener('shine:network-tab-enter', explorerNetworkView.resetExplorerOnTabEntry);
export const pageMeta = modernNetworkView.pageMeta;
function selectedMode() {
try {
const saved = window.localStorage.getItem(NETWORK_VERSION_STORAGE_KEY);
return MODES.has(saved) ? saved : 'modern';
return MODES.has(saved) ? saved : DEFAULT_MODE;
} catch {
return 'modern';
return DEFAULT_MODE;
}
}
@@ -36,10 +41,11 @@ function createModeSwitcher(mode, navigate) {
<option value="legacy">${th('screens.network_version_switcher.text_002')}</option>
<option value="modern">${th('screens.network_version_switcher.text_003')}</option>
<option value="explorer">${th('screens.network_version_switcher.text_005')}</option>
<option value="explorer-canvas">V4 · Canvas</option>
`;
select.value = mode;
select.addEventListener('change', () => {
const nextMode = MODES.has(select.value) ? select.value : 'modern';
const nextMode = MODES.has(select.value) ? select.value : DEFAULT_MODE;
saveMode(nextMode);
navigate?.('network-view');
});
@@ -49,7 +55,7 @@ function createModeSwitcher(mode, navigate) {
export function render(context = {}) {
const mode = selectedMode();
const implementation = mode === 'legacy' ? legacyNetworkView : (mode === 'explorer' ? explorerNetworkView : modernNetworkView);
const implementation = mode === 'legacy' ? legacyNetworkView : (mode === 'explorer' ? explorerNetworkView : (mode === 'explorer-canvas' ? explorerCanvasView : modernNetworkView));
const screen = implementation.render(context);
screen.classList.add(`network-screen--${mode}`);
+35 -8
View File
@@ -57,6 +57,24 @@ function actionLabel(item, activeTab) {
: eventActionLabel(item.sourceMsgSubType, gender);
}
function reciprocalRelationKind(item) {
return Number(item?.connectionTypeCode ?? item?.sourceMsgSubType) === CONNECTION_CLOSE_FRIEND
? 'close_friend'
: 'friend';
}
function reciprocalRelationLabel(kind) {
return kind === 'close_friend'
? t('screens.notifications_view.text_072')
: t('screens.notifications_view.text_009');
}
function reciprocalRelationSuccessLabel(kind) {
return kind === 'close_friend'
? t('screens.notifications_view.text_073')
: t('screens.notifications_view.text_015');
}
export const pageMeta = { id: 'notifications-view', get title() { return t('screens.notifications_view.text_001'); } };
function normalizeItem(item) {
@@ -192,10 +210,19 @@ function renderHead(item) {
|| item.sourceLogin || t('screens.notifications_view.text_030');
const head = document.createElement('div');
head.className = 'notification-card__head';
const identity = document.createElement('div');
identity.className = 'notification-card__identity';
const name = document.createElement('strong');
name.className = 'notification-card__name';
name.textContent = fullName;
head.append(name);
identity.append(name);
if (item.sourceLogin) {
const login = document.createElement('span');
login.className = 'notification-card__login';
login.textContent = item.sourceLogin;
identity.append(login);
}
head.append(identity);
const time = document.createElement('span');
time.className = 'notification-card__time';
time.textContent = formatListTime(item.createdAtMs);
@@ -301,8 +328,7 @@ function renderItem(item, activeTab, navigate) {
function refreshItemRow(row, item, activeTab) {
if (!row?.isConnected) return;
row.querySelector('.notification-avatar')?.replaceWith(renderAvatar(item));
const name = row.querySelector('.notification-card__name');
if (name) name.textContent = renderHead(item).querySelector('.notification-card__name').textContent;
row.querySelector('.notification-card__head')?.replaceWith(renderHead(item));
const action = row.querySelector('.notification-card__action');
if (action && activeTab !== 'replies') action.textContent = actionLabel(item, activeTab);
if (activeTab === 'replies' && item.engagement && !row.querySelector('.notification-engagement')) {
@@ -453,24 +479,25 @@ export function render({ navigate, chrome } = {}) {
const row = rowByItem.get(item);
const body = row?.querySelector('.notification-card__body');
if (!body) continue;
const kind = reciprocalRelationKind(item);
const button = document.createElement('button');
button.type = 'button';
button.className = 'secondary-btn notification-card__answer';
button.textContent = t('screens.notifications_view.text_009');
button.textContent = reciprocalRelationLabel(kind);
button.addEventListener('click', async (event) => {
event.stopPropagation();
button.disabled = true;
button.textContent = t('screens.notifications_view.text_010');
try {
await authService.setUserRelation({ login: self, toLogin: login, kind: 'friend', enabled: true, storagePwd: state.session.storagePwdInMemory });
await authService.setUserRelation({ login: self, toLogin: login, kind, enabled: true, storagePwd: state.session.storagePwdInMemory });
const done = document.createElement('span');
done.className = 'notification-card__answered';
done.innerHTML = `${iconHtml('check')}<span>${th('screens.notifications_view.text_046')}</span>`;
done.innerHTML = `${iconHtml('check')}<span>${th(reciprocalRelationSuccessLabel(kind))}</span>`;
button.replaceWith(done);
showToast(t('screens.notifications_view.text_015'));
showToast(reciprocalRelationSuccessLabel(kind));
} catch (error) {
button.disabled = false;
button.textContent = t('screens.notifications_view.text_011');
button.textContent = reciprocalRelationLabel(kind);
showToast(toUserMessage(error, t('screens.notifications_view.text_016')), { kind: 'error' });
}
});
+32 -9
View File
@@ -1,6 +1,7 @@
import { t, th } from '../i18n/index.js';
import { createTopBar } from '../components/topbar.js';
import { createVisiblePasswordField } from '../components/visible-password-field.js';
import { createVisiblePasswordField, createExpandablePasswordTextarea } from '../components/visible-password-field.js';
import { createSecretGenerationOverlay } from '../components/secret-generation-overlay.js';
import { confirmPasswordBoundarySpaces } from '../services/password-boundary-warning.js';
import { createRegistrationStepper } from '../components/registration-stepper.js';
import { authService, clearAuthMessages, clearRegistrationDraft, state } from '../state.js';
@@ -18,7 +19,8 @@ export function render({ navigate }) {
const body = document.createElement('div');
body.className = 'card stack registration-form signup-wizard__body';
const header = createTopBar({ title: t('screens.register_view.text_002'), back: { label: '←', onClick: goBack } });
screen.append(header, body);
const keyGeneration = createSecretGenerationOverlay();
screen.append(header, body, keyGeneration.overlay);
let namespaces = [];
let isLoading = true;
@@ -143,14 +145,21 @@ export function render({ navigate }) {
const labelText = document.createElement('span');
labelText.className = 'field-label';
labelText.textContent = t('screens.register_view.text_031', { value1: PASSWORD_MAX_LENGTH });
const input = document.createElement('input');
input.className = 'input';
input.type = 'text';
const input = createExpandablePasswordTextarea();
input.autocomplete = 'new-password';
input.maxLength = PASSWORD_MAX_LENGTH;
input.placeholder = t('screens.register_view.text_009');
input.value = draft.password || '';
label.append(labelText, createVisiblePasswordField(input));
// Never repopulate a successfully submitted secret on returning to this step.
input.value = '';
const passwordCount = document.createElement('span');
passwordCount.className = 'password-length-hint';
passwordCount.setAttribute('aria-live', 'off');
const refreshPasswordCount = () => {
passwordCount.textContent = t('screens.register_view.password_counter', { value1: input.value.length, value2: PASSWORD_MAX_LENGTH });
};
label.append(labelText, createVisiblePasswordField(input), passwordCount);
refreshPasswordCount();
requestAnimationFrame(() => input.resizePasswordField());
const guidance = document.createElement('div');
guidance.className = 'signup-guidance';
guidance.innerHTML = `
@@ -167,7 +176,13 @@ export function render({ navigate }) {
next.className = 'primary-btn signup-next';
next.type = 'button';
next.textContent = t('screens.register_view.text_010');
input.addEventListener('input', () => { inputRevision++; status.textContent = ''; });
input.addEventListener('input', () => { inputRevision++; status.textContent = ''; refreshPasswordCount(); });
input.addEventListener('keydown', event => {
if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
event.preventDefault();
next.click();
}
});
next.addEventListener('click', async () => {
const value = input.value;
if (value.length < 1 || value.length > PASSWORD_MAX_LENGTH) {
@@ -188,9 +203,13 @@ export function render({ navigate }) {
}
const revision = inputRevision;
const thisRequest = ++requestId;
const needsGeneration = draft.password !== value || !draft.preGeneratedKeyBundle;
next.disabled = true;
status.textContent = t('screens.register_view.text_013');
status.textContent = '';
if (needsGeneration) keyGeneration.show();
try {
// Дать браузеру отрисовать заставку до тяжёлого KDF.
if (needsGeneration) await new Promise(resolve => setTimeout(resolve, 40));
const changed = draft.password !== value;
draft.password = value;
if (changed) draft.preGeneratedKeyBundle = null;
@@ -198,10 +217,14 @@ export function render({ navigate }) {
if (!screen.isConnected || thisRequest !== requestId) return;
if (revision !== inputRevision) throw new Error(t('screens.register_view.text_027'));
draft.preGeneratedKeyBundle = bundle;
// Hide the password before navigation to prevent a visible flash.
input.clearPasswordField();
refreshPasswordCount();
navigate(flowType === 'free' ? 'registration-email-view' : 'registration-payment-view');
} catch (error) {
if (screen.isConnected && thisRequest === requestId) status.textContent = error.message || t('screens.register_view.text_028');
} finally {
keyGeneration.hide();
if (screen.isConnected && thisRequest === requestId) next.disabled = false;
}
});
+17 -8
View File
@@ -1,6 +1,7 @@
import { t } from '../i18n/index.js';
import { createTopBar } from '../components/topbar.js';
import { resetRegistrationFlow, state } from '../state.js';
import { getRegistrationNamespaces } from '../services/registration-v2-api.js';
export const pageMeta = { id: 'registration-choice-view', get title() { return t('screens.registration_choice_view.text_001'); }, showAppChrome: false };
@@ -55,23 +56,31 @@ export function render({ navigate }) {
box.append(top, description, list, action);
return box;
}
screen.append(
createTopBar({ title: t('screens.registration_choice_view.text_004'), back: { label: '←', onClick: () => navigate('registration-intro-view') } }),
title, intro,
card({
const topBar = createTopBar({ title: t('screens.registration_choice_view.text_004'), back: { label: '←', onClick: () => navigate('registration-intro-view') } });
const plans = document.createElement('div');
plans.className = 'stack';
const paidCard = card({
type: 'paid', icon: '◇', heading: t('screens.registration_choice_view.text_005'),
price: t('screens.registration_choice_view.text_007'),
lead: t('screens.registration_choice_view.text_008'),
perks: [t('screens.registration_choice_view.text_009'), t('screens.registration_choice_view.text_010'), t('screens.registration_choice_view.text_011')],
button: t('screens.registration_choice_view.text_012'),
}),
card({
});
plans.append(paidCard);
screen.append(topBar, title, intro, plans);
// Бесплатная регистрация доступна только если текущий сервер сам объявил
// привязанный к нему type-2 namespace. При ошибке запроса безопасно оставляем
// только платный сценарий.
void getRegistrationNamespaces().then(({ namespaces }) => {
if (!screen.isConnected || !Array.isArray(namespaces) || !namespaces.some(n => Number(n.type) === 2)) return;
plans.append(card({
type: 'free', icon: '♧', heading: t('screens.registration_choice_view.text_006'),
price: t('screens.registration_choice_view.text_013'),
lead: t('screens.registration_choice_view.text_014'),
perks: [t('screens.registration_choice_view.text_015'), t('screens.registration_choice_view.text_016'), t('screens.registration_choice_view.text_017')],
button: t('screens.registration_choice_view.text_018'),
}),
);
}));
});
return screen;
}
+2 -1
View File
@@ -7,6 +7,7 @@ import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
import { readShineUserPda } from '../services/shine-user-pda-service.js';
import { bytesToBase58 } from '../services/crypto-utils.js';
import { t } from '../i18n/index.js';
import { makeSolanaExplorerTxUrl } from '../services/solana-rpc-gateway.js';
export const pageMeta = { id: 'wallet-transfer-view', get title() { return t('wallet_multi.transfer_title'); } };
@@ -181,7 +182,7 @@ export function render({ navigate, chrome, route }) {
await authService.sendDirectMessage({
login: state.session.login, toLogin: recipientLogin,
storagePwd: state.session.storagePwdInMemory,
text: `${t('wallet_multi.dm_prefix')} ${display}\n${t('wallet_multi.dm_signature')}: ${result.signature}`,
text: `${t('wallet_multi.dm_prefix')} ${display}\n${t('wallet_multi.dm_signature')}: ${result.signature}\n${t('wallet_multi.dm_explorer')}: ${makeSolanaExplorerTxUrl(result.signature, endpoint)}`,
});
if (!disposed) setStatus(`${t('wallet_multi.success')}\n${result.signature}\n${t('wallet_multi.notice_sent')}`);
} catch (error) {
+7 -42
View File
@@ -21,10 +21,7 @@ import { getUsdtBalance, getUsdtAsset } from '../services/solana-usdt-service.js
import { openArweaveAttachmentManager } from '../components/arweave-attachment-manager.js';
import { buildArweaveDataUrl, sha256HexFromArrayBuffer } from '../services/arweave-file-service.js';
import {
calcLimitTopupPriceLamports,
getLimitStepBytes,
getShineBlockchainUsage,
getShineUsersEconomyConfig,
updateShineUserPdaOnSolana,
} from '../services/shine-blockchain-wallet-service.js?v=202605300007';
import {
@@ -71,16 +68,6 @@ function lamportsToSolText(lamportsBigInt) {
return formatNumber(value, { minimumFractionDigits: 0, maximumFractionDigits: 9 });
}
function formatLimitTopupError(error) {
const message = String(error?.message || '').trim();
const logs = Array.isArray(error?.logs) ? error.logs.join(' | ') : '';
const haystack = `${message} ${logs}`.toLowerCase();
if (haystack.includes('insufficient funds for rent')) {
return t('screens.wallet_view.text_106');
}
return t('screens.wallet_view.text_153', { value1: message || 'unknown' });
}
function createModeBackButton(renderWalletChoice) {
const backBtn = document.createElement('button');
backBtn.className = 'text-btn';
@@ -537,32 +524,14 @@ export function render({navigate, chrome}) {
async function resolveWalletSigningMaterial() {
const { login, storagePwd } = sessionArgsOrThrow();
let saved = null;
try {
saved = await loadEncryptedUserSecrets(login, storagePwd);
} catch {
saved = null;
}
const blockchainKey = String(saved?.blockchainKey || '').trim();
const clientKey = String(saved?.clientKey || '').trim();
if (blockchainKey && clientKey) {
return {
rootPrivatePkcs8B64: '',
blockchainPrivatePkcs8B64: blockchainKey,
clientPrivatePkcs8B64: clientKey,
};
}
const password = window.prompt(
t('dialogs.pages.wallet_view.prompt_001'),
'',
);
// Root key is intentionally not kept in IndexedDB or encrypted key vault.
// Solana PDA updates are rare, so require a fresh password on every update.
const password = window.prompt(t('dialogs.pages.wallet_view.prompt_001'), '');
if (password == null) throw new Error(t('screens.wallet_view.text_138'));
const keyBundle = await authService.derivePasswordKeyBundle(login, password);
await authService.persistSelectedKeys(login, storagePwd, keyBundle);
return {
rootPrivatePkcs8B64: '',
rootPrivatePkcs8B64: keyBundle.rootPair.privatePkcs8B64,
blockchainPrivatePkcs8B64: keyBundle.blockchainPair.privatePkcs8B64,
clientPrivatePkcs8B64: keyBundle.clientPair.privatePkcs8B64,
};
@@ -1419,14 +1388,11 @@ export function render({navigate, chrome}) {
actions.className = 'stack';
actions.innerHTML = `
<button class="ghost-btn" id="refresh-shine-bch" style="width:100%;">${th('screens.wallet_view.text_266')}</button>
<button class="primary-btn" id="topup-shine-limit" style="width:100%;">${th('screens.wallet_view.text_267')}</button>
`;
const refreshBtn = actions.querySelector('#refresh-shine-bch');
const topupBtn = actions.querySelector('#topup-shine-limit');
const setButtonsDisabled = (disabled) => {
refreshBtn.disabled = disabled;
topupBtn.disabled = disabled;
};
const refreshUsage = async () => {
@@ -1440,11 +1406,11 @@ export function render({navigate, chrome}) {
fetchServerBlockchainState(),
]);
if (modeToken !== activeModeToken) return;
limitValue.textContent = formatKbFromBytes(usage.paidLimitBytes);
limitValue.textContent = usage.paidLimitBytes === 0n ? t('screens.wallet_view.unlimited') : formatKbFromBytes(usage.paidLimitBytes);
const usedServerBytes = BigInt(Math.max(0, Number(serverState.sizeBytes || 0)));
const leftServerBytes = usage.paidLimitBytes > usedServerBytes ? (usage.paidLimitBytes - usedServerBytes) : 0n;
usedValue.textContent = formatKbFromBytes(usedServerBytes);
leftValue.textContent = formatKbFromBytes(leftServerBytes);
leftValue.textContent = usage.paidLimitBytes === 0n ? t('screens.wallet_view.unlimited') : formatKbFromBytes(leftServerBytes);
pdaLabel.textContent = `PDA: ${usage.userPda}`;
endpointLabel.textContent = `RPC: ${usage.endpoint}`;
updatedLabel.textContent = t('screens.wallet_view.text_162', { value1: nowRu() });
@@ -1623,7 +1589,7 @@ export function render({navigate, chrome}) {
pdaLastEl.textContent = t('screens.wallet_view.text_167', { value1: usage.lastBlockNumber });
pdaHashEl.textContent = `Hash: ${usage.lastBlockHashHex || '–'}`;
pdaUsedEl.textContent = t('screens.wallet_view.text_168', { value1: formatBytesRu(usage.usedBytes) });
pdaLimitEl.textContent = t('screens.wallet_view.text_169', { value1: formatBytesRu(usage.paidLimitBytes) });
pdaLimitEl.textContent = t('screens.wallet_view.text_169', { value1: usage.paidLimitBytes === 0n ? t('screens.wallet_view.unlimited') : formatBytesRu(usage.paidLimitBytes) });
pdaArweaveEl.textContent = `Arweave tx: ${usage.arweaveTxId || '–'}`;
if (usage.arweaveTxId) {
pdaArweaveLinkEl.href = buildArweaveDataUrl({ gateway: state.entrySettings.arweaveServer, txId: usage.arweaveTxId });
@@ -1778,7 +1744,6 @@ export function render({navigate, chrome}) {
rootPrivatePkcs8B64: signing.rootPrivatePkcs8B64,
blockchainPrivatePkcs8B64: signing.blockchainPrivatePkcs8B64,
clientPrivatePkcs8B64: signing.clientPrivatePkcs8B64,
additionalLimitBytes: 0n,
nextUsedBytes: BigInt(Math.max(0, serverState.sizeBytes)),
nextLastBlockNumber: serverState.lastNumber,
nextLastBlockHashHex: serverState.lastHash,
+11
View File
@@ -201,3 +201,14 @@ export async function createAns104DataItemWithRawParts({
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 };
}
+41 -12
View File
@@ -7,7 +7,11 @@ import { resolvePublicFileUrl } from './public-file-service.js';
import { updatedUserFileUrlAfterError } from './user-file-server-service.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;
const RECENT_UNAVAILABLE_MS = 20 * 60 * 1000;
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 size = Number(input.sz || input.size || input.sizeBytes || 0);
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 (!validatePublicPiecesRoot(pr) && !validateSha256Hex(sha256Hex)) throw new Error('Некорректный идентификатор файла');
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 (!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) {
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 mmPart = item.mm ? `;mm=${item.mm}` : '';
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 = []) {
@@ -76,15 +81,33 @@ export function composeMessageWithAttachments(text, attachments = []) {
}
function parseFields(rawFields) {
const out = {};
String(rawFields || '').split(';').forEach((part) => {
const parts = String(rawFields || '').split(';');
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('=');
if (eq <= 0) return;
if (eq <= 0) {
if (strict) throw new Error('Некорректное поле вложения');
continue;
}
const key = part.slice(0, eq).trim();
const value = part.slice(eq + 1).trim();
if (key) out[key] = value;
});
return out;
if (strict && (!ATTACH_ALLOWED_FIELDS.has(key) || Object.hasOwn(fields, key))) {
throw new Error('Дублированное либо неизвестное поле вложения');
}
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) {
@@ -94,14 +117,20 @@ export function parseMessageAttachments(rawText) {
while (true) {
const match = rest.match(ATTACH_BLOCK_RE);
if (!match) break;
const fields = parseFields(match[2]);
try {
const fields = parseFields(match[2]);
const version = Number(fields.v || 0);
if (version !== 1 && version !== 2) {
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({
nm: decodeURIComponent(String(fields.nm || fields.name || 'file')),
nm: name,
sz: fields.sz || fields.size,
sha256: fields.sha256,
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) };
}
}
+3 -3
View File
@@ -95,11 +95,11 @@ export function formatShortAge(timestampMs) {
if (!ts) return '';
const ageMinutes = Math.max(0, Math.floor((Date.now() - ts) / 60000));
if (ageMinutes < 1) return formatRelative(0, 'second');
if (ageMinutes < 60) return formatRelative(-ageMinutes, 'minute', { numeric: 'always', style: 'narrow' });
if (ageMinutes < 60) return formatRelative(-ageMinutes, 'minute', { numeric: 'always' });
const ageHours = Math.floor(ageMinutes / 60);
if (ageHours < 24) return formatRelative(-ageHours, 'hour', { numeric: 'always', style: 'narrow' });
if (ageHours < 24) return formatRelative(-ageHours, 'hour', { numeric: 'always' });
const ageDays = Math.floor(ageHours / 24);
if (ageDays < 7) return formatRelative(-ageDays, 'day', { numeric: 'always', style: 'narrow' });
if (ageDays < 7) return formatRelative(-ageDays, 'day', { numeric: 'always' });
const dt = new Date(ts);
const day = shortDay(dt);
return dt.getFullYear() === new Date().getFullYear() ? day : `${day} ${dt.getFullYear()}`;
@@ -209,6 +209,7 @@ export class KeyRotationClient {
payerPrivatePkcs8B64:oldBundle.blockchainPair.privatePkcs8B64,
authorityMode:'root',
newRootPublicKey32:base64ToBytes(newBundle.rootPair.publicKeyB64),
newRootPrivatePkcs8B64:newBundle.rootPair.privatePkcs8B64,
nextClientPublicKey32:base64ToBytes(newBundle.clientPair.publicKeyB64),
newBlockchainPublicKey32:base64ToBytes(newBundle.blockchainPair.publicKeyB64),
newBlockchainPrivatePkcs8B64:newBundle.blockchainPair.privatePkcs8B64,
@@ -1,6 +1,4 @@
export {
calcLimitTopupPriceLamports,
getLimitStepBytes,
getShineBlockchainUsage,
getShineUsersEconomyConfig,
updateShineUserPdaOnSolana,
+7 -1
View File
@@ -70,7 +70,7 @@ export function tokenizeShineMessageLinks(text, options = {}) {
return tokens;
}
export function appendShineMessageLinks(root, text, { navigate, viewMode = 'thread', appendText } = {}) {
export function appendShineMessageLinks(root, text, { navigate, onExternalLink, viewMode = 'thread', appendText } = {}) {
for (const token of tokenizeShineMessageLinks(text, { viewMode })) {
if (token.type === 'text') {
if (typeof appendText === 'function') appendText(root, token.value);
@@ -87,6 +87,12 @@ export function appendShineMessageLinks(root, text, { navigate, viewMode = 'thre
}
link.addEventListener('click', (event) => {
event.stopPropagation();
if (token.type === 'external' && typeof onExternalLink === 'function'
&& event.button === 0 && !event.ctrlKey && !event.metaKey && !event.shiftKey && !event.altKey) {
event.preventDefault();
onExternalLink({ href: token.href, value: token.value });
return;
}
if (token.type === 'internal' && typeof navigate === 'function'
&& event.button === 0 && !event.ctrlKey && !event.metaKey && !event.shiftKey && !event.altKey) {
event.preventDefault();
+95 -76
View File
@@ -13,11 +13,11 @@ import { getNamespace, assertLoginInNamespace, normalizeFullLogin, userPdaSeed32
const MAGIC = 'SHiNE';
const FORMAT_MAJOR = 1;
const FORMAT_MINOR_LEGACY = 0;
const FORMAT_MINOR_CURRENT = 2;
const FORMAT_MINOR_CURRENT = 3;
const FORMAT_MINOR_PREVIOUS = 2;
const SHINE_PAYMENTS_INFLOW_VAULT_SEED = 'shine_payments_inflow_vault';
const SHINE_USERS_USER_PDA_SEED_PREFIX = 'user_login=';
const SHINE_USERS_PROMO_SELLER_PDA_SEED_PREFIX = 'promo_seller=';
const LIMIT_STEP = 10_000n;
const ED25519_PROGRAM_ID = 'Ed25519SigVerify111111111111111111111111111';
const SYSVAR_INSTRUCTIONS_ID = 'Sysvar1nstructions1111111111111111111111111';
const PROMO_SIGN_PREFIX = 'shine_promo_v1:';
@@ -56,7 +56,7 @@ function normalizeAccessServers(values) {
const login = normalizeLogin(value);
if (!login || seen.has(login)) continue;
if (result.length >= MAX_EFFECTIVE_ACCESS_SERVERS) {
throw new Error('PDA 1.2 поддерживает максимум один сервер доступа');
throw new Error('PDA 1.3 поддерживает максимум один сервер доступа');
}
seen.add(login);
result.push(login);
@@ -122,13 +122,11 @@ function makeReader(bytes) {
function parseUsersEconomyConfig(dataBytes) {
const view = new DataView(dataBytes.buffer, dataBytes.byteOffset, dataBytes.byteLength);
if (dataBytes.byteLength < 25) throw new Error('Некорректный economy config');
return {
version: view.getUint8(0),
registrationFeeLamports: view.getBigUint64(1, true),
lamportsPerLimitStep: view.getBigUint64(9, true),
startBonusLimit: view.getBigUint64(17, true),
};
if (dataBytes.byteLength < 9) throw new Error('Некорректный economy config');
const version = view.getUint8(0);
if (version === 2) return { version, updateFeeLamports: view.getBigUint64(1, true) };
if (version === 1 && dataBytes.byteLength >= 25) return { version, updateFeeLamports: 20_000n };
throw new Error('Неподдерживаемая версия economy config');
}
function buildEd25519IxData(sig64, pubkey32, messageBytes) {
@@ -157,7 +155,7 @@ function buildEd25519IxData(sig64, pubkey32, messageBytes) {
function normalizeServerAddresses(values, fallback = null) {
const src = Array.isArray(values) && values.length ? values : (fallback ? [fallback] : []);
if (src.length > 1) throw new Error('PDA 1.2 поддерживает только один адрес сервера');
if (src.length > 1) throw new Error('PDA 1.3 поддерживает только один адрес сервера');
return src.map((item) => {
const address = String(item?.address ?? item?.serverAddress ?? '').trim();
const bytes = new TextEncoder().encode(address);
@@ -225,7 +223,7 @@ function parseV12Pda(bytes, header) {
if (payload.remaining !== 0) throw new Error('Повреждённый BlockchainRegistry');
} else if (blockType === BLOCK_TYPE_SERVER_PROFILE) {
const count = payload.readU8();
if (count !== 1) throw new Error('PDA 1.2 допускает ровно один адрес в ServerProfileBlock');
if (count !== 1) throw new Error('PDA 1.3 допускает ровно один адрес в ServerProfileBlock');
serverAddresses = [];
for (let j = 0; j < count; j += 1) {
serverAddresses.push({
@@ -237,13 +235,13 @@ function parseV12Pda(bytes, header) {
if (payload.remaining !== 0) throw new Error('Повреждённый ServerProfileBlock');
} else if (blockType === BLOCK_TYPE_ACCESS_SERVERS) {
const count = payload.readU8();
if (count > 1) throw new Error('PDA 1.2 допускает максимум один access server');
if (count > 1) throw new Error('PDA 1.3 допускает максимум один access server');
accessServers = [];
for (let j = 0; j < count; j += 1) accessServers.push(payload.readStrU8());
if (payload.remaining !== 0) throw new Error('Повреждённый AccessServersBlock');
}
}
if (!rootKey || !clientKey || !forks) throw new Error('PDA 1.2 не содержит обязательные блоки');
if (!rootKey || !clientKey || !forks) throw new Error('PDA не содержит обязательные блоки');
const firstAddress = serverAddresses[0] || null;
const blockchain = activeBlockchainCompatibility(header.login, forks);
return {
@@ -279,7 +277,7 @@ export function parseShineUserPda(dataBytes) {
const formatMajor = reader.readU8();
const formatMinor = reader.readU8();
const recordLen = reader.readU16();
if (formatMajor !== FORMAT_MAJOR || formatMinor !== FORMAT_MINOR_CURRENT) throw new Error(`Неподдерживаемый формат PDA ${formatMajor}.${formatMinor}`);
if (formatMajor !== FORMAT_MAJOR || ![FORMAT_MINOR_PREVIOUS, FORMAT_MINOR_CURRENT].includes(formatMinor)) throw new Error(`Неподдерживаемый формат PDA ${formatMajor}.${formatMinor}`);
if (recordLen < 9 + 64 || recordLen > bytes.length) throw new Error('Некорректный record_len');
const createdAtMs = reader.readU64();
const updatedAtMs = reader.readU64();
@@ -313,6 +311,58 @@ function writeVariableBlock(out, blockType, writer) {
out[lenPos + 1] = (len >>> 8) & 0xff;
}
/** PDA 1.3 canonical signing message. Only the four limit bytes per fork are skipped.
* All physical length fields remain unchanged, so changing a limit preserves signatures.
*/
export function canonicalPdaSigningBytes(unsignedBytes) {
const bytes = toUint8Array(unsignedBytes);
if (bytes.length < 64 || new TextDecoder().decode(bytes.slice(0, 5)) !== MAGIC || bytes[5] !== 1 || bytes[6] !== 3) {
throw new Error('Ожидается unsigned PDA v1.3');
}
const rd16 = (i) => bytes[i] | (bytes[i + 1] << 8);
if (rd16(7) !== bytes.length + 64) throw new Error('Неверный record_len');
let c = 9 + 8 + 8 + 4 + 32;
c += 1 + bytes[c];
const blocks = bytes[c++];
const chunks = [bytes.slice(0, c)];
let registry = false;
for (let i = 0; i < blocks; i++) {
const start = c;
if (c + 2 > bytes.length) throw new Error('Обрезан PDA');
const type = bytes[c], ver = bytes[c + 1];
c += 2;
if (type === 1 || type === 2) {
c += 32;
if (c > bytes.length) throw new Error('Обрезан PDA');
chunks.push(bytes.slice(start, c));
continue;
}
if (c + 2 > bytes.length) throw new Error('Обрезан блок PDA');
const len = rd16(c); c += 2;
const end = c + len;
if (end > bytes.length) throw new Error('Обрезан payload PDA');
if (type === 3 && ver === 0) {
if (registry || c + 2 > end) throw new Error('Некорректный реестр fork');
registry = true;
const count = rd16(c);
if (!count || len !== 2 + count * 44) throw new Error('Некорректная длина реестра fork');
chunks.push(bytes.slice(start, c + 2));
c += 2;
for (let k = 0; k < count; k++) {
chunks.push(bytes.slice(c, c + 40)); // never sign these four limit bytes
c += 44;
}
if (c !== end) throw new Error('Некорректная длина fork');
} else chunks.push(bytes.slice(start, end));
c = end;
}
if (!registry || c !== bytes.length) throw new Error('Некорректная структура PDA');
const out = new Uint8Array(chunks.reduce((n, b) => n + b.length, 0));
let at = 0;
for (const chunk of chunks) { out.set(chunk, at); at += chunk.length; }
return out;
}
export function serializeUnsignedRecordFromState(stateLike) {
const state = stateLike || {};
const login = String(state.login || '');
@@ -379,7 +429,6 @@ export function serializeCreateUserPdaArgs(args) {
pushStrU8(out, args.login);
pushBytes(out, toUint8Array(args.rootKey32, 32));
pushU64LE(out, args.createdAtMs);
pushU64LE(out, BigInt(args.additionalLimitBytes || 0));
pushBytes(out, toUint8Array(args.clientKey32, 32));
pushBytes(out, toUint8Array(args.blockchainKey32, 32));
const addresses = normalizeServerAddresses(args.serverAddresses || []);
@@ -403,7 +452,6 @@ function serializeUpdateUserPdaArgs(args) {
pushStrU8(out, args.login);
pushBytes(out, toUint8Array(args.rootKey32, 32));
pushU64LE(out, args.updatedAtMs);
pushU64LE(out, BigInt(args.additionalLimitBytes || 0));
pushBytes(out, toUint8Array(args.clientKey32, 32));
out.push(Number(args.authMode) & 0xff);
if (args.newBlockchainKey32) {
@@ -570,7 +618,6 @@ async function createShineUserPdaOnSolana({
const blockchainKey32 = base64ToBytes(keyBundle.blockchainPair.publicKeyB64);
const clientKey32 = base64ToBytes(keyBundle.clientPair.publicKeyB64);
const rootPriv = await importPkcs8Ed25519(keyBundle.rootPair.privatePkcs8B64);
const bchPriv = await importPkcs8Ed25519(keyBundle.blockchainPair.privatePkcs8B64);
const ctx = await buildCommonContext({
login: cleanLogin,
clientPrivatePkcs8B64: keyBundle.clientPair.privatePkcs8B64,
@@ -587,8 +634,7 @@ async function createShineUserPdaOnSolana({
? [namespace.serverLogin] : accessServers;
const ecoInfo = await ctx.connection.getAccountInfo(ctx.economyConfigPda, 'confirmed');
if (!ecoInfo?.data) throw new Error('Economy config не инициализирован.');
const startBonusLimit = parseUsersEconomyConfig(new Uint8Array(ecoInfo.data)).startBonusLimit;
if (startBonusLimit > 0xffffffffn) throw new Error('Стартовый лимит не помещается в PDA 1.2 u32');
parseUsersEconomyConfig(new Uint8Array(ecoInfo.data)); // economy PDA presence/version
const createdAtMs = BigInt(Date.now());
const addresses = normalizeServerAddresses(serverAddresses, isServer ? { addressFormatType, addressFormatVersion, address: serverAddress } : null);
const initial = {
@@ -599,14 +645,13 @@ async function createShineUserPdaOnSolana({
prevRecordHash: new Uint8Array(32),
rootKey: rootKey32,
clientKey: clientKey32,
forks: [{ blockchainKey: blockchainKey32, createdAtMs, paidLimitBytes: startBonusLimit }],
forks: [{ blockchainKey: blockchainKey32, createdAtMs, paidLimitBytes: 0n }],
serverAddresses: addresses,
accessServers: effectiveAccessServers,
};
const unsigned = serializeUnsignedRecordFromState(initial);
const hash = await sha256Bytes(unsigned);
const hash = await sha256Bytes(canonicalPdaSigningBytes(unsigned));
const rootSig = await signBytes(rootPriv, hash);
const recordSig = await signBytes(bchPriv, hash);
// Namespace читается из цепи, комиссия никогда не берётся из старого economy.registrationFee.
const certMessage = registrar
@@ -617,9 +662,8 @@ async function createShineUserPdaOnSolana({
data: buildEd25519IxData(registrar, namespace.registrarPublicKey32, certMessage),
}) : null;
const ixData = serializeCreateUserPdaArgs({ login: rawLogin, rootKey32, createdAtMs, additionalLimitBytes: 0n, clientKey32, blockchainKey32, serverAddresses: addresses, accessServers: effectiveAccessServers, recordSignature64: recordSig, registrarSignature64: registrar });
const ixData = serializeCreateUserPdaArgs({ login: rawLogin, rootKey32, createdAtMs, clientKey32, blockchainKey32, serverAddresses: addresses, accessServers: effectiveAccessServers, recordSignature64: rootSig, registrarSignature64: registrar });
const rootIx = new ctx.solana.TransactionInstruction({ programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(rootSig, rootKey32, hash) });
const recordIx = new ctx.solana.TransactionInstruction({ programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(recordSig, blockchainKey32, hash) });
const createIx = new ctx.solana.TransactionInstruction({
programId: ctx.usersProgram,
keys: [
@@ -636,7 +680,7 @@ async function createShineUserPdaOnSolana({
try {
const tx = new ctx.solana.Transaction();
if (registrarIx) tx.add(registrarIx);
tx.add(rootIx, recordIx, createIx);
tx.add(rootIx, createIx);
const signature = await sendAndConfirmSolanaHttp(ctx.connection, tx, [ctx.payerKeypair]);
return { signature, userPda: ctx.userPda.toBase58(), pdaAddress: ctx.userPda.toBase58(), blockchainName: `${cleanLogin}-001`, registrationFeeLamports: namespace.registrationFeeLamports };
} catch (error) { throw await attachSolanaLogs(error, ctx.connection); }
@@ -692,7 +736,6 @@ export async function updateShineUserPdaOnSolana({
payerPrivatePkcs8B64 = '',
blockchainPrivatePkcs8B64,
authorityMode,
additionalLimitBytes = 0n,
newRootPublicKey32 = null,
newRootPrivatePkcs8B64 = '',
nextClientPublicKey32 = null,
@@ -709,8 +752,6 @@ export async function updateShineUserPdaOnSolana({
payerPrivatePkcs8B64: String(payerPrivatePkcs8B64 || blockchainPrivatePkcs8B64 || ''),
solanaEndpoint,
});
const addLimit = BigInt(additionalLimitBytes || 0);
if (addLimit < 0n || addLimit % LIMIT_STEP !== 0n) throw new Error(`Лимит можно увеличивать только шагом ${LIMIT_STEP}`);
const rootKey = newRootPublicKey32 ? toUint8Array(newRootPublicKey32, 32) : current.rootKey;
const clientKey = nextClientPublicKey32 ? toUint8Array(nextClientPublicKey32, 32) : current.clientKey;
const rootChanged = bytesToBase58(rootKey) !== bytesToBase58(current.rootKey);
@@ -719,10 +760,9 @@ export async function updateShineUserPdaOnSolana({
if ((rootChanged || clientChanged) && !fullKeyRotation) {
throw new Error('Root/client keys меняются только как полная ротация: новый root + новый client + новый blockchain fork');
}
const authMode = fullKeyRotation ? AUTH_MODE_ROOT : AUTH_MODE_BLOCKCHAIN;
if (authorityMode != null) {
const requestedMode = authorityMode === 'root' || authorityMode === AUTH_MODE_ROOT ? AUTH_MODE_ROOT : AUTH_MODE_BLOCKCHAIN;
if (requestedMode !== authMode) throw new Error(fullKeyRotation ? 'Полная ротация требует root authority' : 'Обычное обновление PDA выполняется blockchain authority');
const authMode = AUTH_MODE_ROOT; // Root is the sole user PDA authority in v1.3.
if (authorityMode != null && authorityMode !== 'root' && authorityMode !== 'blockchain' && authorityMode !== AUTH_MODE_ROOT && authorityMode !== AUTH_MODE_BLOCKCHAIN) {
throw new Error('Неподдерживаемый режим authority');
}
const updatedAtMs = BigInt(Date.now());
@@ -733,13 +773,8 @@ export async function updateShineUserPdaOnSolana({
if (forks.some((f) => bytesToBase58(f.blockchainKey) === bytesToBase58(appendedKey))) throw new Error('Этот blockchain key уже был в истории fork');
const lastForkAt = BigInt(forks.at(-1).createdAtMs);
if (!fullKeyRotation && updatedAtMs - lastForkAt < FORK_COOLDOWN_MS) throw new Error('Новый fork обычным blockchain authority можно создавать не чаще одного раза в 72 часа');
const newLimit = forks.at(-1).paidLimitBytes + addLimit;
if (newLimit > 0xffffffffn) throw new Error('paid_limit_bytes превышает u32');
forks.push({ blockchainKey: appendedKey, createdAtMs: updatedAtMs, paidLimitBytes: newLimit });
} else if (addLimit > 0n) {
const active = forks.at(-1);
active.paidLimitBytes += addLimit;
if (active.paidLimitBytes > 0xffffffffn) throw new Error('paid_limit_bytes превышает u32');
// Each new fork starts at 0 (unlimited); older forks keep their own limits.
forks.push({ blockchainKey: appendedKey, createdAtMs: updatedAtMs, paidLimitBytes: 0n });
}
let addresses = current.serverAddresses;
@@ -755,7 +790,8 @@ export async function updateShineUserPdaOnSolana({
createdAtMs: current.createdAtMs,
updatedAtMs,
recordNumber: current.recordNumber + 1,
prevRecordHash: await sha256Bytes(current.unsignedBytes),
prevRecordHash: await sha256Bytes(current.formatMinor === FORMAT_MINOR_CURRENT
? canonicalPdaSigningBytes(current.unsignedBytes) : current.unsignedBytes),
rootKey,
clientKey,
forks,
@@ -763,29 +799,21 @@ export async function updateShineUserPdaOnSolana({
accessServers: nextAccess,
};
const unsigned = serializeUnsignedRecordFromState(next);
const hash = await sha256Bytes(unsigned);
const oldAuthorityPub = fullKeyRotation ? current.rootKey : current.forks.at(-1).blockchainKey;
const oldAuthorityPrivB64 = fullKeyRotation ? rootPrivatePkcs8B64 : blockchainPrivatePkcs8B64;
if (!oldAuthorityPrivB64) throw new Error(fullKeyRotation ? 'Для полной ротации нужен старый root private key' : 'Для обновления PDA нужен blockchain private key');
const oldAuthorityPriv = await importPkcs8Ed25519(oldAuthorityPrivB64);
const authSig = await signBytes(oldAuthorityPriv, hash);
let recordSignerPub;
let recordSignerPrivB64;
if (appendedKey) {
recordSignerPub = appendedKey;
recordSignerPrivB64 = newBlockchainPrivatePkcs8B64;
} else {
recordSignerPub = current.forks.at(-1).blockchainKey;
recordSignerPrivB64 = blockchainPrivatePkcs8B64;
}
if (!recordSignerPrivB64) throw new Error('Нет приватного ключа нового authority для подписи новой PDA');
const recordSignerPriv = await importPkcs8Ed25519(recordSignerPrivB64);
const recordSig = await signBytes(recordSignerPriv, hash);
const authIx = new ctx.solana.TransactionInstruction({ programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(authSig, oldAuthorityPub, hash) });
const recordIx = new ctx.solana.TransactionInstruction({ programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(recordSig, recordSignerPub, hash) });
const hash = await sha256Bytes(canonicalPdaSigningBytes(unsigned));
if (!rootPrivatePkcs8B64) throw new Error('Для изменения PDA нужен приватный Root Key');
const oldRootPriv = await importPkcs8Ed25519(rootPrivatePkcs8B64);
// Never allow an old root to authorize replacing itself without a new root signature.
const oldRootSig = await signBytes(oldRootPriv, hash);
const nextRootPriv = rootChanged
? await importPkcs8Ed25519(newRootPrivatePkcs8B64)
: oldRootPriv;
const recordSig = rootChanged ? await signBytes(nextRootPriv, hash) : oldRootSig;
const authIx = rootChanged ? new ctx.solana.TransactionInstruction({
programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(oldRootSig, current.rootKey, hash),
}) : null;
const recordIx = new ctx.solana.TransactionInstruction({
programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(recordSig, rootKey, hash),
});
const updateIx = new ctx.solana.TransactionInstruction({
programId: ctx.usersProgram,
keys: [
@@ -796,10 +824,10 @@ export async function updateShineUserPdaOnSolana({
{ pubkey: ctx.sysvarInstructions, isSigner: false, isWritable: false },
{ pubkey: ctx.economyConfigPda, isSigner: false, isWritable: false },
],
data: serializeUpdateUserPdaArgs({ login: current.login, rootKey32: rootKey, updatedAtMs, additionalLimitBytes: addLimit, clientKey32: clientKey, authMode, newBlockchainKey32: appendedKey, serverAddresses: addresses, accessServers: nextAccess, recordSignature64: recordSig }),
data: serializeUpdateUserPdaArgs({ login: current.login, rootKey32: rootKey, updatedAtMs, clientKey32: clientKey, authMode, newBlockchainKey32: appendedKey, serverAddresses: addresses, accessServers: nextAccess, recordSignature64: recordSig }),
});
try {
const signature = await sendAndConfirmSolanaHttp(ctx.connection, new ctx.solana.Transaction().add(authIx, recordIx, updateIx), [ctx.payerKeypair]);
const signature = await sendAndConfirmSolanaHttp(ctx.connection, new ctx.solana.Transaction().add(...(authIx ? [authIx] : []), recordIx, updateIx), [ctx.payerKeypair]);
return { signature, userPda: ctx.userPda.toBase58(), pdaAddress: ctx.userPda.toBase58(), paidLimitBytes: forks.at(-1).paidLimitBytes, forkCount: forks.length };
} catch (error) { throw await attachSolanaLogs(error, ctx.connection); }
}
@@ -811,20 +839,11 @@ export async function updateServerOnSolana({ login, keyBundle, serverAddress, se
rootPrivatePkcs8B64: keyBundle.rootPair.privatePkcs8B64,
blockchainPrivatePkcs8B64: keyBundle.blockchainPair.privatePkcs8B64,
clientPrivatePkcs8B64: keyBundle.clientPair.privatePkcs8B64,
authorityMode: 'blockchain',
authorityMode: 'root',
serverAddresses: serverAddresses || [{ addressFormatType, addressFormatVersion, address: serverAddress }],
});
}
export function calcLimitTopupPriceLamports(additionalLimitBytes, lamportsPerLimitStep) {
const add = BigInt(additionalLimitBytes || 0);
const pricePerStep = BigInt(lamportsPerLimitStep || 0);
if (add < 0n || add % LIMIT_STEP !== 0n) throw new Error(`Увеличение лимита должно быть кратно ${LIMIT_STEP} байт`);
return (add / LIMIT_STEP) * pricePerStep;
}
export function getLimitStepBytes() { return LIMIT_STEP; }
function supportData(tag, senderLogin, recipientLogin, amountLamports, starCents, target) {
const out = [tag];
const putString = (value) => { const bytes = new TextEncoder().encode(String(value)); if (bytes.length > 255) throw new Error('Слишком длинный login'); out.push(bytes.length, ...bytes); };
@@ -7,6 +7,16 @@ export function setSolanaCluster(value) {
cluster = next;
}
export function getSolanaCluster() { return cluster; }
export function makeSolanaExplorerTxUrl(signature, endpoint = '') {
const cleanSignature = String(signature || '').trim();
if (!cleanSignature) return '';
const configured = getSolanaCluster();
const source = String(endpoint || '').trim().toLowerCase();
const network = configured || (source.includes('devnet') ? 'devnet' : source.includes('testnet') ? 'testnet' : 'mainnet-beta');
const url = new URL(`https://explorer.solana.com/tx/${encodeURIComponent(cleanSignature)}`);
if (network !== 'mainnet-beta') url.searchParams.set('cluster', network);
return url.toString();
}
export function rpcEndpointFromShineHttp(httpBase) {
const base = String(httpBase || '').trim();
if (!/^https?:\/\//i.test(base)) throw new Error('SHiNE server HTTP address is unavailable');
@@ -174,6 +174,12 @@ export async function loadProfileSnapshot(login) {
};
}
export function profileDisplayName(snapshot, fallback = '') {
const fields = Array.isArray(snapshot?.fields) ? snapshot.fields : [];
const valueOf = (key) => String(fields.find((field) => field?.key === key)?.value || '').trim();
return [valueOf('first_name'), valueOf('last_name')].filter(Boolean).join(' ') || String(fallback || '').trim();
}
export async function saveProfileParamBlock(login, key, value) {
const storagePwd = await getStoragePwd();
await authService.addBlockUserParam({
@@ -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-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; }
+7
View File
@@ -93,6 +93,13 @@
}
.chat-external-link-url {
margin: 0;
word-break: break-word;
user-select: text;
}
.bubble-meta {
margin-top: 4px;
display: flex;
+19
View File
@@ -269,3 +269,22 @@
height: 1px;
pointer-events: none;
}
/* V4: два Canvas поверх статичного фона. Старый анимированный ::before
* принадлежит DOM-движку V1/V3 и не должен работать на Canvas-странице. */
.network-explorer--canvas .fg-stage::before { display: none; }
.network-explorer--canvas .fg-canvas-v4 {
position: absolute;
inset: 0;
display: block;
z-index: 1;
touch-action: none;
user-select: none;
}
.network-explorer--canvas .fg-canvas-v4--edges { pointer-events: none; }
.network-explorer--canvas .fg-canvas-v4--nodes {
z-index: 2;
cursor: grab;
}
.network-explorer--canvas .fg-canvas-v4--nodes.is-over-node { cursor: pointer; }
.network-explorer--canvas .fg-canvas-v4--nodes:active { cursor: grabbing; }
+14 -3
View File
@@ -32,10 +32,11 @@
border-bottom: 1px solid var(--divider-soft);
}
.notification-card__head { display: flex; align-items: baseline; gap: var(--space-2); min-width: 0; }
.notification-card__head { display: flex; align-items: start; gap: var(--space-2); min-width: 0; }
.notification-card__identity { display: grid; flex: 1 1 auto; min-width: 0; gap: 1px; }
.notification-card__name {
flex: 1 1 auto;
min-width: 0;
color: var(--text-primary);
font-size: var(--text-md);
@@ -45,7 +46,17 @@
white-space: nowrap;
}
.notification-card__time { flex: 0 0 auto; color: var(--text-secondary); font-size: var(--text-xs); }
.notification-card__login {
min-width: 0;
overflow: hidden;
color: var(--text-secondary);
font-size: var(--text-xs);
line-height: var(--leading-xs);
text-overflow: ellipsis;
white-space: nowrap;
}
.notification-card__time { flex: 0 0 auto; padding-top: 2px; color: var(--text-secondary); font-size: var(--text-xs); }
/* Непрочитанное: точка-акцент перед временем. */
.notification-card--new .notification-card__time::before {
+71 -8
View File
@@ -898,6 +898,7 @@
position: fixed;
inset: 0;
z-index: 12000;
display: grid;
place-items: center;
padding: 24px;
background: var(--surface);
@@ -906,9 +907,12 @@
}
.secret-generation-overlay[hidden] { display: none; }
.secret-generation-card {
width: min(100%, 290px);
width: min(100%, 350px);
place-items: center;
gap: 16px;
padding: 28px 24px;
border: 1px solid color-mix(in srgb, var(--accent) 18%, transparent);
border-radius: 20px;
@@ -930,15 +934,16 @@
.secret-generation-title {
color: var(--preauth-ivory, var(--text-primary));
font-size: 18px;
font-weight: 650;
font-size: 21px;
line-height: 1.3;
font-weight: 700;
}
.secret-generation-progress {
min-height: 20px;
color: var(--preauth-muted, var(--accent));
font-size: 13px;
.secret-generation-description {
margin: 0;
color: var(--preauth-muted, var(--text-secondary));
font-size: 14px;
line-height: 1.5;
}
@@ -1593,6 +1598,12 @@
width: 100%;
padding-right: 50px;
}
/* Keep input, eye button and mask aligned at 32 monospaced characters. */
.auth-password-field--multiline {
width: min(100%, calc(32ch + 64px));
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 16px;
}
.auth-password-field__toggle {
position: absolute;
right: 2px;
@@ -1619,3 +1630,55 @@
width: 21px;
height: 21px;
}
/* Адаптивная парольная фраза: от одной до трёх строк, при любом количестве символов. */
.auth-password-field > .input.auth-password-field__textarea {
display: block;
/* 32 characters when space allows; on narrow screens the field shrinks. */
width: 100%;
min-height: 0;
height: auto;
padding: 10px 50px 10px 12px;
resize: none;
overflow-y: auto;
/* A scrollbar would steal one character column and misalign the bullet mirror. */
scrollbar-width: none;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 16px;
line-height: 24px;
overflow-wrap: anywhere;
word-break: break-all;
box-sizing: border-box;
}
.auth-password-field__textarea::-webkit-scrollbar { display: none; }
.auth-password-field__mask {
position: absolute;
inset: 0;
box-sizing: border-box;
border: 1px solid transparent;
border-radius: 12px;
padding: 10px 50px 10px 12px;
overflow: hidden;
pointer-events: none;
white-space: pre-wrap;
overflow-wrap: anywhere;
word-break: break-all;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 16px;
line-height: 24px;
color: var(--text-primary);
text-align: start;
}
.auth-password-field__mask[hidden] { display: none; }
.auth-password-field--masked > .auth-password-field__textarea {
color: transparent;
-webkit-text-fill-color: transparent;
caret-color: var(--accent);
}
.auth-password-field__textarea:focus + .auth-password-field__mask {
color: var(--text-primary);
}
.auth-password-field > .auth-password-field__textarea + .auth-password-field__mask + .auth-password-field__toggle {
top: 2px;
transform: none;
}
@@ -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);
}
});
+38
View File
@@ -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'), '');
});
Binary file not shown.
@@ -76,6 +76,25 @@ test('HEADER и PostgreSQL требуют неизменяемого регис
assert.match(migration, /NEW\.login IS DISTINCT FROM OLD\.login/);
});
test('runtime-state блокчейна использует normalized_login, не отображаемое написание', () => {
const migration = readFileSync(new URL('../../SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v43.sql', import.meta.url), 'utf8');
const state = readFileSync(new URL('../../SHiNE-server/shine-server-db/src/main/java/shine/db/entities/BlockchainStateEntry.java', import.meta.url), 'utf8');
assert.match(migration, /FOREIGN KEY \(login\) REFERENCES user_identity_current\(normalized_login\)/);
assert.match(migration, /SET login = LOWER\(BTRIM\(login\)\)/);
assert.match(migration, /NEW\.login := LOWER\(BTRIM\(NEW\.login\)\)/);
assert.match(state, /toLowerCase\(Locale\.ROOT\)/);
});
test('адресат уведомления хранится и ищется по normalized_login', () => {
const migration = readFileSync(new URL('../../SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v44.sql', import.meta.url), 'utf8');
const dao = readFileSync(new URL('../../SHiNE-server/shine-server-db/src/main/java/shine/db/dao/UserNotificationsStateDAO.java', import.meta.url), 'utf8');
assert.match(migration, /SET owner_login = LOWER\(BTRIM\(owner_login\)\)/);
assert.match(migration, /NEW\.owner_login := LOWER\(BTRIM\(NEW\.owner_login\)\)/);
assert.match(dao, /ps\.setString\(i\+\+, normalizedLogin\(e\.getOwnerLogin\(\)\)\)/);
assert.match(dao, /ps\.setString\(1, normalizedLogin\(ownerLogin\)\)/);
assert.match(dao, /toLowerCase\(Locale\.ROOT\)/);
});
test('лента, список подписок и дерево обсуждения возвращают оригинальный регистр автора', () => {
const base = new URL('../../SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/handlers/channels/', import.meta.url);
const read = (file) => readFileSync(new URL(file, base), 'utf8');
+118
View File
@@ -0,0 +1,118 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createExplorerGraph } from '../js/pages/network-explorer/graph-model.js';
import { PALETTES, edgeGradient, edgeCoreGradient, geometryFor } from '../js/pages/network-canvas-v4/graph-style.js';
import { readFileSync } from 'node:fs';
const capture = () => {
const stops = [];
return { stops, ctx: { createLinearGradient(x1, y1, x2, y2) {
assert.deepEqual([x1, y1, x2, y2], [10, 20, 100, 200]);
return { addColorStop(offset, value) { stops.push([offset, value]); } };
} } };
};
const geo = { x1: 10, y1: 20, x2: 100, y2: 200 };
test('V4: двусторонняя связь сохраняет разные цвета у начала и конца', () => {
const { ctx, stops } = capture();
edgeGradient(ctx, geo, { relationType: 'friend', reverseRelationType: 'close_friend', mutual: true }, PALETTES.dark);
assert.deepEqual(stops, [[0, 'rgba(120,179,255,0.98)'], [1, 'rgba(255,76,92,0.98)']]);
});
test('V4: односторонняя связь затухает в направлении адресата', () => {
const { ctx, stops } = capture();
edgeGradient(ctx, geo, { relationType: 'friend', mutual: false }, PALETTES.dark);
assert.deepEqual(stops, [[0, 'rgba(120,179,255,0.98)'], [1, 'rgba(120,179,255,0.035)']]);
});
test('V4: края рёбер касаются сферы, маленькая сфера имеет половину радиуса', () => {
const origin = { x: 0, y: 0 };
const parent = { id: 'a', x: 0, y: 0, visualSmall: false };
const child = { id: 'b', x: 100, y: 0, visualSmall: true };
const g = geometryFor(parent, child, 1, origin, origin);
assert.equal(g.x1, 29);
assert.equal(g.x2, 100 - 14.5);
const doubled = geometryFor(parent, child, 2, origin, origin);
assert.equal(doubled.x1, 58);
assert.equal(doubled.x2, 200 - 29);
});
test('V4: данные V3 с обратным отношением поступают в визуальную модель без потерь', () => {
const graph = createExplorerGraph();
graph.add({ login: 'alice', outFriends: ['bob'], allUsers: [{ login: 'bob', shine: true }] });
graph.add({ login: 'bob', outCloseFriends: ['alice'], allUsers: [{ login: 'alice', shine: true }] });
const model = graph.snapshot('alice', { depth: 1 });
const link = model.nodes.find((n) => n.id === 'bob').edgeParents[0];
assert.equal(link.relationType, 'friend');
assert.equal(link.reverseRelationType, 'close_friend');
assert.ok(model.nodes.every((n) => n.shining));
});
test('V4: статичная Canvas-архитектура не запускает постоянную анимацию', () => {
const js = readFileSync(new URL('../js/pages/network-canvas-v4/graph-renderer.js', import.meta.url), 'utf8');
assert.match(js, /requestAnimationFrame\(\(\) =>/);
assert.doesNotMatch(js, /setInterval\(/);
assert.match(js, /MAX_SPRITES_PER_FRAME/);
assert.match(js, /for \(const node of nodes\)/);
assert.match(js, /const shining = Boolean\(node\.shining && parent\.shining\)/);
});
test('V4: стеклянная кромка восстановлена, фото сверху, цветных колец нет', () => {
const js = readFileSync(new URL('../js/pages/network-canvas-v4/graph-renderer.js', import.meta.url), 'utf8');
assert.match(js, /glass_overlay_faithful\.png/);
assert.match(js, /const GLASS_SCALE = 1\.19/);
assert.match(js, /if \(glassReady && glass\?\.naturalWidth\)/);
assert.match(js, /g\.drawImage\(glass, 0, 0, side, side\);/);
assert.match(js, /g\.drawImage\(img,/);
assert.ok(js.indexOf('g.drawImage(glass, 0, 0, side, side);') < js.indexOf('g.drawImage(img,'),
'непрозрачная фотография должна рисоваться после стекла');
assert.doesNotMatch(js, /const ring = node\.shining/);
assert.match(js, /if \(!node\.shining\) continue;/);
});
test('V4: неон V3 — размытый flare и tube плюс чёткое светлое ядро', () => {
const js = readFileSync(new URL('../js/pages/network-canvas-v4/graph-renderer.js', import.meta.url), 'utf8');
assert.match(js, /drawStroke\(flareCtx, path, 16 \* zoom/);
assert.match(js, /drawStroke\(tubeCtx, path, 6 \* zoom/);
assert.match(js, /blur\(\$\{\(6 \* zoom\)/);
assert.match(js, /blur\(\$\{\(2 \* zoom\)/);
assert.match(js, /globalCompositeOperation = 'screen'/);
assert.match(js, /edgeCoreGradient\(ectx, geo, ref, palette\)/);
assert.doesNotMatch(js, /shadowBlur/);
});
test('V4: светлая сердцевина сохраняет разные цвета и затухание', () => {
const { ctx, stops } = capture();
edgeCoreGradient(ctx, geo, { relationType: 'friend', reverseRelationType: 'close_friend', mutual: false }, PALETTES.dark);
assert.equal(stops.length, 2);
assert.ok(stops[0][1].startsWith('rgba(206,228,255,'), 'светлое голубое начало');
assert.ok(stops[1][1].startsWith('rgba(255,191,196,'), 'светло-красное окончание');
assert.ok(stops[1][1].endsWith(',0.035)'), 'затухание односторонней связи');
});
test('V4: подписи используют плашки V2, а не контур вокруг букв', () => {
const js = readFileSync(new URL('../js/pages/network-canvas-v4/graph-renderer.js', import.meta.url), 'utf8');
assert.match(js, /ctx\.roundRect\(x0, y0, w, h, h \/ 2\)/);
assert.match(js, /words\[1\]\[0\]/);
assert.match(js, /if \(collides\(bounds\)\)/);
assert.doesNotMatch(js, /ctx\.strokeText\(/);
});
test('V3/V4: вход через нижнюю кнопку очищает исследование; переключатель версий не очищает', () => {
const toolbar = readFileSync(new URL('../js/components/toolbar.js', import.meta.url), 'utf8');
const switcher = readFileSync(new URL('../js/pages/network-version-switcher.js', import.meta.url), 'utf8');
const view = readFileSync(new URL('../js/pages/network-explorer/network-view.js', import.meta.url), 'utf8');
assert.match(toolbar, /dispatchEvent\(new Event\('shine:network-tab-enter'\)\)/);
assert.match(switcher, /addEventListener\('shine:network-tab-enter', explorerNetworkView\.resetExplorerOnTabEntry\)/);
assert.match(view, /export function resetExplorerOnTabEntry\(\)/);
assert.match(view, /retained = null;/);
assert.match(view, /resetBarrier = resetBarrier\.catch\(\(\) => \{\}\)\.then\(\(\) => clearExplorerGraphCache\(\)\)/);
assert.match(view, /void resetBarrier\.then\(async \(\) =>/);
assert.doesNotMatch(switcher, /select\.addEventListener\('change',[\s\S]*resetExplorerOnTabEntry/);
});
test('V4 Canvas открывается по умолчанию, но ранее выбранная версия сохраняется', () => {
const switcher = readFileSync(new URL('../js/pages/network-version-switcher.js', import.meta.url), 'utf8');
assert.match(switcher, /const DEFAULT_MODE = 'explorer-canvas';/);
assert.match(switcher, /MODES\.has\(saved\) \? saved : DEFAULT_MODE/);
});
@@ -0,0 +1,19 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
const page = readFileSync(new URL('../js/pages/notifications-view.js', import.meta.url), 'utf8');
const css = readFileSync(new URL('../styles/features/notifications.css', import.meta.url), 'utf8');
test('уведомление показывает логин автора под отображаемым именем', () => {
assert.match(page, /notification-card__login/);
assert.match(page, /login\.textContent = item\.sourceLogin/);
assert.match(css, /\.notification-card__login/);
});
test('ответная связь повторяет тип входящей связи', () => {
assert.match(page, /CONNECTION_CLOSE_FRIEND[\s\S]*\? 'close_friend'[\s\S]*: 'friend'/);
assert.match(page, /kind, enabled: true/);
assert.match(page, /text_072/);
assert.match(page, /text_073/);
});

Some files were not shown because too many files have changed in this diff Show More