Доделать смену ключей в новой версии

Добавлена доработка сценариев ротации ключей, закрытия сессий и повторного шифрования DM.

Версия пока не проверена полностью, но ожидается рабочей.
This commit is contained in:
AidarKC
2026-10-06 18:42:55 +03:00
parent 72e62127b3
commit 79598fffa6
58 changed files with 1084 additions and 125 deletions
@@ -45,7 +45,8 @@ public final class BodyRecordParser {
|| st == (MsgSubType.TEXT_COURSE & 0xFFFF)
|| st == (MsgSubType.TEXT_ENTRYPOINT & 0xFFFF)
|| st == (MsgSubType.TEXT_REPOST & 0xFFFF)
|| st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF)) {
|| st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF)
|| st == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF)) {
yield new TextLineBody(subType, version, bodyBytes);
}
@@ -81,6 +81,9 @@ public final class MsgSubType {
*/
public static final short TEXT_CHANNEL_META = 90;
/** CHANNEL_DELETE — soft-delete marker for a channel line. */
public static final short TEXT_CHANNEL_DELETE = 92;
/** ENTRYPOINT — входная страница канала (line-based). */
public static final short TEXT_ENTRYPOINT = 100;
/** EXERCISE — упражнение/комплекс (line-based). */
@@ -73,7 +73,7 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
this.toBlockHash32 = null;
}
boolean allowEmpty = st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF) || st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF);
boolean allowEmpty = st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF) || st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF) || st == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF);
this.message = readText(bb, allowEmpty);
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected TextLineBody tail");
}
@@ -125,6 +125,8 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
}
if (st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF)) {
if (message == null) throw new IllegalArgumentException("CHANNEL_META message is null");
} else if (st == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF)) {
if (message == null || !message.isEmpty()) throw new IllegalArgumentException("CHANNEL_DELETE message must be empty");
} else if (message == null || message.isBlank()) {
throw new IllegalArgumentException("Text message is blank");
}
@@ -167,6 +169,7 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
int st = subType & 0xFFFF;
return st == (MsgSubType.TEXT_POST & 0xFFFF) || st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)
|| st == (MsgSubType.TEXT_REPOST & 0xFFFF) || st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF)
|| st == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF)
|| st == (MsgSubType.TEXT_ENTRYPOINT & 0xFFFF) || st == (MsgSubType.TEXT_EXERCISE & 0xFFFF)
|| st == (MsgSubType.TEXT_SERVICE & 0xFFFF) || st == (MsgSubType.TEXT_COURSE & 0xFFFF);
}
@@ -21,8 +21,9 @@ public final class DatabaseInitializer {
public static final String DB_FORMAT_MARKER = "SHiNE_DB_V2";
public static final int DB_FORMAT_VERSION = 2;
public static final int SCHEMA_VERSION_1 = 1;
public static final int SCHEMA_VERSION_30 = 30;
public static final int SCHEMA_VERSION_31 = 31;
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
private DatabaseInitializer() {}
@@ -33,6 +34,7 @@ public final class DatabaseInitializer {
public static final short TEXT_RATING = 30;
public static final short TEXT_REPOST = 50;
public static final short TEXT_CHANNEL_META = 90;
public static final short TEXT_CHANNEL_DELETE = 92;
public static final short TEXT_ENTRYPOINT = 100;
public static final short TEXT_EXERCISE = 110;
public static final short TEXT_SERVICE = 120;
@@ -113,9 +115,13 @@ public final class DatabaseInitializer {
validateDatabaseFormatV2(conn);
int currentVersion = readCurrentSchemaVersion(conn);
if (currentVersion != SCHEMA_VERSION_30) {
if (currentVersion == 30) {
runSqlScript(conn, POSTGRES_MIGRATION_V31_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion != SCHEMA_VERSION_31) {
throw new SQLException(
"Unsupported SHiNE DB v2 schema version: expected 30, found " + currentVersion);
"Unsupported SHiNE DB v2 schema version: expected 31, found " + currentVersion);
}
}
}
@@ -38,6 +38,7 @@ public final class MsgSubType {
/** CHANNEL_META — скрытый технический снимок профиля канала. */
public static final short TEXT_CHANNEL_META = 90;
public static final short TEXT_CHANNEL_DELETE = 92;
/** ENTRYPOINT — входная страница канала (line-based). */
public static final short TEXT_ENTRYPOINT = 100;
@@ -269,6 +269,57 @@ public final class ActiveSessionsDAO {
}
}
/**
* Удаляет все сессии пользователя, кроме указанной текущей, и возвращает их sessionId.
* Вариант с Connection используется внутри транзакции запуска key rotation.
*/
public List<String> deleteOtherSessions(Connection c, String login, String keepSessionId) throws SQLException {
List<String> sessionIds = new ArrayList<>();
String selectSql = """
SELECT session_id
FROM active_sessions
WHERE LOWER(login) = LOWER(?)
AND session_id <> ?
""";
try (PreparedStatement ps = c.prepareStatement(selectSql)) {
ps.setString(1, login);
ps.setString(2, keepSessionId == null ? "" : keepSessionId);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) sessionIds.add(rs.getString(1));
}
}
if (sessionIds.isEmpty()) return sessionIds;
String deleteSql = """
DELETE FROM active_sessions
WHERE LOWER(login) = LOWER(?)
AND session_id <> ?
""";
try (PreparedStatement ps = c.prepareStatement(deleteSql)) {
ps.setString(1, login);
ps.setString(2, keepSessionId == null ? "" : keepSessionId);
ps.executeUpdate();
}
return sessionIds;
}
public List<String> deleteOtherSessions(String login, String keepSessionId) throws SQLException {
try (Connection c = db.getConnection()) {
boolean oldAutoCommit = c.getAutoCommit();
c.setAutoCommit(false);
try {
List<String> ids = deleteOtherSessions(c, login, keepSessionId);
c.commit();
return ids;
} catch (SQLException e) {
c.rollback();
throw e;
} finally {
c.setAutoCommit(oldAutoCommit);
}
}
}
// -------------------- MAPPER --------------------
private ActiveSessionEntry mapRow(ResultSet rs) throws SQLException {
@@ -120,6 +120,27 @@ public final class ChannelNameStateDAO {
insert(c, entry);
}
}
public boolean updateDeletedState(Connection c, String ownerBchName, int rootBlockNumber, boolean deleted, long deletedAtMs, Integer deletedBlockNumber) throws SQLException {
String sql = """
UPDATE channel_names_state
SET is_deleted = ?,
deleted_at_ms = ?,
deleted_block_number = ?
WHERE owner_bch_name = ?
AND channel_root_block_number = ?
AND is_deleted IS DISTINCT FROM ?
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setBoolean(1, deleted);
ps.setLong(2, deleted ? Math.max(0L, deletedAtMs) : 0L);
if (deleted && deletedBlockNumber != null) ps.setInt(3, deletedBlockNumber); else ps.setNull(3, java.sql.Types.INTEGER);
ps.setString(4, ownerBchName);
ps.setInt(5, rootBlockNumber);
ps.setBoolean(6, deleted);
return ps.executeUpdate() > 0;
}
}
public String getSlugByOwnerAndRoot(String ownerBchName, int rootBlockNumber) throws SQLException {
String sql = "SELECT slug FROM channel_names_state WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number=? LIMIT 1";
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
@@ -80,6 +80,7 @@ public final class ChannelReadStateDAO {
WHERE LOWER(cns.owner_login)=LOWER(crs.owner_login)
AND cns.slug=crs.channel_name
AND cns.channel_type_code=1
AND NOT cns.is_deleted
)
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -377,6 +377,7 @@ public final class SignedMessagesDAO {
String peerLogin,
long beforeTimeMs,
String beforeMessageKey,
long reencryptedBeforeMs,
int limit
) throws Exception {
try (Connection c = db.getConnection()) {
@@ -398,6 +399,7 @@ public final class SignedMessagesDAO {
OR time_ms < ?
OR (time_ms = ? AND (? = '' OR message_key < ?))
)
AND (? <= 0 OR (created_at_ms <= ? AND reencrypted_at_ms < ?))
ORDER BY time_ms DESC, message_key DESC
LIMIT ?
""".formatted(messagesTable());
@@ -413,7 +415,10 @@ public final class SignedMessagesDAO {
ps.setLong(8, beforeTimeMs);
ps.setString(9, beforeMessageKey == null ? "" : beforeMessageKey);
ps.setString(10, beforeMessageKey == null ? "" : beforeMessageKey);
ps.setInt(11, limit);
ps.setLong(11, reencryptedBeforeMs);
ps.setLong(12, reencryptedBeforeMs);
ps.setLong(13, reencryptedBeforeMs);
ps.setInt(14, limit);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) out.add(mapRow(rs));
}
@@ -422,6 +427,102 @@ public final class SignedMessagesDAO {
}
}
public long countMessagesNeedingReencryption(String login, long reencryptedBeforeMs) throws SQLException {
if (reencryptedBeforeMs <= 0) return 0;
try (Connection c = db.getConnection();
PreparedStatement ps = c.prepareStatement("""
SELECT COUNT(*)
FROM %s
WHERE LOWER(target_login) = LOWER(?)
AND message_type IN (1, 2)
AND created_at_ms <= ?
AND reencrypted_at_ms < ?
""".formatted(messagesTable()))) {
ps.setString(1, login);
ps.setLong(2, reencryptedBeforeMs);
ps.setLong(3, reencryptedBeforeMs);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? rs.getLong(1) : 0L;
}
}
}
/** Обновляет только уже существующую локальную type=1/2 копию при key rotation. */
public ApplyStatus upsertReencryptedLocalCopy(SignedMessageEntry next) throws Exception {
return withBusyRetry(() -> {
try (Connection c = db.getConnection()) {
boolean oldAutoCommit = c.getAutoCommit();
c.setAutoCommit(false);
try {
SignedMessageEntry current = getByMessageKey(c, next.getMessageKey());
if (current == null) { c.rollback(); return ApplyStatus.DUPLICATE_OR_OLDER; }
if (current.getMessageType() != next.getMessageType()
|| current.getTimeMs() != next.getTimeMs()
|| current.getNonce() != next.getNonce()
|| current.getRevisionTimeMs() != next.getRevisionTimeMs()
|| !current.getFromLogin().equalsIgnoreCase(next.getFromLogin())
|| !current.getToLogin().equalsIgnoreCase(next.getToLogin())
|| !current.getBaseKey().equals(next.getBaseKey())
|| next.getReencryptedAtMs() <= current.getReencryptedAtMs()) {
c.rollback();
return ApplyStatus.DUPLICATE_OR_OLDER;
}
updateReencryptedLocalCopy(c, next);
DmDialogStateDAO.getInstance().refreshConversationPair(c, next.getFromLogin(), next.getToLogin());
c.commit();
return ApplyStatus.APPLIED;
} catch (Exception e) {
try { c.rollback(); } catch (Exception ignored) {}
throw e;
} finally {
c.setAutoCommit(oldAutoCommit);
}
}
});
}
/**
* Перезаписывает только криптографическую локальную копию сообщения при key rotation.
* Исторические metadata (created_at_ms/source_api/origin_session_id/read_at_ms) сохраняются.
*/
private void updateReencryptedLocalCopy(Connection c, SignedMessageEntry next) throws SQLException {
String sql = """
UPDATE %s
SET reencrypted_at_ms = ?,
raw_block = ?
WHERE message_key = ?
AND reencrypted_at_ms < ?
""".formatted(messagesTable());
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setLong(1, next.getReencryptedAtMs());
ps.setBytes(2, next.getRawBlock());
ps.setString(3, next.getMessageKey());
ps.setLong(4, next.getReencryptedAtMs());
int changed = ps.executeUpdate();
if (changed != 1) {
throw new SQLException("Reencrypted local copy was not updated: " + next.getMessageKey());
}
}
}
private SignedMessageEntry getByMessageKey(Connection c, String messageKey) throws SQLException {
String sql = """
SELECT
message_key, base_key, target_login, from_login, to_login,
time_ms, nonce, message_type, revision_time_ms, reencrypted_at_ms,
raw_block, created_at_ms, source_api, origin_session_id,
receipt_ref_base_key, receipt_ref_type, read_at_ms
FROM %s
WHERE message_key = ?
""".formatted(messagesTable());
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, messageKey);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? mapRow(rs) : null;
}
}
}
public SyncBatch listSyncBatch(
String ownerLogin,
long afterStoredAtMs,
@@ -111,31 +111,48 @@ public final class UserProfileStateDAO {
return out;
}
public List<ChannelCard> listPublicChannels(Connection c, String login, String mode, int limit, int offset) throws SQLException {
public List<ChannelCard> listPublicChannels(Connection c, String login, String mode, boolean includeDeleted, int limit, int offset) throws SQLException {
int safeLimit=Math.max(1,Math.min(limit<=0?100:limit,500)), safeOffset=Math.max(0,offset);
String sql;
if ("owned".equals(mode)) {
sql="""
SELECT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.owner_bch_name, cn.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash
FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(?) AND cn.channel_type_code=1
SELECT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.owner_bch_name,
cn.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash,
cn.is_deleted, cn.deleted_at_ms, cn.deleted_block_number
FROM channel_names_state cn
WHERE LOWER(cn.owner_login)=LOWER(?) AND cn.channel_type_code=1 AND (? OR NOT cn.is_deleted)
ORDER BY cn.display_name, cn.slug LIMIT ? OFFSET ?
""";
} else if ("following".equals(mode)) {
sql="""
SELECT DISTINCT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.owner_bch_name, cn.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash
FROM connections_state cs JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login) AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash
WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=30 AND cn.channel_type_code=1
SELECT DISTINCT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.owner_bch_name,
cn.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash,
cn.is_deleted, cn.deleted_at_ms, cn.deleted_block_number
FROM connections_state cs
JOIN channel_names_state cn
ON LOWER(cn.owner_login)=LOWER(cs.to_login)
AND cn.channel_root_block_number=cs.to_block_number
AND cn.channel_root_block_hash=cs.to_block_hash
WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=30 AND cn.channel_type_code=1 AND (? OR NOT cn.is_deleted)
ORDER BY cn.display_name, cn.slug LIMIT ? OFFSET ?
""";
} else throw new IllegalArgumentException("Unsupported channel mode: "+mode);
List<ChannelCard> out=new ArrayList<>();
try(PreparedStatement ps=c.prepareStatement(sql)){ ps.setString(1,login);ps.setInt(2,safeLimit);ps.setInt(3,safeOffset);
try(ResultSet rs=ps.executeQuery()){while(rs.next())out.add(new ChannelCard(rs.getString("owner_login"),rs.getString("slug"),rs.getString("display_name"),rs.getString("ava_ar"),rs.getString("owner_bch_name"),rs.getInt("channel_root_block_number"),rs.getString("root_hash")));}}
try(PreparedStatement ps=c.prepareStatement(sql)){
ps.setString(1,login); ps.setBoolean(2,includeDeleted); ps.setInt(3,safeLimit); ps.setInt(4,safeOffset);
try(ResultSet rs=ps.executeQuery()){
while(rs.next()) out.add(new ChannelCard(
rs.getString("owner_login"), rs.getString("slug"), rs.getString("display_name"), rs.getString("ava_ar"),
rs.getString("owner_bch_name"), rs.getInt("channel_root_block_number"), rs.getString("root_hash"),
rs.getBoolean("is_deleted"), rs.getLong("deleted_at_ms"), (Integer) rs.getObject("deleted_block_number")
));
}
}
return out;
}
private static ProfileCard map(ResultSet rs)throws SQLException{return new ProfileCard(rs.getString("login"),rs.getString("first_name"),rs.getString("last_name"),rs.getString("ava_ar"),rs.getString("account_role"),rs.getString("shine_status"));}
public record ProfileCard(String login,String firstName,String lastName,String avatarAr,String accountRole,String shineStatus){}
public record RelationCard(String login,String firstName,String lastName,String avatarAr,String accountRole,String shineStatus,boolean primaryConfirmed,boolean shineConfirmed,String relationType,int primaryConfirmationsCount,int shineConfirmationsCount){}
public record ChannelCard(String ownerLogin,String slug,String displayName,String avatarAr,String ownerBlockchainName,int rootBlockNumber,String rootBlockHashHex){}
public record ChannelCard(String ownerLogin,String slug,String displayName,String avatarAr,String ownerBlockchainName,int rootBlockNumber,String rootBlockHashHex,boolean deleted,long deletedAtMs,Integer deletedBlockNumber){}
}
@@ -0,0 +1,32 @@
BEGIN;
ALTER TABLE channel_names_state
ADD COLUMN IF NOT EXISTS is_deleted BOOLEAN NOT NULL DEFAULT FALSE,
ADD COLUMN IF NOT EXISTS deleted_at_ms BIGINT NOT NULL DEFAULT 0,
ADD COLUMN IF NOT EXISTS deleted_block_number INTEGER;
CREATE OR REPLACE FUNCTION shine_refresh_user_stats(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$
DECLARE v_now BIGINT:=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT);
BEGIN
IF p_login IS NULL OR btrim(p_login)='' THEN RETURN; END IF;
INSERT INTO user_stats_state(login,owned_public_channels_count,following_users_count,following_channels_count,close_friends_count,friends_count,
primary_confirmations_received_count,primary_confirmations_given_count,shine_confirmations_received_count,shine_confirmations_given_count,updated_at_ms)
SELECT p_login,
(SELECT COUNT(*)::INT FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(p_login) AND cn.channel_type_code=1 AND NOT cn.is_deleted),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cs.to_block_number=0),
(SELECT COUNT(*)::INT FROM connections_state cs JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login) AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cn.channel_type_code=1 AND NOT cn.is_deleted),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=10),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=14 AND NOT EXISTS(SELECT 1 FROM connections_state cf WHERE LOWER(cf.login)=LOWER(p_login) AND LOWER(cf.to_login)=LOWER(cs.to_login) AND cf.rel_type=10)),
(SELECT COUNT(DISTINCT LOWER(cs.login))::INT FROM connections_state cs WHERE LOWER(cs.to_login)=LOWER(p_login) AND cs.rel_type=80 AND shine_is_primary(cs.login) AND shine_target_accepts_primary_confirmation(p_login)),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=80 AND shine_is_primary(p_login) AND shine_target_accepts_primary_confirmation(cs.to_login)),
(SELECT COUNT(DISTINCT LOWER(cs.login))::INT FROM connections_state cs WHERE LOWER(cs.to_login)=LOWER(p_login) AND cs.rel_type=70 AND shine_is_primary(cs.login) AND shine_is_shining(cs.login) AND shine_target_accepts_shine_confirmation(p_login)),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=70 AND shine_is_primary(p_login) AND shine_is_shining(p_login) AND shine_target_accepts_shine_confirmation(cs.to_login)),v_now
ON CONFLICT(login) DO UPDATE SET owned_public_channels_count=EXCLUDED.owned_public_channels_count,following_users_count=EXCLUDED.following_users_count,following_channels_count=EXCLUDED.following_channels_count,close_friends_count=EXCLUDED.close_friends_count,friends_count=EXCLUDED.friends_count,primary_confirmations_received_count=EXCLUDED.primary_confirmations_received_count,primary_confirmations_given_count=EXCLUDED.primary_confirmations_given_count,shine_confirmations_received_count=EXCLUDED.shine_confirmations_received_count,shine_confirmations_given_count=EXCLUDED.shine_confirmations_given_count,updated_at_ms=EXCLUDED.updated_at_ms;
END $$;
UPDATE db_schema_version
SET schema_version = 31,
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
WHERE id = 1;
COMMIT;
@@ -665,7 +665,10 @@ CREATE TABLE IF NOT EXISTS channel_names_state (
ava_ar TEXT NOT NULL DEFAULT '',
ava_sha256 TEXT NOT NULL DEFAULT '',
ava_size BIGINT NOT NULL DEFAULT 0,
meta_updated_at_ms BIGINT NOT NULL DEFAULT 0
meta_updated_at_ms BIGINT NOT NULL DEFAULT 0,
is_deleted BOOLEAN NOT NULL DEFAULT FALSE,
deleted_at_ms BIGINT NOT NULL DEFAULT 0,
deleted_block_number INTEGER
);
CREATE UNIQUE INDEX IF NOT EXISTS uq_channel_names_state_owner_type_slug
@@ -1874,11 +1877,11 @@ BEGIN
primary_confirmations_received_count, primary_confirmations_given_count,
shine_confirmations_received_count, shine_confirmations_given_count, updated_at_ms)
SELECT p_login,
(SELECT COUNT(*)::INT FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(p_login) AND cn.channel_type_code=1),
(SELECT COUNT(*)::INT FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(p_login) AND cn.channel_type_code=1 AND NOT cn.is_deleted),
0,
(SELECT COUNT(*)::INT FROM connections_state cs JOIN channel_names_state cn
ON cn.owner_bch_name=cs.to_bch_name AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash
WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cn.channel_type_code=1),
WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cn.channel_type_code=1 AND NOT cn.is_deleted),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=10),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs
WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=14
@@ -2336,9 +2339,9 @@ BEGIN
INSERT INTO user_stats_state(login,owned_public_channels_count,following_users_count,following_channels_count,close_friends_count,friends_count,
primary_confirmations_received_count,primary_confirmations_given_count,shine_confirmations_received_count,shine_confirmations_given_count,updated_at_ms)
SELECT p_login,
(SELECT COUNT(*)::INT FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(p_login) AND cn.channel_type_code=1),
(SELECT COUNT(*)::INT FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(p_login) AND cn.channel_type_code=1 AND NOT cn.is_deleted),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cs.to_block_number=0),
(SELECT COUNT(*)::INT FROM connections_state cs JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login) AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cn.channel_type_code=1),
(SELECT COUNT(*)::INT FROM connections_state cs JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login) AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cn.channel_type_code=1 AND NOT cn.is_deleted),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=10),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=14 AND NOT EXISTS(SELECT 1 FROM connections_state cf WHERE LOWER(cf.login)=LOWER(p_login) AND LOWER(cf.to_login)=LOWER(cs.to_login) AND cf.rel_type=10)),
(SELECT COUNT(DISTINCT LOWER(cs.login))::INT FROM connections_state cs WHERE LOWER(cs.to_login)=LOWER(p_login) AND cs.rel_type=80 AND shine_is_primary(cs.login) AND shine_target_accepts_primary_confirmation(p_login)),
@@ -2655,6 +2658,6 @@ CREATE TABLE IF NOT EXISTS canonical_rebuild_staging (
);
CREATE INDEX IF NOT EXISTS idx_canonical_rebuild_staging_login ON canonical_rebuild_staging(login,logical_block_number);
INSERT INTO db_schema_version(id,schema_version,updated_at_ms) VALUES(1,30,CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT)) ON CONFLICT(id) DO UPDATE SET schema_version=EXCLUDED.schema_version,updated_at_ms=EXCLUDED.updated_at_ms;
INSERT INTO db_schema_version(id,schema_version,updated_at_ms) VALUES(1,31,CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT)) ON CONFLICT(id) DO UPDATE SET schema_version=EXCLUDED.schema_version,updated_at_ms=EXCLUDED.updated_at_ms;
COMMIT;
@@ -6,6 +6,7 @@ import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.auth.Net_AuthChallenge_Handler;
import server.logic.ws_protocol.JSON.handlers.auth.Net_ResolveLoginForAuth_Handler;
import server.logic.ws_protocol.JSON.handlers.auth.Net_CloseActiveSession_Handler;
import server.logic.ws_protocol.JSON.handlers.auth.Net_CloseOtherSessions_Handler;
import server.logic.ws_protocol.JSON.handlers.auth.Net_CreateAuthSession__Handler;
import server.logic.ws_protocol.JSON.handlers.auth.Net_ListSessions_Handler;
import server.logic.ws_protocol.JSON.handlers.auth.Net_ListEspPairingRequests_Handler;
@@ -25,6 +26,7 @@ import server.logic.ws_protocol.JSON.handlers.auth.Net_UpsertEspPairingSettings_
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_AuthChallenge_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_ResolveLoginForAuth_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_CloseActiveSession_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_CloseOtherSessions_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_CreateAuthSession_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_ListSessions_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_ListEspPairingRequests_Request;
@@ -126,6 +128,7 @@ import server.logic.ws_protocol.JSON.messages.Net_CallSignalToSession_Handler;
import server.logic.ws_protocol.JSON.messages.Net_DeleteConversation_Handler;
import server.logic.ws_protocol.JSON.messages.Net_DeleteMessage_Handler;
import server.logic.ws_protocol.JSON.messages.Net_GetDirectMessages_Handler;
import server.logic.ws_protocol.JSON.messages.Net_ReencryptDirectMessage_Handler;
import server.logic.ws_protocol.JSON.messages.Net_SendSignal_Handler;
import server.logic.ws_protocol.JSON.messages.Net_ReceiveIncomingMessage_Handler;
import server.logic.ws_protocol.JSON.messages.Net_SendMessagePair_Handler;
@@ -137,6 +140,7 @@ import server.logic.ws_protocol.JSON.messages.entyties.Net_CallSignalToSession_R
import server.logic.ws_protocol.JSON.messages.entyties.Net_DeleteConversation_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_DeleteMessage_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_GetDirectMessages_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_ReencryptDirectMessage_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_SendSignal_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_ReceiveIncomingMessage_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_SendMessagePair_Request;
@@ -184,6 +188,7 @@ public final class JsonHandlerRegistry {
Map.entry("AuthChallenge", new Net_AuthChallenge_Handler()),
Map.entry("CreateAuthSession", new Net_CreateAuthSession__Handler()),
Map.entry("CloseActiveSession", new Net_CloseActiveSession_Handler()),
Map.entry("CloseOtherSessions", new Net_CloseOtherSessions_Handler()),
Map.entry("ListSessions", new Net_ListSessions_Handler()),
// --- login to existing session in 2 steps ---
@@ -257,6 +262,7 @@ public final class JsonHandlerRegistry {
Map.entry("DeleteMessage", new Net_DeleteMessage_Handler()),
Map.entry("DeleteConversation", new Net_DeleteConversation_Handler()),
Map.entry("GetDirectMessages", new Net_GetDirectMessages_Handler()),
Map.entry("ReencryptDirectMessage", new Net_ReencryptDirectMessage_Handler()),
Map.entry("AckSessionDelivery", new Net_AckSessionDelivery_Handler()),
Map.entry("CallInviteBroadcast", new Net_CallInviteBroadcast_Handler()),
Map.entry("CallSignalToSession", new Net_CallSignalToSession_Handler()),
@@ -286,6 +292,7 @@ public final class JsonHandlerRegistry {
Map.entry("AuthChallenge", Net_AuthChallenge_Request.class),
Map.entry("CreateAuthSession", Net_CreateAuthSession_Request.class),
Map.entry("CloseActiveSession", Net_CloseActiveSession_Request.class),
Map.entry("CloseOtherSessions", Net_CloseOtherSessions_Request.class),
Map.entry("ListSessions", Net_ListSessions_Request.class),
// --- NEW v2 ---
@@ -359,6 +366,7 @@ public final class JsonHandlerRegistry {
Map.entry("DeleteMessage", Net_DeleteMessage_Request.class),
Map.entry("DeleteConversation", Net_DeleteConversation_Request.class),
Map.entry("GetDirectMessages", Net_GetDirectMessages_Request.class),
Map.entry("ReencryptDirectMessage", Net_ReencryptDirectMessage_Request.class),
Map.entry("AckSessionDelivery", Net_AckSessionDelivery_Request.class),
Map.entry("CallInviteBroadcast", Net_CallInviteBroadcast_Request.class),
Map.entry("CallSignalToSession", Net_CallSignalToSession_Request.class),
@@ -1,10 +1,7 @@
package server.logic.ws_protocol.JSON.handlers.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.logic.ws_protocol.JSON.ActiveConnectionsRegistry;
import server.logic.ws_protocol.JSON.ConnectionContext;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
@@ -12,10 +9,7 @@ import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_CloseActiveSession_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_CloseActiveSession_Response;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.JSON.push.WsEventSender;
import server.logic.ws_protocol.JSON.utils.NetIdGenerator;
import server.logic.ws_protocol.WireCodes;
import server.ws.WsConnectionUtils;
import shine.db.dao.ActiveSessionsDAO;
import shine.db.entities.ActiveSessionEntry;
import shine.db.entities.CurrentUserEntry;
@@ -36,7 +30,6 @@ import java.sql.SQLException;
public class Net_CloseActiveSession_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_CloseActiveSession_Handler.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
@Override
public Net_Response handle(Net_Request baseReq, ConnectionContext ctx) throws Exception {
@@ -103,7 +96,7 @@ public class Net_CloseActiveSession_Handler implements JsonMessageHandler {
boolean isCurrentSession = targetSessionId.equals(ctx.getSessionId());
closeActiveSession(targetSessionId, ctx, isCurrentSession);
closeActiveSession(targetSessionId, isCurrentSession);
Net_CloseActiveSession_Response resp = new Net_CloseActiveSession_Response();
resp.setOp(req.getOp());
@@ -113,7 +106,6 @@ public class Net_CloseActiveSession_Handler implements JsonMessageHandler {
}
private void closeActiveSession(String targetSessionId,
ConnectionContext currentCtx,
boolean isCurrentSession) {
try {
@@ -122,32 +114,20 @@ public class Net_CloseActiveSession_Handler implements JsonMessageHandler {
log.error("Ошибка БД при удалении сессии sessionId={}", targetSessionId, e);
}
ConnectionContext ctxToClose =
ActiveConnectionsRegistry.getInstance().getBySessionId(targetSessionId);
if (ctxToClose == null) return;
String eventId = NetIdGenerator.eventId("evt");
ObjectNode payload = MAPPER.createObjectNode();
payload.put("eventId", eventId);
payload.put("sessionId", targetSessionId);
payload.put("reason", "closed_from_another_device");
payload.put("timeMs", System.currentTimeMillis());
WsEventSender.sendEvent(ctxToClose, "SessionRevoked", eventId, payload);
if (isCurrentSession && ctxToClose == currentCtx) {
if (isCurrentSession) {
// Для текущей сессии даём ответу успеть уйти клиенту.
new Thread(() -> {
try { Thread.sleep(50); } catch (InterruptedException ignored) {}
WsConnectionUtils.closeConnection(
ctxToClose,
4000,
SessionRevocationSupport.revokeConnection(
targetSessionId,
"closed_from_another_device",
"Session closed by client via CloseActiveSession"
);
}, "CloseSession-" + targetSessionId).start();
} else {
WsConnectionUtils.closeConnection(
ctxToClose,
4000,
SessionRevocationSupport.revokeConnection(
targetSessionId,
"closed_from_another_device",
"Session closed by client via CloseActiveSession"
);
}
@@ -0,0 +1,44 @@
package server.logic.ws_protocol.JSON.handlers.auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.logic.ws_protocol.JSON.ConnectionContext;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_CloseOtherSessions_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_CloseOtherSessions_Response;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;
import java.util.List;
/** Закрывает все остальные сессии пользователя одним запросом. */
public final class Net_CloseOtherSessions_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_CloseOtherSessions_Handler.class);
@Override
public Net_Response handle(Net_Request baseReq, ConnectionContext ctx) {
Net_CloseOtherSessions_Request req = (Net_CloseOtherSessions_Request) baseReq;
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()
|| ctx.getSessionId() == null || ctx.getSessionId().isBlank()) {
return NetExceptionResponseFactory.error(req, WireCodes.Status.UNVERIFIED,
"NOT_AUTHENTICATED", "Операция доступна только для авторизованной сессии");
}
try {
List<String> ids = SessionRevocationSupport.deleteOtherSessions(ctx.getLogin().trim(), ctx.getSessionId());
SessionRevocationSupport.revokeConnections(ids, "closed_other_sessions",
"Session closed by CloseOtherSessions");
Net_CloseOtherSessions_Response resp = new Net_CloseOtherSessions_Response();
resp.setOp(req.getOp());
resp.setRequestId(req.getRequestId());
resp.setStatus(WireCodes.Status.OK);
resp.setClosedCount(ids.size());
return resp;
} catch (Exception e) {
log.error("CloseOtherSessions failed login={}", ctx.getLogin(), e);
return NetExceptionResponseFactory.error(req, WireCodes.Status.SERVER_DATA_ERROR,
"DB_ERROR", "Не удалось закрыть остальные сессии");
}
}
}
@@ -0,0 +1,49 @@
package server.logic.ws_protocol.JSON.handlers.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import server.logic.ws_protocol.JSON.ActiveConnectionsRegistry;
import server.logic.ws_protocol.JSON.ConnectionContext;
import server.logic.ws_protocol.JSON.push.WsEventSender;
import server.logic.ws_protocol.JSON.utils.NetIdGenerator;
import server.ws.WsConnectionUtils;
import shine.db.dao.ActiveSessionsDAO;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
/** Общая логика отзыва пользовательских сессий. */
public final class SessionRevocationSupport {
private static final ObjectMapper MAPPER = new ObjectMapper();
private SessionRevocationSupport() {}
public static List<String> deleteOtherSessions(Connection c, String login, String keepSessionId) throws SQLException {
return ActiveSessionsDAO.getInstance().deleteOtherSessions(c, login, keepSessionId);
}
public static List<String> deleteOtherSessions(String login, String keepSessionId) throws SQLException {
return ActiveSessionsDAO.getInstance().deleteOtherSessions(login, keepSessionId);
}
public static void revokeConnections(List<String> sessionIds, String reason, String closeReason) {
if (sessionIds == null) return;
for (String sessionId : sessionIds) {
revokeConnection(sessionId, reason, closeReason);
}
}
public static void revokeConnection(String sessionId, String reason, String closeReason) {
ConnectionContext target = ActiveConnectionsRegistry.getInstance().getBySessionId(sessionId);
if (target == null) return;
String eventId = NetIdGenerator.eventId("evt");
ObjectNode payload = MAPPER.createObjectNode();
payload.put("eventId", eventId);
payload.put("sessionId", sessionId);
payload.put("reason", reason == null ? "session_revoked" : reason);
payload.put("timeMs", System.currentTimeMillis());
WsEventSender.sendEvent(target, "SessionRevoked", eventId, payload);
WsConnectionUtils.closeConnection(target, 4000, closeReason == null ? "Session revoked" : closeReason);
}
}
@@ -0,0 +1,7 @@
package server.logic.ws_protocol.JSON.handlers.auth.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
/** Закрыть все активные сессии текущего пользователя, кроме текущей. */
public final class Net_CloseOtherSessions_Request extends Net_Request {
}
@@ -0,0 +1,9 @@
package server.logic.ws_protocol.JSON.handlers.auth.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
public final class Net_CloseOtherSessions_Response extends Net_Response {
private int closedCount;
public int getClosedCount() { return closedCount; }
public void setClosedCount(int closedCount) { this.closedCount = closedCount; }
}
@@ -884,6 +884,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
sub == (MsgSubType.TEXT_POST & 0xffff)
|| sub == (MsgSubType.TEXT_REPOST & 0xffff)
|| sub == (MsgSubType.TEXT_CHANNEL_META & 0xffff)
|| sub == (MsgSubType.TEXT_CHANNEL_DELETE & 0xffff)
|| sub == (MsgSubType.TEXT_ENTRYPOINT & 0xffff)
|| sub == (MsgSubType.TEXT_EXERCISE & 0xffff)
|| sub == (MsgSubType.TEXT_SERVICE & 0xffff)
@@ -80,6 +80,17 @@ public final class BlockchainWriter {
int msgType = block.type & 0xFFFF;
int msgSubType = block.subType & 0xFFFF;
Integer lineCode = be.getLineCode();
boolean channelVisibilityChanged = false;
if (msgType == 1 && lineCode != null && lineCode > 0) {
if (msgSubType == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF)) {
channelVisibilityChanged = channelNameStateDAO.updateDeletedState(
c, blockchainName, lineCode, true, block.timestamp * 1000L, block.blockNumber);
} else if (isPublicChannelPublication(msgType, msgSubType)) {
channelVisibilityChanged = channelNameStateDAO.updateDeletedState(
c, blockchainName, lineCode, false, 0L, null);
}
if (channelVisibilityChanged) refreshChannelVisibilityStats(c, blockchainName, lineCode);
}
if (!replayMode && isPublicChannelPublication(msgType, msgSubType) && lineCode != null && lineCode > 0) {
String channelName = channelReadStateDAO.resolvePublicChannelNameByRoot(c, blockchainName, lineCode);
if (channelName != null && !channelName.isBlank()) {
@@ -110,6 +121,42 @@ public final class BlockchainWriter {
return counterChangedLogins;
}
private static void refreshChannelVisibilityStats(Connection c, String blockchainName, int lineCode) throws SQLException {
String sql = """
SELECT owner_login FROM channel_names_state
WHERE owner_bch_name=? AND channel_root_block_number=?
LIMIT 1
""";
String ownerLogin = null;
try (var ps = c.prepareStatement(sql)) {
ps.setString(1, blockchainName);
ps.setInt(2, lineCode);
try (var rs = ps.executeQuery()) { if (rs.next()) ownerLogin = rs.getString(1); }
}
if (ownerLogin == null || ownerLogin.isBlank()) return;
try (var ps = c.prepareStatement("SELECT shine_refresh_user_stats(?)")) {
ps.setString(1, ownerLogin);
ps.execute();
}
String followersSql = """
SELECT DISTINCT cs.login
FROM connections_state cs
JOIN channel_names_state cn
ON LOWER(cn.owner_login)=LOWER(cs.to_login)
AND cn.channel_root_block_number=cs.to_block_number
AND cn.channel_root_block_hash=cs.to_block_hash
WHERE cs.rel_type=? AND LOWER(cn.owner_login)=LOWER(?) AND cn.channel_root_block_number=?
""";
try (var ps = c.prepareStatement(followersSql)) {
ps.setInt(1, MsgSubType.CONNECTION_FOLLOW);
ps.setString(2, ownerLogin);
ps.setInt(3, lineCode);
try (var rs = ps.executeQuery(); var refresh = c.prepareStatement("SELECT shine_refresh_user_stats(?)")) {
while (rs.next()) { refresh.setString(1, rs.getString(1)); refresh.execute(); }
}
}
}
private static boolean isPublicChannelPublication(int msgType, int msgSubType) {
if (msgType != 1) return false;
return msgSubType == (MsgSubType.TEXT_POST & 0xFFFF)
@@ -138,6 +138,7 @@ public final class ChannelNamesStateBootstrapper {
dao.insertAll(c, entries);
applyMetaUpdates(c, dao, entries, skipped);
applyDeletionStates(c, dao, skipped);
// v18: counters are a projection, so rebuild them from current state after a full channel-name bootstrap.
try (PreparedStatement ps = c.prepareStatement("SELECT shine_refresh_user_stats(login) FROM solana_user_pda_current")) {
ps.execute();
@@ -182,6 +183,39 @@ public final class ChannelNamesStateBootstrapper {
}
}
private static void applyDeletionStates(Connection c, ChannelNameStateDAO dao, List<String> skipped) throws Exception {
String sql = """
SELECT bch_name, block_number, block_bytes, msg_sub_type
FROM blocks
WHERE msg_type = ? AND msg_sub_type IN (?, ?, ?, ?, ?, ?, ?)
ORDER BY bch_name, block_number
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setInt(1, MSG_TYPE_TEXT);
ps.setInt(2, MsgSubType.TEXT_CHANNEL_DELETE);
ps.setInt(3, MsgSubType.TEXT_POST);
ps.setInt(4, MsgSubType.TEXT_REPOST);
ps.setInt(5, MsgSubType.TEXT_ENTRYPOINT);
ps.setInt(6, MsgSubType.TEXT_EXERCISE);
ps.setInt(7, MsgSubType.TEXT_SERVICE);
ps.setInt(8, MsgSubType.TEXT_COURSE);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
String ownerBch = rs.getString("bch_name");
int blockNumber = rs.getInt("block_number");
try {
BchBlockEntry parsed = new BchBlockEntry(rs.getBytes("block_bytes"));
if (!(parsed.body instanceof TextLineBody body) || body.lineCode() <= 0) continue;
boolean deleted = rs.getInt("msg_sub_type") == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF);
dao.updateDeletedState(c, ownerBch, body.lineCode(), deleted, deleted ? parsed.timestamp * 1000L : 0L, deleted ? blockNumber : null);
} catch (Exception e) {
skipped.add(ownerBch + "#" + blockNumber + " (invalid_channel_state_event)");
}
}
}
}
}
private static void applyMetaUpdates(Connection c,
ChannelNameStateDAO dao,
List<ChannelNameStateEntry> entries,
@@ -53,7 +53,7 @@ final class ChannelsReadSupport {
String stateSql = """
SELECT slug, display_name, channel_description, channel_type_code, channel_type_version,
ava_ar, ava_sha256, ava_size, meta_updated_at_ms
ava_ar, ava_sha256, ava_size, meta_updated_at_ms, is_deleted, deleted_at_ms, deleted_block_number
FROM channel_names_state
WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number = ?
LIMIT 1
@@ -72,6 +72,9 @@ final class ChannelsReadSupport {
meta.avaSha256 = String.valueOf(rs.getString("ava_sha256") == null ? "" : rs.getString("ava_sha256"));
meta.avaSize = rs.getLong("ava_size");
meta.metaUpdatedAtMs = rs.getLong("meta_updated_at_ms");
meta.deleted = rs.getBoolean("is_deleted");
meta.deletedAtMs = rs.getLong("deleted_at_ms");
meta.deletedBlockNumber = (Integer) rs.getObject("deleted_block_number");
return meta;
}
}
@@ -534,6 +537,36 @@ final class ChannelsReadSupport {
}
}
}
String deleteSql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,this_line_number
FROM blocks
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type=? AND line_code=?
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)
ORDER BY block_number ASC
""";
try (PreparedStatement ps = c.prepareStatement(deleteSql)) {
ps.setString(1, loginFromChainName(ownerBch));
ps.setInt(2, MSG_TYPE_TEXT);
ps.setInt(3, MsgSubType.TEXT_CHANNEL_DELETE);
ps.setInt(4, lineCode);
ps.setString(5, loginFromChainName(ownerBch));
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
MetaEvent event = new MetaEvent();
event.kind = "deleted";
event.login = rs.getString("login");
event.bchName = rs.getString("bch_name");
event.blockNumber = rs.getInt("block_number");
event.blockHash = rs.getBytes("block_hash");
event.lineStep = (Integer) rs.getObject("this_line_number");
try { event.createdAtMs = new BchBlockEntry(rs.getBytes("block_bytes")).timestamp * 1000L; }
catch (Exception ignored) { event.createdAtMs = 0L; }
out.add(event);
}
}
}
out.sort(Comparator.comparingLong((MetaEvent e) -> e.createdAtMs).thenComparingInt(e -> e.blockNumber));
return out;
}
@@ -681,6 +714,9 @@ final class ChannelsReadSupport {
String avaSha256 = "";
long avaSize = 0L;
long metaUpdatedAtMs = 0L;
boolean deleted = false;
long deletedAtMs = 0L;
Integer deletedBlockNumber;
}
static final class MetaEvent {
@@ -70,6 +70,9 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
channel.setChannelTypeCode(meta.channelTypeCode);
channel.setChannelTypeVersion(meta.channelTypeVersion);
channel.setSubscribersCount(loadSubscribersCount(c, ownerBch, lineCode, meta.channelTypeCode));
channel.setDeleted(meta.deleted);
channel.setDeletedAtMs(meta.deletedAtMs);
channel.setDeletedBlockNumber(meta.deletedBlockNumber);
Net_GetChannelMessages_Response.BlockRef rootRef = new Net_GetChannelMessages_Response.BlockRef();
rootRef.setBlockNumber(lineCode);
rootRef.setBlockHash(req.getChannel().getChannelRootBlockHash());
@@ -75,6 +75,9 @@ public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
channelRef.setChannelTypeCode(meta.channelTypeCode);
channelRef.setChannelTypeVersion(meta.channelTypeVersion);
channelRef.setPersonal(meta.channelTypeCode == 100);
channelRef.setDeleted(meta.deleted);
channelRef.setDeletedAtMs(meta.deletedAtMs);
channelRef.setDeletedBlockNumber(meta.deletedBlockNumber);
Net_ListSubscriptionsFeed_Response.BlockRef rootRef = new Net_ListSubscriptionsFeed_Response.BlockRef();
rootRef.setBlockNumber(key.rootNumber);
@@ -33,6 +33,9 @@ public class Net_GetChannelMessages_Response extends Net_Response {
private Integer channelTypeCode;
private Integer channelTypeVersion;
private Integer subscribersCount;
private boolean deleted;
private long deletedAtMs;
private Integer deletedBlockNumber;
private BlockRef channelRoot;
public String getOwnerLogin() { return ownerLogin; }
@@ -71,6 +74,13 @@ public class Net_GetChannelMessages_Response extends Net_Response {
public Integer getSubscribersCount() { return subscribersCount; }
public void setSubscribersCount(Integer subscribersCount) { this.subscribersCount = subscribersCount; }
public boolean isDeleted() { return deleted; }
public void setDeleted(boolean deleted) { this.deleted = deleted; }
public long getDeletedAtMs() { return deletedAtMs; }
public void setDeletedAtMs(long deletedAtMs) { this.deletedAtMs = deletedAtMs; }
public Integer getDeletedBlockNumber() { return deletedBlockNumber; }
public void setDeletedBlockNumber(Integer deletedBlockNumber) { this.deletedBlockNumber = deletedBlockNumber; }
public BlockRef getChannelRoot() { return channelRoot; }
public void setChannelRoot(BlockRef channelRoot) { this.channelRoot = channelRoot; }
}
@@ -63,6 +63,9 @@ public class Net_ListSubscriptionsFeed_Response extends Net_Response {
private Integer channelTypeCode;
private Integer channelTypeVersion;
private boolean personal;
private boolean deleted;
private long deletedAtMs;
private Integer deletedBlockNumber;
private BlockRef channelRoot;
public String getOwnerLogin() { return ownerLogin; }
@@ -100,6 +103,12 @@ public class Net_ListSubscriptionsFeed_Response extends Net_Response {
public boolean isPersonal() { return personal; }
public void setPersonal(boolean personal) { this.personal = personal; }
public boolean isDeleted() { return deleted; }
public void setDeleted(boolean deleted) { this.deleted = deleted; }
public long getDeletedAtMs() { return deletedAtMs; }
public void setDeletedAtMs(long deletedAtMs) { this.deletedAtMs = deletedAtMs; }
public Integer getDeletedBlockNumber() { return deletedBlockNumber; }
public void setDeletedBlockNumber(Integer deletedBlockNumber) { this.deletedBlockNumber = deletedBlockNumber; }
public BlockRef getChannelRoot() { return channelRoot; }
public void setChannelRoot(BlockRef channelRoot) { this.channelRoot = channelRoot; }
@@ -6,14 +6,13 @@ import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationContinue_Request;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import shine.db.dao.CurrentUsersDAO;
import shine.db.dao.KeyRotationSessionsDAO;
import shine.db.dao.SignedMessagesDAO;
import shine.db.entities.KeyRotationSessionEntry;
import shine.db.entities.KeyRotationStatus;
/**
* Сейчас wallet/DM migration — явные заглушки. Continue фиксирует NOT_IMPLEMENTED
* и переводит state machine дальше, не делая вид, что данные были реально мигрированы.
*/
/** Координирует реально выполненные wallet/DM этапы после rebuild. */
public final class Net_KeyRotationContinue_Handler implements JsonMessageHandler {
private final KeyRotationSessionsDAO rotations = KeyRotationSessionsDAO.getInstance();
@@ -24,23 +23,36 @@ public final class Net_KeyRotationContinue_Handler implements JsonMessageHandler
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
}
try {
KeyRotationSessionEntry current = rotations.getActiveByLogin(ctx.getLogin().trim());
String login = ctx.getLogin().trim();
KeyRotationSessionEntry current = rotations.getActiveByLogin(login);
if (current == null) return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), null);
if (current.getStatus() == KeyRotationStatus.WALLET_MIGRATION) {
rotations.setMigrationSubStatus(current.getId(), "wallet_migration_status", "NOT_IMPLEMENTED");
String walletStatus = String.valueOf(req.getWalletMigrationStatus() == null ? "" : req.getWalletMigrationStatus()).trim().toUpperCase();
if (!"COMPLETE".equals(walletStatus) && !"SKIPPED".equals(walletStatus)) {
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_WALLET_STATUS",
"walletMigrationStatus должен быть COMPLETE или SKIPPED");
}
rotations.setMigrationSubStatus(current.getId(), "wallet_migration_status", walletStatus);
current = rotations.transition(current.getId(), KeyRotationStatus.WALLET_MIGRATION, KeyRotationStatus.MESSAGE_MIGRATION);
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current);
}
if (current.getStatus() == KeyRotationStatus.MESSAGE_MIGRATION) {
rotations.setMigrationSubStatus(current.getId(), "message_migration_status", "NOT_IMPLEMENTED");
long remaining = SignedMessagesDAO.getInstance()
.countMessagesNeedingReencryption(login, current.getUpdatedAtMs());
if (remaining > 0) {
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_DM_PENDING",
"Остались неперешифрованные личные сообщения: " + remaining);
}
rotations.setMigrationSubStatus(current.getId(), "message_migration_status", "COMPLETE");
current = rotations.transition(current.getId(), KeyRotationStatus.MESSAGE_MIGRATION, KeyRotationStatus.FINALIZING);
// FINALIZING пока не содержит отдельной пользовательской работы: сразу завершаем.
current = rotations.transition(current.getId(), KeyRotationStatus.FINALIZING, KeyRotationStatus.COMPLETE);
refreshCurrentUser(ctx, login);
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current);
}
if (current.getStatus() == KeyRotationStatus.FINALIZING) {
current = rotations.transition(current.getId(), KeyRotationStatus.FINALIZING, KeyRotationStatus.COMPLETE);
refreshCurrentUser(ctx, login);
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current);
}
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_CONTINUE_NOT_ALLOWED",
@@ -50,4 +62,10 @@ public final class Net_KeyRotationContinue_Handler implements JsonMessageHandler
"Не удалось продолжить смену ключей");
}
}
private static void refreshCurrentUser(ConnectionContext ctx, String login) throws Exception {
var fresh = CurrentUsersDAO.getInstance().getByLogin(login);
if (fresh != null) ctx.setCurrentUser(fresh);
}
}
@@ -6,6 +6,7 @@ import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationRotatePda_Request;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import shine.db.dao.CurrentUsersDAO;
import shine.db.dao.KeyRotationSessionsDAO;
import shine.db.entities.KeyRotationSessionEntry;
import shine.db.entities.KeyRotationStatus;
@@ -39,6 +40,8 @@ public final class Net_KeyRotationRotatePda_Handler implements JsonMessageHandle
}
if (current.getStatus() == KeyRotationStatus.PDA_ROTATED) {
var fresh = CurrentUsersDAO.getInstance().getByLogin(login);
if (fresh != null) ctx.setCurrentUser(fresh);
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current);
}
@@ -61,7 +64,12 @@ public final class Net_KeyRotationRotatePda_Handler implements JsonMessageHandle
// Solana sync мог увидеть новое PDA ещё до этого API-вызова.
KeyRotationSessionEntry confirmed = rotations.tryMarkPdaRotatedFromCurrentState(current.getId());
rotations.clearError(current.getId());
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), confirmed != null ? confirmed : rotations.getById(current.getId()));
KeyRotationSessionEntry result = confirmed != null ? confirmed : rotations.getById(current.getId());
if (result != null && result.getStatus() == KeyRotationStatus.PDA_ROTATED) {
var fresh = CurrentUsersDAO.getInstance().getByLogin(login);
if (fresh != null) ctx.setCurrentUser(fresh);
}
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), result);
} catch (Exception e) {
return NetExceptionResponseFactory.error(req, 500, "KEY_ROTATION_ROTATE_PDA_FAILED",
"Не удалось зафиксировать Solana-ротацию PDA");
@@ -5,6 +5,7 @@ import server.logic.ws_protocol.JSON.entyties.Net_Request;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler_utils.BlockchainLocks;
import server.logic.ws_protocol.JSON.handlers.auth.SessionRevocationSupport;
import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationStart_Request;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import shine.db.DbController;
@@ -19,6 +20,7 @@ import shine.db.entities.KeyRotationStatus;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
/**
@@ -38,6 +40,11 @@ public final class Net_KeyRotationStart_Handler implements JsonMessageHandler {
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
}
String login = ctx.getLogin().trim();
String currentSessionId = ctx.getSessionId() == null ? "" : ctx.getSessionId().trim();
if (currentSessionId.isEmpty()) {
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_SESSION_STALE",
"В текущем соединении отсутствует sessionId; войдите заново");
}
String ctxBlockchainName = ctx.getCurrentUser() != null ? ctx.getCurrentUser().getBlockchainName() : null;
if (ctxBlockchainName == null || ctxBlockchainName.isBlank()) {
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_SESSION_STALE",
@@ -152,7 +159,14 @@ public final class Net_KeyRotationStart_Handler implements JsonMessageHandler {
entry.setProgressTotal(1); // segmented fork publishes only TECH_FORK
KeyRotationSessionEntry created = rotations.createCopyingSession(c, entry);
List<String> revokedSessionIds = SessionRevocationSupport
.deleteOtherSessions(c, login, currentSessionId);
c.commit();
SessionRevocationSupport.revokeConnections(
revokedSessionIds,
"key_rotation_started",
"Session closed because key rotation started"
);
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), created);
} catch (ArithmeticException e) {
c.rollback();
@@ -6,8 +6,10 @@ import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationStatus_Request;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import shine.db.dao.CurrentUsersDAO;
import shine.db.dao.KeyRotationSessionsDAO;
import shine.db.entities.KeyRotationSessionEntry;
import shine.db.entities.KeyRotationStatus;
public final class Net_KeyRotationStatus_Handler implements JsonMessageHandler {
private final KeyRotationSessionsDAO rotations = KeyRotationSessionsDAO.getInstance();
@@ -19,11 +21,30 @@ public final class Net_KeyRotationStatus_Handler implements JsonMessageHandler {
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
}
try {
KeyRotationSessionEntry current = rotations.getActiveByLogin(ctx.getLogin().trim());
String login = ctx.getLogin().trim();
KeyRotationSessionEntry current = rotations.getActiveByLogin(login);
if (current != null && isPdaAlreadyRotated(current.getStatus())) {
refreshCurrentUser(ctx, login);
}
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current);
} catch (Exception e) {
return NetExceptionResponseFactory.error(req, 500, "KEY_ROTATION_STATUS_FAILED",
"Не удалось прочитать состояние смены ключей");
}
}
private static boolean isPdaAlreadyRotated(KeyRotationStatus status) {
return status == KeyRotationStatus.PDA_ROTATED
|| status == KeyRotationStatus.REBUILDING_SERVER
|| status == KeyRotationStatus.WALLET_MIGRATION
|| status == KeyRotationStatus.MESSAGE_MIGRATION
|| status == KeyRotationStatus.FINALIZING
|| status == KeyRotationStatus.COMPLETE;
}
private static void refreshCurrentUser(ConnectionContext ctx, String login) throws Exception {
var fresh = CurrentUsersDAO.getInstance().getByLogin(login);
if (fresh != null) ctx.setCurrentUser(fresh);
}
}
@@ -2,6 +2,10 @@ package server.logic.ws_protocol.JSON.handlers.keyRotation.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
/** Продолжить один из интерактивных/заглушечных этапов после rebuild. */
/** Продолжить post-PDA этап после фактической клиентской работы. */
public final class Net_KeyRotationContinue_Request extends Net_Request {
private String walletMigrationStatus;
public String getWalletMigrationStatus() { return walletMigrationStatus; }
public void setWalletMigrationStatus(String walletMigrationStatus) { this.walletMigrationStatus = walletMigrationStatus; }
}
@@ -1,3 +1,3 @@
package server.logic.ws_protocol.JSON.handlers.profile;
import server.logic.ws_protocol.JSON.*;import server.logic.ws_protocol.JSON.entyties.*;import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;import server.logic.ws_protocol.JSON.handlers.profile.entyties.*;import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;import server.logic.ws_protocol.WireCodes;import shine.db.dao.UserProfileStateDAO;import java.sql.*;import java.util.*;
public class Net_ListUserProfileChannels_Handler implements JsonMessageHandler {public Net_Response handle(Net_Request base,ConnectionContext ctx)throws Exception{var req=(Net_ListUserProfileChannels_Request)base;if(req.getLogin()==null||req.getLogin().isBlank())return NetExceptionResponseFactory.error(req,400,"BAD_FIELDS","login required");try(Connection c=shine.db.DbController.getInstance().getConnection()){var rows=UserProfileStateDAO.getInstance().listPublicChannels(c,req.getLogin(),req.getMode(),req.getLimit()==null?100:req.getLimit(),req.getOffset()==null?0:req.getOffset());var resp=new Net_ListUserProfileChannels_Response();resp.setOp(req.getOp());resp.setRequestId(req.getRequestId());resp.setStatus(WireCodes.Status.OK);resp.setLogin(req.getLogin());resp.setMode(req.getMode());List<Net_ListUserProfileChannels_Response.ChannelItem> items=new ArrayList<>();for(var r:rows){var i=new Net_ListUserProfileChannels_Response.ChannelItem();i.setOwnerLogin(r.ownerLogin());i.setSlug(r.slug());i.setDisplayName(r.displayName());i.setAvatarAr(r.avatarAr());i.setOwnerBlockchainName(r.ownerBlockchainName());i.setRootBlockNumber(r.rootBlockNumber());i.setRootBlockHashHex(r.rootBlockHashHex());items.add(i);}resp.setChannels(items);return resp;}}}
public class Net_ListUserProfileChannels_Handler implements JsonMessageHandler {public Net_Response handle(Net_Request base,ConnectionContext ctx)throws Exception{var req=(Net_ListUserProfileChannels_Request)base;if(req.getLogin()==null||req.getLogin().isBlank())return NetExceptionResponseFactory.error(req,400,"BAD_FIELDS","login required");try(Connection c=shine.db.DbController.getInstance().getConnection()){var rows=UserProfileStateDAO.getInstance().listPublicChannels(c,req.getLogin(),req.getMode(),Boolean.TRUE.equals(req.getIncludeDeleted()),req.getLimit()==null?100:req.getLimit(),req.getOffset()==null?0:req.getOffset());var resp=new Net_ListUserProfileChannels_Response();resp.setOp(req.getOp());resp.setRequestId(req.getRequestId());resp.setStatus(WireCodes.Status.OK);resp.setLogin(req.getLogin());resp.setMode(req.getMode());List<Net_ListUserProfileChannels_Response.ChannelItem> items=new ArrayList<>();for(var r:rows){var i=new Net_ListUserProfileChannels_Response.ChannelItem();i.setOwnerLogin(r.ownerLogin());i.setSlug(r.slug());i.setDisplayName(r.displayName());i.setAvatarAr(r.avatarAr());i.setOwnerBlockchainName(r.ownerBlockchainName());i.setRootBlockNumber(r.rootBlockNumber());i.setRootBlockHashHex(r.rootBlockHashHex());i.setDeleted(r.deleted());i.setDeletedAtMs(r.deletedAtMs());i.setDeletedBlockNumber(r.deletedBlockNumber());items.add(i);}resp.setChannels(items);return resp;}}}
@@ -1,3 +1,3 @@
package server.logic.ws_protocol.JSON.handlers.profile.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
public class Net_ListUserProfileChannels_Request extends Net_Request {private String login,mode;private Integer limit,offset;public String getLogin(){return login;}public void setLogin(String v){login=v;}public String getMode(){return mode;}public void setMode(String v){mode=v;}public Integer getLimit(){return limit;}public void setLimit(Integer v){limit=v;}public Integer getOffset(){return offset;}public void setOffset(Integer v){offset=v;}}
public class Net_ListUserProfileChannels_Request extends Net_Request {private String login,mode;private Integer limit,offset;private Boolean includeDeleted;public String getLogin(){return login;}public void setLogin(String v){login=v;}public String getMode(){return mode;}public void setMode(String v){mode=v;}public Integer getLimit(){return limit;}public void setLimit(Integer v){limit=v;}public Integer getOffset(){return offset;}public void setOffset(Integer v){offset=v;}public Boolean getIncludeDeleted(){return includeDeleted;}public void setIncludeDeleted(Boolean v){includeDeleted=v;}}
@@ -1,3 +1,3 @@
package server.logic.ws_protocol.JSON.handlers.profile.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Response;import java.util.*;
public class Net_ListUserProfileChannels_Response extends Net_Response {private String login,mode;private List<ChannelItem> channels=new ArrayList<>();public String getLogin(){return login;}public void setLogin(String v){login=v;}public String getMode(){return mode;}public void setMode(String v){mode=v;}public List<ChannelItem> getChannels(){return channels;}public void setChannels(List<ChannelItem> v){channels=v;}public static class ChannelItem{private String ownerLogin,slug,displayName,avatarAr,ownerBlockchainName,rootBlockHashHex;private int rootBlockNumber;public String getOwnerLogin(){return ownerLogin;}public void setOwnerLogin(String v){ownerLogin=v;}public String getSlug(){return slug;}public void setSlug(String v){slug=v;}public String getDisplayName(){return displayName;}public void setDisplayName(String v){displayName=v;}public String getAvatarAr(){return avatarAr;}public void setAvatarAr(String v){avatarAr=v;}public String getOwnerBlockchainName(){return ownerBlockchainName;}public void setOwnerBlockchainName(String v){ownerBlockchainName=v;}public int getRootBlockNumber(){return rootBlockNumber;}public void setRootBlockNumber(int v){rootBlockNumber=v;}public String getRootBlockHashHex(){return rootBlockHashHex;}public void setRootBlockHashHex(String v){rootBlockHashHex=v;}}}
public class Net_ListUserProfileChannels_Response extends Net_Response {private String login,mode;private List<ChannelItem> channels=new ArrayList<>();public String getLogin(){return login;}public void setLogin(String v){login=v;}public String getMode(){return mode;}public void setMode(String v){mode=v;}public List<ChannelItem> getChannels(){return channels;}public void setChannels(List<ChannelItem> v){channels=v;}public static class ChannelItem{private String ownerLogin,slug,displayName,avatarAr,ownerBlockchainName,rootBlockHashHex;private int rootBlockNumber;private boolean deleted;private long deletedAtMs;private Integer deletedBlockNumber;public String getOwnerLogin(){return ownerLogin;}public void setOwnerLogin(String v){ownerLogin=v;}public String getSlug(){return slug;}public void setSlug(String v){slug=v;}public String getDisplayName(){return displayName;}public void setDisplayName(String v){displayName=v;}public String getAvatarAr(){return avatarAr;}public void setAvatarAr(String v){avatarAr=v;}public String getOwnerBlockchainName(){return ownerBlockchainName;}public void setOwnerBlockchainName(String v){ownerBlockchainName=v;}public int getRootBlockNumber(){return rootBlockNumber;}public void setRootBlockNumber(int v){rootBlockNumber=v;}public String getRootBlockHashHex(){return rootBlockHashHex;}public void setRootBlockHashHex(String v){rootBlockHashHex=v;}public boolean isDeleted(){return deleted;}public void setDeleted(boolean v){deleted=v;}public long getDeletedAtMs(){return deletedAtMs;}public void setDeletedAtMs(long v){deletedAtMs=v;}public Integer getDeletedBlockNumber(){return deletedBlockNumber;}public void setDeletedBlockNumber(Integer v){deletedBlockNumber=v;}}}
@@ -49,6 +49,11 @@ public class Net_GetDirectMessages_Handler implements JsonMessageHandler {
String peerLogin = req.getPeerLogin().trim();
long beforeTimeMs = req.getBeforeTimeMs() == null ? 0L : req.getBeforeTimeMs();
String beforeMessageKey = req.getBeforeMessageKey() == null ? "" : req.getBeforeMessageKey().trim();
long reencryptedBeforeMs = req.getReencryptedBeforeMs() == null ? 0L : req.getReencryptedBeforeMs();
if (reencryptedBeforeMs < 0) {
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST,
"BAD_REENCRYPTED_BEFORE", "reencryptedBeforeMs должен быть >= 0");
}
try {
List<SignedMessageEntry> page = SignedMessagesDAO.getInstance().listConversationPage(
@@ -56,6 +61,7 @@ public class Net_GetDirectMessages_Handler implements JsonMessageHandler {
peerLogin,
beforeTimeMs,
beforeMessageKey,
reencryptedBeforeMs,
limit + 1
);
@@ -35,6 +35,15 @@ public class Net_ReceiveIncomingMessage_Handler implements JsonMessageHandler {
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "BAD_MESSAGE_TYPE", "API принимает только входящие типы 1/3");
}
// Перешифрованная локальная копия type=1 подписана уже получателем, а не исходным
// отправителем. Она никогда не должна приходить через federation API; для неё есть
// ReencryptDirectMessage, который дополнительно проверяет активную key rotation.
if (incoming.messageType == SignedMessageBlock.TYPE_INCOMING_TEXT && incoming.reencryptedAtMs > 0) {
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST,
"REENCRYPTED_DM_LOCAL_ONLY",
"Перешифрованный входящий DM принимается только через ReencryptDirectMessage");
}
try {
SignedMessagesCore.verifyUsersAndSignature(incoming);
} catch (IllegalArgumentException ex) {
@@ -0,0 +1,70 @@
package server.logic.ws_protocol.JSON.messages;
import server.logic.ws_protocol.JSON.ConnectionContext;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.messages.entyties.Net_ReencryptDirectMessage_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_ReencryptDirectMessage_Response;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;
import shine.db.dao.KeyRotationSessionsDAO;
import shine.db.dao.SignedMessagesDAO;
import shine.db.entities.KeyRotationSessionEntry;
import shine.db.entities.KeyRotationStatus;
import shine.db.entities.SignedMessageEntry;
/** Сохраняет только локальную перешифрованную type=1/2 копию, без federation/delivery. */
public final class Net_ReencryptDirectMessage_Handler implements JsonMessageHandler {
@Override
public Net_Response handle(Net_Request baseReq, ConnectionContext ctx) throws Exception {
Net_ReencryptDirectMessage_Request req = (Net_ReencryptDirectMessage_Request) baseReq;
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
return NetExceptionResponseFactory.error(req, WireCodes.Status.UNVERIFIED, "NOT_AUTHENTICATED", "Требуется авторизация");
}
if (req.getBlobB64() == null || req.getBlobB64().isBlank()) {
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "BAD_FIELDS", "blobB64 обязателен");
}
String login = ctx.getLogin().trim();
KeyRotationSessionEntry rotation = KeyRotationSessionsDAO.getInstance().getActiveByLogin(login);
if (rotation == null || rotation.getStatus() != KeyRotationStatus.MESSAGE_MIGRATION) {
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_MESSAGE_MIGRATION_REQUIRED",
"Перешифровка DM разрешена только на этапе MESSAGE_MIGRATION");
}
final SignedMessageBlock block;
try {
block = SignedMessagesCore.parseFromB64(req.getBlobB64());
if (!block.isContentType()) throw new IllegalArgumentException("BAD_MESSAGE_TYPE");
if (block.reencryptedAtMs != rotation.getUpdatedAtMs()) throw new IllegalArgumentException("BAD_REENCRYPTED_TIME");
boolean owned = block.messageType == SignedMessageBlock.TYPE_INCOMING_TEXT
? login.equalsIgnoreCase(block.toLogin)
: login.equalsIgnoreCase(block.fromLogin);
if (!owned) throw new IllegalArgumentException("MESSAGE_OF_ANOTHER_USER");
SignedMessagesCore.verifyUsersAndSignature(block);
} catch (IllegalArgumentException e) {
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, e.getMessage(),
"Некорректная локальная перешифрованная копия");
}
SignedMessageEntry entry = SignedMessagesCore.toEntry(block, "ReencryptDirectMessage", ctx.getSessionId());
SignedMessagesDAO.ApplyStatus status = SignedMessagesDAO.getInstance().upsertReencryptedLocalCopy(entry);
if (!status.applied()) {
SignedMessageEntry stored = SignedMessagesDAO.getInstance().getByMessageKey(entry.getMessageKey());
if (stored == null) {
return NetExceptionResponseFactory.error(req, 404, "MESSAGE_NOT_FOUND", "Исходная локальная копия не найдена");
}
if (stored.getReencryptedAtMs() < entry.getReencryptedAtMs()) {
return NetExceptionResponseFactory.error(req, 409, "STALE_MESSAGE_REVISION", "Локальная копия не была обновлена");
}
}
Net_ReencryptDirectMessage_Response resp = new Net_ReencryptDirectMessage_Response();
resp.setOp(req.getOp());
resp.setRequestId(req.getRequestId());
resp.setStatus(WireCodes.Status.OK);
resp.setMessageKey(entry.getMessageKey());
resp.setReencryptedAtMs(entry.getReencryptedAtMs());
return resp;
}
}
@@ -33,6 +33,9 @@ public class Net_SendMessagePair_Handler implements JsonMessageHandler {
incoming = SignedMessagesCore.parseFromB64(req.getIncomingBlobB64());
outgoing = SignedMessagesCore.parseFromB64(req.getOutgoingBlobB64());
SignedMessagesCore.validatePair(incoming, outgoing);
if (incoming.reencryptedAtMs != 0 || outgoing.reencryptedAtMs != 0) {
throw new IllegalArgumentException("BAD_REENCRYPTED_TIME");
}
} catch (IllegalArgumentException ex) {
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, ex.getMessage(), "Некорректный формат пары сообщений");
}
@@ -179,7 +179,8 @@ final class SignedMessageBlock {
}
boolean isSignedByRecipient() {
return messageType == TYPE_MESSAGE_DELETED_BY_RECIPIENT
return (messageType == TYPE_INCOMING_TEXT && reencryptedAtMs > 0)
|| messageType == TYPE_MESSAGE_DELETED_BY_RECIPIENT
|| messageType == TYPE_CONVERSATION_DELETED_BY_RECIPIENT;
}
@@ -7,6 +7,7 @@ public class Net_GetDirectMessages_Request extends Net_Request {
private Integer limit;
private Long beforeTimeMs;
private String beforeMessageKey;
private Long reencryptedBeforeMs;
public String getPeerLogin() { return peerLogin; }
public void setPeerLogin(String peerLogin) { this.peerLogin = peerLogin; }
@@ -16,4 +17,6 @@ public class Net_GetDirectMessages_Request extends Net_Request {
public void setBeforeTimeMs(Long beforeTimeMs) { this.beforeTimeMs = beforeTimeMs; }
public String getBeforeMessageKey() { return beforeMessageKey; }
public void setBeforeMessageKey(String beforeMessageKey) { this.beforeMessageKey = beforeMessageKey; }
public Long getReencryptedBeforeMs() { return reencryptedBeforeMs; }
public void setReencryptedBeforeMs(Long reencryptedBeforeMs) { this.reencryptedBeforeMs = reencryptedBeforeMs; }
}
@@ -0,0 +1,9 @@
package server.logic.ws_protocol.JSON.messages.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
public final class Net_ReencryptDirectMessage_Request extends Net_Request {
private String blobB64;
public String getBlobB64() { return blobB64; }
public void setBlobB64(String blobB64) { this.blobB64 = blobB64; }
}
@@ -0,0 +1,12 @@
package server.logic.ws_protocol.JSON.messages.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
public final class Net_ReencryptDirectMessage_Response extends Net_Response {
private String messageKey;
private long reencryptedAtMs;
public String getMessageKey() { return messageKey; }
public void setMessageKey(String messageKey) { this.messageKey = messageKey; }
public long getReencryptedAtMs() { return reencryptedAtMs; }
public void setReencryptedAtMs(long reencryptedAtMs) { this.reencryptedAtMs = reencryptedAtMs; }
}