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

Добавлена доработка сценариев ротации ключей, закрытия сессий и повторного шифрования 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_COURSE & 0xFFFF)
|| st == (MsgSubType.TEXT_ENTRYPOINT & 0xFFFF) || st == (MsgSubType.TEXT_ENTRYPOINT & 0xFFFF)
|| st == (MsgSubType.TEXT_REPOST & 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); yield new TextLineBody(subType, version, bodyBytes);
} }
@@ -81,6 +81,9 @@ public final class MsgSubType {
*/ */
public static final short TEXT_CHANNEL_META = 90; 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). */ /** ENTRYPOINT — входная страница канала (line-based). */
public static final short TEXT_ENTRYPOINT = 100; public static final short TEXT_ENTRYPOINT = 100;
/** EXERCISE — упражнение/комплекс (line-based). */ /** EXERCISE — упражнение/комплекс (line-based). */
@@ -73,7 +73,7 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
this.toBlockHash32 = null; 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); this.message = readText(bb, allowEmpty);
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected TextLineBody tail"); 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 (st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF)) {
if (message == null) throw new IllegalArgumentException("CHANNEL_META message is null"); 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()) { } else if (message == null || message.isBlank()) {
throw new IllegalArgumentException("Text message is blank"); throw new IllegalArgumentException("Text message is blank");
} }
@@ -167,6 +169,7 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
int st = subType & 0xFFFF; int st = subType & 0xFFFF;
return st == (MsgSubType.TEXT_POST & 0xFFFF) || st == (MsgSubType.TEXT_EDIT_POST & 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_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_ENTRYPOINT & 0xFFFF) || st == (MsgSubType.TEXT_EXERCISE & 0xFFFF)
|| st == (MsgSubType.TEXT_SERVICE & 0xFFFF) || st == (MsgSubType.TEXT_COURSE & 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 String DB_FORMAT_MARKER = "SHiNE_DB_V2";
public static final int DB_FORMAT_VERSION = 2; public static final int DB_FORMAT_VERSION = 2;
public static final int SCHEMA_VERSION_1 = 1; 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_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
private DatabaseInitializer() {} private DatabaseInitializer() {}
@@ -33,6 +34,7 @@ public final class DatabaseInitializer {
public static final short TEXT_RATING = 30; public static final short TEXT_RATING = 30;
public static final short TEXT_REPOST = 50; public static final short TEXT_REPOST = 50;
public static final short TEXT_CHANNEL_META = 90; 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_ENTRYPOINT = 100;
public static final short TEXT_EXERCISE = 110; public static final short TEXT_EXERCISE = 110;
public static final short TEXT_SERVICE = 120; public static final short TEXT_SERVICE = 120;
@@ -113,9 +115,13 @@ public final class DatabaseInitializer {
validateDatabaseFormatV2(conn); validateDatabaseFormatV2(conn);
int currentVersion = readCurrentSchemaVersion(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( 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 — скрытый технический снимок профиля канала. */ /** CHANNEL_META — скрытый технический снимок профиля канала. */
public static final short TEXT_CHANNEL_META = 90; public static final short TEXT_CHANNEL_META = 90;
public static final short TEXT_CHANNEL_DELETE = 92;
/** ENTRYPOINT — входная страница канала (line-based). */ /** ENTRYPOINT — входная страница канала (line-based). */
public static final short TEXT_ENTRYPOINT = 100; 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 -------------------- // -------------------- MAPPER --------------------
private ActiveSessionEntry mapRow(ResultSet rs) throws SQLException { private ActiveSessionEntry mapRow(ResultSet rs) throws SQLException {
@@ -120,6 +120,27 @@ public final class ChannelNameStateDAO {
insert(c, entry); 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 { 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"; 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)) { 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) WHERE LOWER(cns.owner_login)=LOWER(crs.owner_login)
AND cns.slug=crs.channel_name AND cns.slug=crs.channel_name
AND cns.channel_type_code=1 AND cns.channel_type_code=1
AND NOT cns.is_deleted
) )
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -377,6 +377,7 @@ public final class SignedMessagesDAO {
String peerLogin, String peerLogin,
long beforeTimeMs, long beforeTimeMs,
String beforeMessageKey, String beforeMessageKey,
long reencryptedBeforeMs,
int limit int limit
) throws Exception { ) throws Exception {
try (Connection c = db.getConnection()) { try (Connection c = db.getConnection()) {
@@ -398,6 +399,7 @@ public final class SignedMessagesDAO {
OR time_ms < ? OR time_ms < ?
OR (time_ms = ? AND (? = '' OR message_key < ?)) 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 ORDER BY time_ms DESC, message_key DESC
LIMIT ? LIMIT ?
""".formatted(messagesTable()); """.formatted(messagesTable());
@@ -413,7 +415,10 @@ public final class SignedMessagesDAO {
ps.setLong(8, beforeTimeMs); ps.setLong(8, beforeTimeMs);
ps.setString(9, beforeMessageKey == null ? "" : beforeMessageKey); ps.setString(9, beforeMessageKey == null ? "" : beforeMessageKey);
ps.setString(10, 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()) { try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) out.add(mapRow(rs)); 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( public SyncBatch listSyncBatch(
String ownerLogin, String ownerLogin,
long afterStoredAtMs, long afterStoredAtMs,
@@ -111,31 +111,48 @@ public final class UserProfileStateDAO {
return out; 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); int safeLimit=Math.max(1,Math.min(limit<=0?100:limit,500)), safeOffset=Math.max(0,offset);
String sql; String sql;
if ("owned".equals(mode)) { if ("owned".equals(mode)) {
sql=""" 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 SELECT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.owner_bch_name,
FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(?) AND cn.channel_type_code=1 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 ? ORDER BY cn.display_name, cn.slug LIMIT ? OFFSET ?
"""; """;
} else if ("following".equals(mode)) { } else if ("following".equals(mode)) {
sql=""" 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 SELECT DISTINCT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.owner_bch_name,
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 cn.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash,
WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=30 AND cn.channel_type_code=1 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 ? ORDER BY cn.display_name, cn.slug LIMIT ? OFFSET ?
"""; """;
} else throw new IllegalArgumentException("Unsupported channel mode: "+mode); } else throw new IllegalArgumentException("Unsupported channel mode: "+mode);
List<ChannelCard> out=new ArrayList<>(); List<ChannelCard> out=new ArrayList<>();
try(PreparedStatement ps=c.prepareStatement(sql)){ ps.setString(1,login);ps.setInt(2,safeLimit);ps.setInt(3,safeOffset); try(PreparedStatement ps=c.prepareStatement(sql)){
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")));}} 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; 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"));} 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 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 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_ar TEXT NOT NULL DEFAULT '',
ava_sha256 TEXT NOT NULL DEFAULT '', ava_sha256 TEXT NOT NULL DEFAULT '',
ava_size BIGINT NOT NULL DEFAULT 0, 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 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, primary_confirmations_received_count, primary_confirmations_given_count,
shine_confirmations_received_count, shine_confirmations_given_count, updated_at_ms) shine_confirmations_received_count, shine_confirmations_given_count, updated_at_ms)
SELECT p_login, 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, 0,
(SELECT COUNT(*)::INT FROM connections_state cs JOIN channel_names_state cn (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 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=10),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs (SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs
WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=14 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, 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) primary_confirmations_received_count,primary_confirmations_given_count,shine_confirmations_received_count,shine_confirmations_given_count,updated_at_ms)
SELECT p_login, 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(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=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.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.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); 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; 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_AuthChallenge_Handler;
import server.logic.ws_protocol.JSON.handlers.auth.Net_ResolveLoginForAuth_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_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_CreateAuthSession__Handler;
import server.logic.ws_protocol.JSON.handlers.auth.Net_ListSessions_Handler; import server.logic.ws_protocol.JSON.handlers.auth.Net_ListSessions_Handler;
import server.logic.ws_protocol.JSON.handlers.auth.Net_ListEspPairingRequests_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_AuthChallenge_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_ResolveLoginForAuth_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_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_CreateAuthSession_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_ListSessions_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; 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_DeleteConversation_Handler;
import server.logic.ws_protocol.JSON.messages.Net_DeleteMessage_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_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_SendSignal_Handler;
import server.logic.ws_protocol.JSON.messages.Net_ReceiveIncomingMessage_Handler; import server.logic.ws_protocol.JSON.messages.Net_ReceiveIncomingMessage_Handler;
import server.logic.ws_protocol.JSON.messages.Net_SendMessagePair_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_DeleteConversation_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_DeleteMessage_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_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_SendSignal_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_ReceiveIncomingMessage_Request; import server.logic.ws_protocol.JSON.messages.entyties.Net_ReceiveIncomingMessage_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_SendMessagePair_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("AuthChallenge", new Net_AuthChallenge_Handler()),
Map.entry("CreateAuthSession", new Net_CreateAuthSession__Handler()), Map.entry("CreateAuthSession", new Net_CreateAuthSession__Handler()),
Map.entry("CloseActiveSession", new Net_CloseActiveSession_Handler()), Map.entry("CloseActiveSession", new Net_CloseActiveSession_Handler()),
Map.entry("CloseOtherSessions", new Net_CloseOtherSessions_Handler()),
Map.entry("ListSessions", new Net_ListSessions_Handler()), Map.entry("ListSessions", new Net_ListSessions_Handler()),
// --- login to existing session in 2 steps --- // --- login to existing session in 2 steps ---
@@ -257,6 +262,7 @@ public final class JsonHandlerRegistry {
Map.entry("DeleteMessage", new Net_DeleteMessage_Handler()), Map.entry("DeleteMessage", new Net_DeleteMessage_Handler()),
Map.entry("DeleteConversation", new Net_DeleteConversation_Handler()), Map.entry("DeleteConversation", new Net_DeleteConversation_Handler()),
Map.entry("GetDirectMessages", new Net_GetDirectMessages_Handler()), Map.entry("GetDirectMessages", new Net_GetDirectMessages_Handler()),
Map.entry("ReencryptDirectMessage", new Net_ReencryptDirectMessage_Handler()),
Map.entry("AckSessionDelivery", new Net_AckSessionDelivery_Handler()), Map.entry("AckSessionDelivery", new Net_AckSessionDelivery_Handler()),
Map.entry("CallInviteBroadcast", new Net_CallInviteBroadcast_Handler()), Map.entry("CallInviteBroadcast", new Net_CallInviteBroadcast_Handler()),
Map.entry("CallSignalToSession", new Net_CallSignalToSession_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("AuthChallenge", Net_AuthChallenge_Request.class),
Map.entry("CreateAuthSession", Net_CreateAuthSession_Request.class), Map.entry("CreateAuthSession", Net_CreateAuthSession_Request.class),
Map.entry("CloseActiveSession", Net_CloseActiveSession_Request.class), Map.entry("CloseActiveSession", Net_CloseActiveSession_Request.class),
Map.entry("CloseOtherSessions", Net_CloseOtherSessions_Request.class),
Map.entry("ListSessions", Net_ListSessions_Request.class), Map.entry("ListSessions", Net_ListSessions_Request.class),
// --- NEW v2 --- // --- NEW v2 ---
@@ -359,6 +366,7 @@ public final class JsonHandlerRegistry {
Map.entry("DeleteMessage", Net_DeleteMessage_Request.class), Map.entry("DeleteMessage", Net_DeleteMessage_Request.class),
Map.entry("DeleteConversation", Net_DeleteConversation_Request.class), Map.entry("DeleteConversation", Net_DeleteConversation_Request.class),
Map.entry("GetDirectMessages", Net_GetDirectMessages_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("AckSessionDelivery", Net_AckSessionDelivery_Request.class),
Map.entry("CallInviteBroadcast", Net_CallInviteBroadcast_Request.class), Map.entry("CallInviteBroadcast", Net_CallInviteBroadcast_Request.class),
Map.entry("CallSignalToSession", Net_CallSignalToSession_Request.class), Map.entry("CallSignalToSession", Net_CallSignalToSession_Request.class),
@@ -1,10 +1,7 @@
package server.logic.ws_protocol.JSON.handlers.auth; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import server.logic.ws_protocol.JSON.ActiveConnectionsRegistry;
import server.logic.ws_protocol.JSON.ConnectionContext; import server.logic.ws_protocol.JSON.ConnectionContext;
import server.logic.ws_protocol.JSON.entyties.Net_Request; import server.logic.ws_protocol.JSON.entyties.Net_Request;
import server.logic.ws_protocol.JSON.entyties.Net_Response; 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_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_CloseActiveSession_Response; 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.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.logic.ws_protocol.WireCodes;
import server.ws.WsConnectionUtils;
import shine.db.dao.ActiveSessionsDAO; import shine.db.dao.ActiveSessionsDAO;
import shine.db.entities.ActiveSessionEntry; import shine.db.entities.ActiveSessionEntry;
import shine.db.entities.CurrentUserEntry; import shine.db.entities.CurrentUserEntry;
@@ -36,7 +30,6 @@ import java.sql.SQLException;
public class Net_CloseActiveSession_Handler implements JsonMessageHandler { public class Net_CloseActiveSession_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_CloseActiveSession_Handler.class); private static final Logger log = LoggerFactory.getLogger(Net_CloseActiveSession_Handler.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
@Override @Override
public Net_Response handle(Net_Request baseReq, ConnectionContext ctx) throws Exception { 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()); boolean isCurrentSession = targetSessionId.equals(ctx.getSessionId());
closeActiveSession(targetSessionId, ctx, isCurrentSession); closeActiveSession(targetSessionId, isCurrentSession);
Net_CloseActiveSession_Response resp = new Net_CloseActiveSession_Response(); Net_CloseActiveSession_Response resp = new Net_CloseActiveSession_Response();
resp.setOp(req.getOp()); resp.setOp(req.getOp());
@@ -113,7 +106,6 @@ public class Net_CloseActiveSession_Handler implements JsonMessageHandler {
} }
private void closeActiveSession(String targetSessionId, private void closeActiveSession(String targetSessionId,
ConnectionContext currentCtx,
boolean isCurrentSession) { boolean isCurrentSession) {
try { try {
@@ -122,32 +114,20 @@ public class Net_CloseActiveSession_Handler implements JsonMessageHandler {
log.error("Ошибка БД при удалении сессии sessionId={}", targetSessionId, e); log.error("Ошибка БД при удалении сессии sessionId={}", targetSessionId, e);
} }
ConnectionContext ctxToClose = if (isCurrentSession) {
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) {
new Thread(() -> { new Thread(() -> {
try { Thread.sleep(50); } catch (InterruptedException ignored) {} try { Thread.sleep(50); } catch (InterruptedException ignored) {}
WsConnectionUtils.closeConnection( SessionRevocationSupport.revokeConnection(
ctxToClose, targetSessionId,
4000, "closed_from_another_device",
"Session closed by client via CloseActiveSession" "Session closed by client via CloseActiveSession"
); );
}, "CloseSession-" + targetSessionId).start(); }, "CloseSession-" + targetSessionId).start();
} else { } else {
WsConnectionUtils.closeConnection( SessionRevocationSupport.revokeConnection(
ctxToClose, targetSessionId,
4000, "closed_from_another_device",
"Session closed by client via CloseActiveSession" "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_POST & 0xffff)
|| sub == (MsgSubType.TEXT_REPOST & 0xffff) || sub == (MsgSubType.TEXT_REPOST & 0xffff)
|| sub == (MsgSubType.TEXT_CHANNEL_META & 0xffff) || sub == (MsgSubType.TEXT_CHANNEL_META & 0xffff)
|| sub == (MsgSubType.TEXT_CHANNEL_DELETE & 0xffff)
|| sub == (MsgSubType.TEXT_ENTRYPOINT & 0xffff) || sub == (MsgSubType.TEXT_ENTRYPOINT & 0xffff)
|| sub == (MsgSubType.TEXT_EXERCISE & 0xffff) || sub == (MsgSubType.TEXT_EXERCISE & 0xffff)
|| sub == (MsgSubType.TEXT_SERVICE & 0xffff) || sub == (MsgSubType.TEXT_SERVICE & 0xffff)
@@ -80,6 +80,17 @@ public final class BlockchainWriter {
int msgType = block.type & 0xFFFF; int msgType = block.type & 0xFFFF;
int msgSubType = block.subType & 0xFFFF; int msgSubType = block.subType & 0xFFFF;
Integer lineCode = be.getLineCode(); 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) { if (!replayMode && isPublicChannelPublication(msgType, msgSubType) && lineCode != null && lineCode > 0) {
String channelName = channelReadStateDAO.resolvePublicChannelNameByRoot(c, blockchainName, lineCode); String channelName = channelReadStateDAO.resolvePublicChannelNameByRoot(c, blockchainName, lineCode);
if (channelName != null && !channelName.isBlank()) { if (channelName != null && !channelName.isBlank()) {
@@ -110,6 +121,42 @@ public final class BlockchainWriter {
return counterChangedLogins; 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) { private static boolean isPublicChannelPublication(int msgType, int msgSubType) {
if (msgType != 1) return false; if (msgType != 1) return false;
return msgSubType == (MsgSubType.TEXT_POST & 0xFFFF) return msgSubType == (MsgSubType.TEXT_POST & 0xFFFF)
@@ -138,6 +138,7 @@ public final class ChannelNamesStateBootstrapper {
dao.insertAll(c, entries); dao.insertAll(c, entries);
applyMetaUpdates(c, dao, entries, skipped); 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. // 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")) { try (PreparedStatement ps = c.prepareStatement("SELECT shine_refresh_user_stats(login) FROM solana_user_pda_current")) {
ps.execute(); 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, private static void applyMetaUpdates(Connection c,
ChannelNameStateDAO dao, ChannelNameStateDAO dao,
List<ChannelNameStateEntry> entries, List<ChannelNameStateEntry> entries,
@@ -53,7 +53,7 @@ final class ChannelsReadSupport {
String stateSql = """ String stateSql = """
SELECT slug, display_name, channel_description, channel_type_code, channel_type_version, 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 FROM channel_names_state
WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number = ? WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number = ?
LIMIT 1 LIMIT 1
@@ -72,6 +72,9 @@ final class ChannelsReadSupport {
meta.avaSha256 = String.valueOf(rs.getString("ava_sha256") == null ? "" : rs.getString("ava_sha256")); meta.avaSha256 = String.valueOf(rs.getString("ava_sha256") == null ? "" : rs.getString("ava_sha256"));
meta.avaSize = rs.getLong("ava_size"); meta.avaSize = rs.getLong("ava_size");
meta.metaUpdatedAtMs = rs.getLong("meta_updated_at_ms"); 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; 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; return out;
} }
@@ -681,6 +714,9 @@ final class ChannelsReadSupport {
String avaSha256 = ""; String avaSha256 = "";
long avaSize = 0L; long avaSize = 0L;
long metaUpdatedAtMs = 0L; long metaUpdatedAtMs = 0L;
boolean deleted = false;
long deletedAtMs = 0L;
Integer deletedBlockNumber;
} }
static final class MetaEvent { static final class MetaEvent {
@@ -70,6 +70,9 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
channel.setChannelTypeCode(meta.channelTypeCode); channel.setChannelTypeCode(meta.channelTypeCode);
channel.setChannelTypeVersion(meta.channelTypeVersion); channel.setChannelTypeVersion(meta.channelTypeVersion);
channel.setSubscribersCount(loadSubscribersCount(c, ownerBch, lineCode, meta.channelTypeCode)); 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(); Net_GetChannelMessages_Response.BlockRef rootRef = new Net_GetChannelMessages_Response.BlockRef();
rootRef.setBlockNumber(lineCode); rootRef.setBlockNumber(lineCode);
rootRef.setBlockHash(req.getChannel().getChannelRootBlockHash()); rootRef.setBlockHash(req.getChannel().getChannelRootBlockHash());
@@ -75,6 +75,9 @@ public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
channelRef.setChannelTypeCode(meta.channelTypeCode); channelRef.setChannelTypeCode(meta.channelTypeCode);
channelRef.setChannelTypeVersion(meta.channelTypeVersion); channelRef.setChannelTypeVersion(meta.channelTypeVersion);
channelRef.setPersonal(meta.channelTypeCode == 100); 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(); Net_ListSubscriptionsFeed_Response.BlockRef rootRef = new Net_ListSubscriptionsFeed_Response.BlockRef();
rootRef.setBlockNumber(key.rootNumber); rootRef.setBlockNumber(key.rootNumber);
@@ -33,6 +33,9 @@ public class Net_GetChannelMessages_Response extends Net_Response {
private Integer channelTypeCode; private Integer channelTypeCode;
private Integer channelTypeVersion; private Integer channelTypeVersion;
private Integer subscribersCount; private Integer subscribersCount;
private boolean deleted;
private long deletedAtMs;
private Integer deletedBlockNumber;
private BlockRef channelRoot; private BlockRef channelRoot;
public String getOwnerLogin() { return ownerLogin; } public String getOwnerLogin() { return ownerLogin; }
@@ -71,6 +74,13 @@ public class Net_GetChannelMessages_Response extends Net_Response {
public Integer getSubscribersCount() { return subscribersCount; } public Integer getSubscribersCount() { return subscribersCount; }
public void setSubscribersCount(Integer subscribersCount) { this.subscribersCount = 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 BlockRef getChannelRoot() { return channelRoot; }
public void setChannelRoot(BlockRef channelRoot) { this.channelRoot = 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 channelTypeCode;
private Integer channelTypeVersion; private Integer channelTypeVersion;
private boolean personal; private boolean personal;
private boolean deleted;
private long deletedAtMs;
private Integer deletedBlockNumber;
private BlockRef channelRoot; private BlockRef channelRoot;
public String getOwnerLogin() { return ownerLogin; } public String getOwnerLogin() { return ownerLogin; }
@@ -100,6 +103,12 @@ public class Net_ListSubscriptionsFeed_Response extends Net_Response {
public boolean isPersonal() { return personal; } public boolean isPersonal() { return personal; }
public void setPersonal(boolean personal) { this.personal = 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 BlockRef getChannelRoot() { return channelRoot; }
public void setChannelRoot(BlockRef channelRoot) { this.channelRoot = 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.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationContinue_Request; import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationContinue_Request;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory; import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import shine.db.dao.CurrentUsersDAO;
import shine.db.dao.KeyRotationSessionsDAO; import shine.db.dao.KeyRotationSessionsDAO;
import shine.db.dao.SignedMessagesDAO;
import shine.db.entities.KeyRotationSessionEntry; import shine.db.entities.KeyRotationSessionEntry;
import shine.db.entities.KeyRotationStatus; import shine.db.entities.KeyRotationStatus;
/** /** Координирует реально выполненные wallet/DM этапы после rebuild. */
* Сейчас wallet/DM migration — явные заглушки. Continue фиксирует NOT_IMPLEMENTED
* и переводит state machine дальше, не делая вид, что данные были реально мигрированы.
*/
public final class Net_KeyRotationContinue_Handler implements JsonMessageHandler { public final class Net_KeyRotationContinue_Handler implements JsonMessageHandler {
private final KeyRotationSessionsDAO rotations = KeyRotationSessionsDAO.getInstance(); 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", "Нужна авторизованная пользовательская сессия"); return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
} }
try { 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 == null) return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), null);
if (current.getStatus() == KeyRotationStatus.WALLET_MIGRATION) { 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); current = rotations.transition(current.getId(), KeyRotationStatus.WALLET_MIGRATION, KeyRotationStatus.MESSAGE_MIGRATION);
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current); return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current);
} }
if (current.getStatus() == KeyRotationStatus.MESSAGE_MIGRATION) { 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); current = rotations.transition(current.getId(), KeyRotationStatus.MESSAGE_MIGRATION, KeyRotationStatus.FINALIZING);
// FINALIZING пока не содержит отдельной пользовательской работы: сразу завершаем.
current = rotations.transition(current.getId(), KeyRotationStatus.FINALIZING, KeyRotationStatus.COMPLETE); current = rotations.transition(current.getId(), KeyRotationStatus.FINALIZING, KeyRotationStatus.COMPLETE);
refreshCurrentUser(ctx, login);
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current); return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current);
} }
if (current.getStatus() == KeyRotationStatus.FINALIZING) { if (current.getStatus() == KeyRotationStatus.FINALIZING) {
current = rotations.transition(current.getId(), KeyRotationStatus.FINALIZING, KeyRotationStatus.COMPLETE); current = rotations.transition(current.getId(), KeyRotationStatus.FINALIZING, KeyRotationStatus.COMPLETE);
refreshCurrentUser(ctx, login);
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current); return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current);
} }
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_CONTINUE_NOT_ALLOWED", 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.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationRotatePda_Request; import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationRotatePda_Request;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory; import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import shine.db.dao.CurrentUsersDAO;
import shine.db.dao.KeyRotationSessionsDAO; import shine.db.dao.KeyRotationSessionsDAO;
import shine.db.entities.KeyRotationSessionEntry; import shine.db.entities.KeyRotationSessionEntry;
import shine.db.entities.KeyRotationStatus; import shine.db.entities.KeyRotationStatus;
@@ -39,6 +40,8 @@ public final class Net_KeyRotationRotatePda_Handler implements JsonMessageHandle
} }
if (current.getStatus() == KeyRotationStatus.PDA_ROTATED) { 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); return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current);
} }
@@ -61,7 +64,12 @@ public final class Net_KeyRotationRotatePda_Handler implements JsonMessageHandle
// Solana sync мог увидеть новое PDA ещё до этого API-вызова. // Solana sync мог увидеть новое PDA ещё до этого API-вызова.
KeyRotationSessionEntry confirmed = rotations.tryMarkPdaRotatedFromCurrentState(current.getId()); KeyRotationSessionEntry confirmed = rotations.tryMarkPdaRotatedFromCurrentState(current.getId());
rotations.clearError(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) { } catch (Exception e) {
return NetExceptionResponseFactory.error(req, 500, "KEY_ROTATION_ROTATE_PDA_FAILED", return NetExceptionResponseFactory.error(req, 500, "KEY_ROTATION_ROTATE_PDA_FAILED",
"Не удалось зафиксировать Solana-ротацию PDA"); "Не удалось зафиксировать 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.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler; 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.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.handlers.keyRotation.entyties.Net_KeyRotationStart_Request;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory; import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import shine.db.DbController; import shine.db.DbController;
@@ -19,6 +20,7 @@ import shine.db.entities.KeyRotationStatus;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock; 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", "Нужна авторизованная пользовательская сессия"); return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
} }
String login = ctx.getLogin().trim(); 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; String ctxBlockchainName = ctx.getCurrentUser() != null ? ctx.getCurrentUser().getBlockchainName() : null;
if (ctxBlockchainName == null || ctxBlockchainName.isBlank()) { if (ctxBlockchainName == null || ctxBlockchainName.isBlank()) {
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_SESSION_STALE", 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 entry.setProgressTotal(1); // segmented fork publishes only TECH_FORK
KeyRotationSessionEntry created = rotations.createCopyingSession(c, entry); KeyRotationSessionEntry created = rotations.createCopyingSession(c, entry);
List<String> revokedSessionIds = SessionRevocationSupport
.deleteOtherSessions(c, login, currentSessionId);
c.commit(); c.commit();
SessionRevocationSupport.revokeConnections(
revokedSessionIds,
"key_rotation_started",
"Session closed because key rotation started"
);
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), created); return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), created);
} catch (ArithmeticException e) { } catch (ArithmeticException e) {
c.rollback(); 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.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationStatus_Request; import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationStatus_Request;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory; import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import shine.db.dao.CurrentUsersDAO;
import shine.db.dao.KeyRotationSessionsDAO; import shine.db.dao.KeyRotationSessionsDAO;
import shine.db.entities.KeyRotationSessionEntry; import shine.db.entities.KeyRotationSessionEntry;
import shine.db.entities.KeyRotationStatus;
public final class Net_KeyRotationStatus_Handler implements JsonMessageHandler { public final class Net_KeyRotationStatus_Handler implements JsonMessageHandler {
private final KeyRotationSessionsDAO rotations = KeyRotationSessionsDAO.getInstance(); 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", "Нужна авторизованная пользовательская сессия"); return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
} }
try { 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); return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current);
} catch (Exception e) { } catch (Exception e) {
return NetExceptionResponseFactory.error(req, 500, "KEY_ROTATION_STATUS_FAILED", 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; import server.logic.ws_protocol.JSON.entyties.Net_Request;
/** Продолжить один из интерактивных/заглушечных этапов после rebuild. */ /** Продолжить post-PDA этап после фактической клиентской работы. */
public final class Net_KeyRotationContinue_Request extends Net_Request { 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; 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.*; 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; package server.logic.ws_protocol.JSON.handlers.profile.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Request; 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; package server.logic.ws_protocol.JSON.handlers.profile.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Response;import java.util.*; 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(); String peerLogin = req.getPeerLogin().trim();
long beforeTimeMs = req.getBeforeTimeMs() == null ? 0L : req.getBeforeTimeMs(); long beforeTimeMs = req.getBeforeTimeMs() == null ? 0L : req.getBeforeTimeMs();
String beforeMessageKey = req.getBeforeMessageKey() == null ? "" : req.getBeforeMessageKey().trim(); 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 { try {
List<SignedMessageEntry> page = SignedMessagesDAO.getInstance().listConversationPage( List<SignedMessageEntry> page = SignedMessagesDAO.getInstance().listConversationPage(
@@ -56,6 +61,7 @@ public class Net_GetDirectMessages_Handler implements JsonMessageHandler {
peerLogin, peerLogin,
beforeTimeMs, beforeTimeMs,
beforeMessageKey, beforeMessageKey,
reencryptedBeforeMs,
limit + 1 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"); 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 { try {
SignedMessagesCore.verifyUsersAndSignature(incoming); SignedMessagesCore.verifyUsersAndSignature(incoming);
} catch (IllegalArgumentException ex) { } 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()); incoming = SignedMessagesCore.parseFromB64(req.getIncomingBlobB64());
outgoing = SignedMessagesCore.parseFromB64(req.getOutgoingBlobB64()); outgoing = SignedMessagesCore.parseFromB64(req.getOutgoingBlobB64());
SignedMessagesCore.validatePair(incoming, outgoing); SignedMessagesCore.validatePair(incoming, outgoing);
if (incoming.reencryptedAtMs != 0 || outgoing.reencryptedAtMs != 0) {
throw new IllegalArgumentException("BAD_REENCRYPTED_TIME");
}
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, ex.getMessage(), "Некорректный формат пары сообщений"); return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, ex.getMessage(), "Некорректный формат пары сообщений");
} }
@@ -179,7 +179,8 @@ final class SignedMessageBlock {
} }
boolean isSignedByRecipient() { 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; || messageType == TYPE_CONVERSATION_DELETED_BY_RECIPIENT;
} }
@@ -7,6 +7,7 @@ public class Net_GetDirectMessages_Request extends Net_Request {
private Integer limit; private Integer limit;
private Long beforeTimeMs; private Long beforeTimeMs;
private String beforeMessageKey; private String beforeMessageKey;
private Long reencryptedBeforeMs;
public String getPeerLogin() { return peerLogin; } public String getPeerLogin() { return peerLogin; }
public void setPeerLogin(String peerLogin) { this.peerLogin = 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 void setBeforeTimeMs(Long beforeTimeMs) { this.beforeTimeMs = beforeTimeMs; }
public String getBeforeMessageKey() { return beforeMessageKey; } public String getBeforeMessageKey() { return beforeMessageKey; }
public void setBeforeMessageKey(String beforeMessageKey) { this.beforeMessageKey = 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; }
}
+2 -2
View File
@@ -1,2 +1,2 @@
client.version=1.14.9 client.version=1.14.10
server.version=1.12.8 server.version=1.12.9
+17
View File
@@ -488,3 +488,20 @@ TTL заявки фиксирован на сервере и сейчас все
- `404 / PAIRING_NOT_FOUND` - `404 / PAIRING_NOT_FOUND`
- `422 / PAIRING_OF_ANOTHER_REQUESTER` - `422 / PAIRING_OF_ANOTHER_REQUESTER`
- `422 / PAIRING_NOT_PENDING` - `422 / PAIRING_NOT_PENDING`
## 3. `CloseOtherSessions`
Закрывает все активные сессии текущего пользователя, кроме той, из которой выполнен запрос.
Запрос:
```json
{
"op": "CloseOtherSessions",
"payload": {}
}
```
Успешный ответ содержит `closedCount` — число закрытых сессий. Сервер сначала удаляет остальные сессии из `active_sessions`, затем отправляет их активным WebSocket-подключениям событие `SessionRevoked` и закрывает соединения. Текущая сессия не затрагивается.
Эта же внутренняя операция используется при успешном `KeyRotationStart`: после создания ротации в той же транзакции все остальные сессии пользователя удаляются, а после commit их WebSocket-подключения закрываются.
+4 -2
View File
@@ -29,6 +29,7 @@
| `GetTrustedDeviceLoginStatus` | `03_Session_Management_API.md` | чтение статуса и результата pairing-заявки | | `GetTrustedDeviceLoginStatus` | `03_Session_Management_API.md` | чтение статуса и результата pairing-заявки |
| `ListSessions` | `03_Session_Management_API.md` | список активных сессий | | `ListSessions` | `03_Session_Management_API.md` | список активных сессий |
| `CloseActiveSession` | `03_Session_Management_API.md` | закрытие активной сессии | | `CloseActiveSession` | `03_Session_Management_API.md` | закрытие активной сессии |
| `CloseOtherSessions` | `03_Session_Management_API.md` | закрыть все остальные сессии текущего пользователя |
| `AddBlock` | `04_Add_Block_to_Blockchain_API.md` | добавление блока в блокчейн | | `AddBlock` | `04_Add_Block_to_Blockchain_API.md` | добавление блока в блокчейн |
| `GetBlockchainBlock` | `04_Add_Block_to_Blockchain_API.md` | чтение одного блока блокчейна | | `GetBlockchainBlock` | `04_Add_Block_to_Blockchain_API.md` | чтение одного блока блокчейна |
| `KeyRotationStart` | `19_Key_Rotation_API.md` | начать смену ключей сразу в состоянии `COPYING_CHAIN` | | `KeyRotationStart` | `19_Key_Rotation_API.md` | начать смену ключей сразу в состоянии `COPYING_CHAIN` |
@@ -36,7 +37,7 @@
| `KeyRotationAddBlock` | `19_Key_Rotation_API.md` | добавить подписанный новым blockchain key candidate-блок будущего fork | | `KeyRotationAddBlock` | `19_Key_Rotation_API.md` | добавить подписанный новым blockchain key candidate-блок будущего fork |
| `KeyRotationFinishChain` | `19_Key_Rotation_API.md` | проверить полную публикацию candidate-chain и перевести её в `CHAIN_READY` | | `KeyRotationFinishChain` | `19_Key_Rotation_API.md` | проверить полную публикацию candidate-chain и перевести её в `CHAIN_READY` |
| `KeyRotationRotatePda` | `19_Key_Rotation_API.md` | зафиксировать отправленную Solana-ротацию PDA и ждать подтверждения sync | | `KeyRotationRotatePda` | `19_Key_Rotation_API.md` | зафиксировать отправленную Solana-ротацию PDA и ждать подтверждения sync |
| `KeyRotationContinue` | `19_Key_Rotation_API.md` | продолжить интерактивный post-PDA этап; сейчас wallet/DM отмечаются как `NOT_IMPLEMENTED` и пропускаются | | `KeyRotationContinue` | `19_Key_Rotation_API.md` | зафиксировать wallet migration или завершить DM migration после серверной проверки |
| `KeyRotationAbort` | `19_Key_Rotation_API.md` | прервать ротацию до отправки Solana PDA-ротации | | `KeyRotationAbort` | `19_Key_Rotation_API.md` | прервать ротацию до отправки Solana PDA-ротации |
| `GetMyBlockchain` | `20_Get_My_Blockchain_API.md` | постранично читать текущую активную собственную цепочку для аудита и выбора fork point | | `GetMyBlockchain` | `20_Get_My_Blockchain_API.md` | постранично читать текущую активную собственную цепочку для аудита и выбора fork point |
| `ServerHello` | `16_Server_Connection_Pool_API.md` | объявление server-to-server соединения и возможностей peer без криптографической проверки | | `ServerHello` | `16_Server_Connection_Pool_API.md` | объявление server-to-server соединения и возможностей peer без криптографической проверки |
@@ -76,7 +77,8 @@
| `ReceiveIncomingMessage` | `12_Direct_Messages_Push_Calls_API.md` | внутренняя доставка входящего DM-блока на единственный сервер получателя | | `ReceiveIncomingMessage` | `12_Direct_Messages_Push_Calls_API.md` | внутренняя доставка входящего DM-блока на единственный сервер получателя |
| `DeleteMessage` | `12_Direct_Messages_Push_Calls_API.md` | tombstone одного личного сообщения у обеих сторон | | `DeleteMessage` | `12_Direct_Messages_Push_Calls_API.md` | tombstone одного личного сообщения у обеих сторон |
| `DeleteConversation` | `12_Direct_Messages_Push_Calls_API.md` | tombstone удаления истории переписки | | `DeleteConversation` | `12_Direct_Messages_Push_Calls_API.md` | tombstone удаления истории переписки |
| `GetDirectMessages` | `12_Direct_Messages_Push_Calls_API.md` | постраничная загрузка истории личного диалога | | `GetDirectMessages` | `12_Direct_Messages_Push_Calls_API.md` | постраничная загрузка истории личного диалога; опциональный фильтр `reencryptedBeforeMs` |
| `ReencryptDirectMessage` | `12_Direct_Messages_Push_Calls_API.md` | сохранить локальную перешифрованную type=1/2 копию без federation |
| `AckSessionDelivery` | `12_Direct_Messages_Push_Calls_API.md` | подтверждение доставки в сессию | | `AckSessionDelivery` | `12_Direct_Messages_Push_Calls_API.md` | подтверждение доставки в сессию |
| `CallInviteBroadcast` | `12_Direct_Messages_Push_Calls_API.md` | broadcast приглашения к звонку | | `CallInviteBroadcast` | `12_Direct_Messages_Push_Calls_API.md` | broadcast приглашения к звонку |
| `CallSignalToSession` | `12_Direct_Messages_Push_Calls_API.md` | сигнал звонка в конкретную сессию | | `CallSignalToSession` | `12_Direct_Messages_Push_Calls_API.md` | сигнал звонка в конкретную сессию |
@@ -367,3 +367,23 @@ signed-блока проверяется всегда. Официальный UI
- сервер хранит последнюю применённую версию контентного сообщения по правилу `revisionTimeMs`, а при равенстве — по `reencryptedAtMs` - сервер хранит последнюю применённую версию контентного сообщения по правилу `revisionTimeMs`, а при равенстве — по `reencryptedAtMs`
- если сервер уже знает tombstone удаления переписки и получает старое сообщение до этой границы, он перерассылает известный `DeleteConversation` на `access_servers` обеих сторон - если сервер уже знает tombstone удаления переписки и получает старое сообщение до этой границы, он перерассылает известный `DeleteConversation` на `access_servers` обеих сторон
- HTTP endpoints для DM-файлов сейчас отсутствуют - HTTP endpoints для DM-файлов сейчас отсутствуют
## Перешифровка локальных DM при смене client key
`GetDirectMessages` поддерживает необязательный параметр `reencryptedBeforeMs`.
Если он больше нуля, сервер возвращает только `type=1/2` локальные копии диалога, которые были сохранены не позже указанного cutoff (`created_at_ms <= reencryptedBeforeMs`) и ещё не прошли эту миграцию (`reencryptedAtMs < reencryptedBeforeMs`). Обычный запрос без параметра работает как раньше.
Для сохранения локальной перешифрованной копии используется операция `ReencryptDirectMessage`:
```json
{
"op": "ReencryptDirectMessage",
"payload": {
"blobB64": "..."
}
}
```
Операция разрешена только авторизованному владельцу на активном этапе `MESSAGE_MIGRATION`. Принимаются только `type=1/2`; `reencryptedAtMs` обязан совпадать с временем входа текущей rotation в `MESSAGE_MIGRATION` (в текущем состоянии это `updatedAtMs`). Для `type=1` владельцем считается `toLogin`, для `type=2` — `fromLogin`.
`ReencryptDirectMessage` обновляет только уже существующую локальную копию. Он не создаёт federation/delivery-задачу, не посылает push и не отправляет сообщение на сервер собеседника.
+33 -25
View File
@@ -68,7 +68,7 @@
Новые root/blockchain/client keys должны быть валидными 32-байтовыми публичными ключами, отличаться от соответствующих старых ключей и друг от друга. Новые root/blockchain/client keys должны быть валидными 32-байтовыми публичными ключами, отличаться от соответствующих старых ключей и друг от друга.
После успеха создаётся `key_rotation_sessions` со статусом `COPYING_CHAIN`. `progressTotal` равен количеству будущих candidate-блоков: копия `0..forkFromBlock` плюс `TECH_FORK`. После успеха создаётся `key_rotation_sessions` со статусом `COPYING_CHAIN`. В сегментированной модели `progressTotal = 1`: публикуется только один новый `TECH_FORK` с номером `forkFromBlock + 1`; старый префикс `0..forkFromBlock` не перепубликуется.
### Success response ### Success response
@@ -123,7 +123,7 @@
## `KeyRotationAddBlock` ## `KeyRotationAddBlock`
Принимает один ANS-104 DataItem будущего fork на этапе `COPYING_CHAIN`. Candidate-блоки хранятся отдельно от обычной таблицы `blocks`, поэтому до переключения fork они **не создают лайки, ответы, каналы, связи и другие materialized effects**. Принимает единственный ANS-104 `TECH_FORK` будущего сегмента на этапе `COPYING_CHAIN`. Candidate-блок хранится отдельно от обычной таблицы `blocks`, поэтому до переключения fork он **не создаёт лайки, ответы, каналы, связи и другие materialized effects**.
### Request ### Request
@@ -132,9 +132,9 @@
"op": "KeyRotationAddBlock", "op": "KeyRotationAddBlock",
"requestId": "kr-block-1", "requestId": "kr-block-1",
"payload": { "payload": {
"blockNumber": 0, "blockNumber": "<forkFromBlock+1>",
"prevBlockHash": "", "prevBlockHash": "<forkFromHash>",
"blockBytesB64": "<полный ANS-104 DataItem в Base64>" "blockBytesB64": "<полный ANS-104 TECH_FORK DataItem в Base64>"
} }
} }
``` ```
@@ -142,9 +142,8 @@
Правила: Правила:
- операция доступна только при `rotationStatus=COPYING_CHAIN`; - операция доступна только при `rotationStatus=COPYING_CHAIN`;
- блоки принимаются строго последовательно: `0..forkFromBlock`, затем один `TECH_FORK` с номером `forkFromBlock+1`; - принимается только один `TECH_FORK` с номером `forkFromBlock + 1`; старые блоки `0..forkFromBlock` повторно не загружаются;
- каждый DataItem обязан быть подписан `newBlockchainKey`; - каждый DataItem обязан быть подписан `newBlockchainKey`;
- для копируемых блоков Frame, ANS-104 tags, target и anchor должны полностью совпадать с исходным блоком; меняются только owner/signature/DataItem id;
- последний блок обязан быть `TECH_FORK`, а его parent key, fork point, старый tip, reason/comment и число отброшенных блоков должны совпадать с `KeyRotationStart`; - последний блок обязан быть `TECH_FORK`, а его parent key, fork point, старый tip, reason/comment и число отброшенных блоков должны совпадать с `KeyRotationStart`;
- повтор уже принятого идентичного блока безопасен и возвращает success; другой DataItem/hash на том же номере возвращает conflict; - повтор уже принятого идентичного блока безопасен и возвращает success; другой DataItem/hash на том же номере возвращает conflict;
- candidate-блоки попадают в отдельную очередь Arweave/Turbo publisher-а и имеют приоритет перед обычными блоками; - candidate-блоки попадают в отдельную очередь Arweave/Turbo publisher-а и имеют приоритет перед обычными блоками;
@@ -153,11 +152,9 @@
### Основные ошибки ### Основные ошибки
- `KEY_ROTATION_NOT_COPYING` — ротация не находится в `COPYING_CHAIN`; - `KEY_ROTATION_NOT_COPYING` — ротация не находится в `COPYING_CHAIN`;
- `KEY_ROTATION_BLOCK_OUT_OF_ORDER` — пропущен предыдущий candidate-блок; - `KEY_ROTATION_BLOCK_OUT_OF_ORDER` — передан номер, отличный от `forkFromBlock + 1`;
- `KEY_ROTATION_BLOCK_CONFLICT` — на этом номере уже сохранён другой candidate-блок; - `KEY_ROTATION_BLOCK_CONFLICT` — на этом номере уже сохранён другой candidate-блок;
- `KEY_ROTATION_BAD_SIGNATURE` — DataItem подписан не новым blockchain key; - `KEY_ROTATION_BAD_SIGNATURE` — DataItem подписан не новым blockchain key;
- `KEY_ROTATION_FRAME_MISMATCH` — копируемый Frame отличается от исходной цепочки;
- `KEY_ROTATION_TAGS_MISMATCH` — изменены ANS-104 tags копируемого блока;
- `KEY_ROTATION_TECH_FORK_REQUIRED` — вместо финального `TECH_FORK` передан другой блок; - `KEY_ROTATION_TECH_FORK_REQUIRED` — вместо финального `TECH_FORK` передан другой блок;
- ошибки `KEY_ROTATION_TECH_FORK_*` — поля `TECH_FORK` не соответствуют зафиксированной rotation session. - ошибки `KEY_ROTATION_TECH_FORK_*` — поля `TECH_FORK` не соответствуют зафиксированной rotation session.
@@ -177,7 +174,7 @@
## `KeyRotationFinishChain` ## `KeyRotationFinishChain`
Финализирует этап построения candidate-chain. Операция **не меняет PDA** и не переключает активную цепочку пользователя: она только доказывает, что будущий fork уже полностью сохранён и опубликован в Arweave/Turbo. Финализирует публикацию candidate `TECH_FORK`. Операция **не меняет PDA** и не переключает активную цепочку пользователя: она только доказывает, что новый сегмент уже имеет опубликованную точку входа в Arweave/Turbo.
### Request ### Request
@@ -191,14 +188,11 @@
Перед переходом в `CHAIN_READY` сервер повторно проверяет: Перед переходом в `CHAIN_READY` сервер повторно проверяет:
- количество candidate-блоков равно `progressTotal` (`0..forkFromBlock` + один `TECH_FORK`); - существует ровно один candidate-блок, соответствующий `progressTotal = 1`;
- каждый candidate-блок уже подтверждён Arweave/Turbo publisher-ом; - каждый candidate-блок уже подтверждён Arweave/Turbo publisher-ом;
- номера идут строго `0,1,2,...` без дырок;
- `blockHash` и `DataItem id` совпадают с сохранёнными значениями; - `blockHash` и `DataItem id` совпадают с сохранёнными значениями;
- каждый DataItem подписан `newBlockchainKey`; - каждый DataItem подписан `newBlockchainKey`;
- `block 0` имеет нулевой `prevHash`, а каждый следующий блок ссылается на hash предыдущего Frame; - единственный candidate-блок является корректным `TECH_FORK`, его `prevHash` равен hash выбранного fork point, а body повторяет зафиксированные parent key, fork point, parent tip, reason/comment и число отброшенных блоков.
- копируемые блоки всё ещё байт-в-байт совпадают с выбранным префиксом исходной цепочки по Frame, tags, target и anchor;
- последний блок является корректным `TECH_FORK` и повторяет зафиксированные fork point, parent tip, reason/comment и число отброшенных блоков.
Только после успешной финальной проверки выполняется: Только после успешной финальной проверки выполняется:
@@ -212,8 +206,7 @@
- `KEY_ROTATION_NOT_COPYING` — текущий этап уже не позволяет завершать candidate-chain; - `KEY_ROTATION_NOT_COPYING` — текущий этап уже не позволяет завершать candidate-chain;
- `KEY_ROTATION_CHAIN_INCOMPLETE` — сервер получил не все candidate-блоки; - `KEY_ROTATION_CHAIN_INCOMPLETE` — сервер получил не все candidate-блоки;
- `KEY_ROTATION_CHAIN_NOT_PUBLISHED` — не все DataItem подтверждены Arweave/Turbo publisher-ом; - `KEY_ROTATION_CHAIN_NOT_PUBLISHED` — не все DataItem подтверждены Arweave/Turbo publisher-ом;
- `KEY_ROTATION_CANDIDATE_GAP` / `KEY_ROTATION_CHAIN_HASH_MISMATCH` — нарушена последовательность candidate-chain; - `KEY_ROTATION_BAD_SIGNATURE` — сохранённый `TECH_FORK` не подтверждается новым blockchain key;
- `KEY_ROTATION_BAD_SIGNATURE` — сохранённый candidate не подтверждается новым blockchain key;
- `KEY_ROTATION_TECH_FORK_*` — финальный `TECH_FORK` больше не соответствует rotation session; - `KEY_ROTATION_TECH_FORK_*` — финальный `TECH_FORK` больше не соответствует rotation session;
- `KEY_ROTATION_FINISH_CHAIN_RACE` — состояние ротации было одновременно изменено другой операцией. - `KEY_ROTATION_FINISH_CHAIN_RACE` — состояние ротации было одновременно изменено другой операцией.
@@ -285,22 +278,31 @@
## `KeyRotationContinue` ## `KeyRotationContinue`
Продолжает интерактивные post-PDA этапы. Сервер по-прежнему не хранит приватные ключи и сам не переводит средства. В текущем UI перед вызовом `KeyRotationContinue` на этапе `WALLET_MIGRATION` пользователь может перевести весь доступный SOL со старого blockchain-wallet на новый (или явно пропустить перенос). После этого сервер фиксирует этап как `NOT_IMPLEMENTED`/завершённый placeholder и переводит процесс дальше. Продолжает post-PDA этапы после фактической клиентской работы. Сервер не хранит приватные ключи и сам не переводит средства и не расшифровывает DM.
- `WALLET_MIGRATION`: клиентский UI выполняет перенос SOL локально, используя временно доступный старый blockchain private key; сервер только продолжает state machine. Перенос AR/Turbo пока TODO; ### `WALLET_MIGRATION`
- `MESSAGE_MIGRATION`: `messageMigrationStatus = NOT_IMPLEMENTED`, затем `FINALIZING -> COMPLETE`.
Request: Клиент сначала выполняет перенос SOL локально или пользователь явно пропускает перенос, затем вызывает:
```json ```json
{ {
"op": "KeyRotationContinue", "op": "KeyRotationContinue",
"requestId": "kr-continue-1", "requestId": "kr-continue-wallet",
"payload": {} "payload": {
"walletMigrationStatus": "COMPLETE"
}
} }
``` ```
`KeyRotationContinue` сам не переводит деньги и не перешифровывает DM. SOL-перевод реализован на стороне UI до этого запроса; серверная часть WALLET_MIGRATION остаётся точкой координации. AR/Turbo и DM остаются отдельными точками расширения. Допустимые значения: `COMPLETE`, `SKIPPED`. После фиксации сервер переводит ротацию в `MESSAGE_MIGRATION`. Автоматически переносится только SOL; другие активы пользователь переносит вручную.
### `MESSAGE_MIGRATION`
Момент перехода в `MESSAGE_MIGRATION` становится cutoff текущей DM-миграции (`updatedAtMs` состояния). Клиент выбирает старые локальные копии через `GetDirectMessages` с `reencryptedBeforeMs=cutoff`, перешифровывает их старым/новым client key и сохраняет через `ReencryptDirectMessage`, выставляя `reencryptedAtMs=cutoff`.
После обхода клиент вызывает `KeyRotationContinue` с пустым payload. Сервер сам считает строки владельца с `message_type IN (1,2)`, `created_at_ms <= cutoff` и `reencrypted_at_ms < cutoff`. Если они ещё есть, возвращается `KEY_ROTATION_DM_PENDING`. Если нет — `message_migration_status=COMPLETE`, затем `FINALIZING -> COMPLETE`.
Эта схема позволяет безопасно продолжить после перезапуска: уже обновлённые сообщения больше не попадают в выборку. Новые сообщения, сохранённые после начала `MESSAGE_MIGRATION`, в текущую миграцию не включаются.
## `KeyRotationAbort` ## `KeyRotationAbort`
@@ -321,3 +323,9 @@ Request:
``` ```
При `ABORTED` временные candidate-строки удаляются из PostgreSQL. Уже опубликованные Arweave DataItem остаются неизменяемым сиротским историческим следом и не становятся активной цепочкой, поскольку PDA не переключён. При `ABORTED` временные candidate-строки удаляются из PostgreSQL. Уже опубликованные Arweave DataItem остаются неизменяемым сиротским историческим следом и не становятся активной цепочкой, поскольку PDA не переключён.
## Пользовательский flow key rotation (06.10.2026)
`KeyRotationStart` после успешного создания ротации в той же транзакции удаляет все остальные активные сессии пользователя, оставляя текущую. После commit активные WebSocket-подключения этих сессий получают `SessionRevoked` и закрываются.
Для пользователя подготовка `TECH_FORK` и последующая смена PDA выглядят как одна последовательность: если старый и новый наборы ключей ещё находятся в RAM, после `CHAIN_READY` клиент автоматически запускает Solana-ротацию без повторного ввода паролей. Серверные состояния остаются отдельными checkpoint'ами для безопасного восстановления.
+4
View File
@@ -33,3 +33,7 @@
- сервер файлов ключ расшифрования не получает. - сервер файлов ключ расшифрования не получает.
Формат бинарного контейнера `SHiNE_DM` при этом не меняется. Формат бинарного контейнера `SHiNE_DM` при этом не меняется.
### Key rotation и локальный архив DM
При смене client key старые `type=1/2` локальные копии перешифровываются клиентом пакетами. Критерий незавершённой миграции — локальная копия была сохранена до cutoff входа в `MESSAGE_MIGRATION` и имеет `reencryptedAtMs < cutoff`. Повторная отправка на сервер собеседника не выполняется. Для перешифрованного входящего `type=1` подпись принадлежит получателю; это локальная мигрированная копия, а не сохранённая подпись первоначального отправителя.
@@ -262,3 +262,11 @@ DeleteMessage принимает type=5/6. DeleteConversation принимает
- исходный `<S:reply...>` не переносится, поэтому новое сообщение не остаётся ответом на сообщение из старого чата; - исходный `<S:reply...>` не переносится, поэтому новое сообщение не остаётся ответом на сообщение из старого чата;
- для сообщения с файлами повторно используются существующие `<S:file...>`-описатели, поэтому ciphertext не шифруется и не загружается повторно; - для сообщения с файлами повторно используются существующие `<S:file...>`-описатели, поэтому ciphertext не шифруется и не загружается повторно;
- сервер и получатель видят пересланное сообщение как обычное новое сообщение без служебной пометки об источнике. - сервер и получатель видят пересланное сообщение как обычное новое сообщение без служебной пометки об источнике.
## Перешифровка локального архива при смене client key (06.10.2026)
При key rotation сервер собеседника повторно не уведомляется. Меняются только локальные копии `type=1` и `type=2` на access-сервере владельца архива.
`reencryptedAtMs=0` означает обычную исходную копию. При входе rotation в `MESSAGE_MIGRATION` её `updatedAtMs` фиксирует cutoff текущей миграции. Старые локальные копии, сохранённые до cutoff, получают `reencryptedAtMs=cutoff`. Следующая ротация использует уже свой новый cutoff.
Правило подписи `type=1` зависит от `reencryptedAtMs`: исходная входящая копия (`0`) подписана отправителем; локально перешифрованная входящая копия (`>0`) подписывается новым client key получателя. `type=2` остаётся подписанным владельцем исходящей локальной копии (`fromLogin`). Перешифрованная копия предназначена для локального восстановления содержимого новым client key и не считается сохранением первоначальной подписи отправителя.
+13 -1
View File
@@ -317,7 +317,9 @@ UI-примечание (байтовый формат не меняет): ра
Правило подписи по `messageType`: Правило подписи по `messageType`:
- `1`, `2`, `5`, `7` подписывает отправитель сообщения; - `1` при `reencryptedAtMs = 0` подписывает исходный отправитель сообщения;
- `1` при `reencryptedAtMs > 0` — это локальная перешифрованная копия, её подписывает получатель;
- `2`, `5`, `7` подписывает отправитель сообщения;
- `6`, `8` подписывает получатель сообщения. - `6`, `8` подписывает получатель сообщения.
Практическое UI-следствие: Практическое UI-следствие:
@@ -393,3 +395,13 @@ UI-примечание (байтовый формат не меняет): ра
- информация о том, из какого чата или сообщения выполнена пересылка, в контейнер не добавляется. - информация о том, из какого чата или сообщения выполнена пересылка, в контейнер не добавляется.
Таким образом подпись, `baseKey`, шифрование и структура контейнера остаются полностью прежними: меняется только содержимое нового plaintext перед стандартной отправкой. Таким образом подпись, `baseKey`, шифрование и структура контейнера остаются полностью прежними: меняется только содержимое нового plaintext перед стандартной отправкой.
## Семантика `reencryptedAtMs` и подписи при key rotation (06.10.2026)
Байтовый формат `SHiNE_DM v1.0` не изменяется. Поле `reencryptedAtMs` используется как эпоха локальной перешифровки.
- `type=1`, `reencryptedAtMs == 0`: подпись проверяется по `clientKey` `fromLogin`.
- `type=1`, `reencryptedAtMs > 0`: подпись проверяется по `clientKey` `toLogin`; ciphertext зашифрован на новый client key получателя.
- `type=2`: подпись проверяется по `clientKey` `fromLogin`; при миграции ciphertext локальной исходящей копии также шифруется на новый client key владельца.
При перешифровке сохраняются `fromLogin`, `toLogin`, `timeMs`, `nonce`, `messageType` и `revisionTimeMs`; меняются encrypted body, подпись и `reencryptedAtMs`.
+23
View File
@@ -1,5 +1,6 @@
import { iconHtml } from '../components/ui-icon.js'; import { iconHtml } from '../components/ui-icon.js';
import { createTopBar } from '../components/topbar.js'; import { createTopBar } from '../components/topbar.js';
import { confirmDialog } from '../components/confirm-dialog.js';
import { renderAvatar } from '../components/avatar-image.js'; import { renderAvatar } from '../components/avatar-image.js';
import { authService, setChannelsFeed, state } from '../state.js'; import { authService, setChannelsFeed, state } from '../state.js';
import { navigateBack, getPreviousTrackedPath } from '../router.js'; import { navigateBack, getPreviousTrackedPath } from '../router.js';
@@ -446,6 +447,7 @@ export function render({ navigate, route, chrome }) {
const channelName = String(channel?.channelName || '').trim(); const channelName = String(channel?.channelName || '').trim();
const description = String(channel?.channelDescription || channel?.description || '').trim(); const description = String(channel?.channelDescription || channel?.description || '').trim();
const subscribersCount = Number(channel?.subscribersCount || 0); const subscribersCount = Number(channel?.subscribersCount || 0);
const isDeleted = !!channel?.deleted;
const shortRoute = makeShineChannelShortRoute({ const shortRoute = makeShineChannelShortRoute({
ownerLogin, ownerLogin,
ownerBlockchainName: selector?.ownerBlockchainName, ownerBlockchainName: selector?.ownerBlockchainName,
@@ -471,6 +473,7 @@ export function render({ navigate, route, chrome }) {
<div class="channel-about-avatar-slot" id="channel-about-avatar-slot"></div> <div class="channel-about-avatar-slot" id="channel-about-avatar-slot"></div>
<h2 class="channel-about-title">${escapeHtml(cleanName)}</h2> <h2 class="channel-about-title">${escapeHtml(cleanName)}</h2>
<div class="channel-about-subline">@${escapeHtml(channelName || ownerLogin)} · ${escapeHtml(statsText(subscribersCount))} ${escapeHtml(subscribersWord(subscribersCount))}</div> <div class="channel-about-subline">@${escapeHtml(channelName || ownerLogin)} · ${escapeHtml(statsText(subscribersCount))} ${escapeHtml(subscribersWord(subscribersCount))}</div>
${isDeleted ? '<div class="status-line is-unavailable">Канал удалён владельцем. История остаётся доступной.</div>' : ''}
</div> </div>
<div class="channel-about-tiles"> <div class="channel-about-tiles">
@@ -492,6 +495,10 @@ export function render({ navigate, route, chrome }) {
</span> </span>
<span class="channel-about-row-chevron">${iconHtml('chevron')}</span> <span class="channel-about-row-chevron">${iconHtml('chevron')}</span>
</button> </button>
${isOwnChannel && !isDeleted ? `<button class="channel-about-row" id="channel-about-delete" type="button">
<span class="channel-about-row-main"><span class="channel-about-row-label">Удалить канал</span><span class="meta-muted">Канал можно будет восстановить новой публикацией</span></span>
<span class="channel-about-row-chevron" aria-hidden="true">${iconHtml('trash')}</span>
</button>` : ''}
<button class="channel-about-row" id="channel-about-copy-row" type="button"> <button class="channel-about-row" id="channel-about-copy-row" type="button">
<span class="channel-about-row-main"> <span class="channel-about-row-main">
<span class="channel-about-row-label">Ссылка</span> <span class="channel-about-row-label">Ссылка</span>
@@ -538,6 +545,22 @@ export function render({ navigate, route, chrome }) {
} }
}; };
content.querySelector('#channel-about-copy-row')?.addEventListener('click', copyLink); content.querySelector('#channel-about-copy-row')?.addEventListener('click', copyLink);
content.querySelector('#channel-about-delete')?.addEventListener('click', async () => {
if (!await confirmDialog({
title: 'Удалить канал?',
text: 'Канал исчезнет из обычных списков, но история и старая ссылка останутся доступны. Новая публикация автоматически восстановит канал.',
confirmLabel: 'Удалить канал',
danger: true,
})) return;
try {
const { login, storagePwd } = requireSigningSession();
await authService.addBlockChannelDelete({ login, storagePwd, channel: selector });
showToast('Канал помечен как удалённый');
void refresh();
} catch (error) {
showToast(toUserMessage(error, 'Не удалось удалить канал.'), { kind: 'error' });
}
});
const subscriptionButton = content.querySelector('#channel-about-subscription'); const subscriptionButton = content.querySelector('#channel-about-subscription');
subscriptionButton?.addEventListener('click', async () => { subscriptionButton?.addEventListener('click', async () => {
+13 -2
View File
@@ -1512,6 +1512,8 @@ async function loadFromApi(route, channelId) {
metaUpdatedAtMs: Number(payload.channel?.metaUpdatedAtMs || 0), metaUpdatedAtMs: Number(payload.channel?.metaUpdatedAtMs || 0),
subscribersCount: Number(payload.channel?.subscribersCount || 0), subscribersCount: Number(payload.channel?.subscribersCount || 0),
ownerName: ownerLogin || 'неизвестно', ownerName: ownerLogin || 'неизвестно',
deleted: !!payload.channel?.deleted,
deletedAtMs: Number(payload.channel?.deletedAtMs || 0),
}, },
posts, posts,
metaEvents: Array.isArray(payload?.metaEvents) ? payload.metaEvents : [], metaEvents: Array.isArray(payload?.metaEvents) ? payload.metaEvents : [],
@@ -1626,12 +1628,14 @@ function renderChannelMetaEventCard(event, dayLabel = '') {
card.className = 'card channel-system-event-card'; card.className = 'card channel-system-event-card';
const label = event.kind === 'created' const label = event.kind === 'created'
? 'Канал создан' ? 'Канал создан'
: 'Изменено описание канала'; : event.kind === 'deleted'
? 'Канал удалён'
: 'Изменено описание канала';
const shownLabel = dayLabel ? `${label} · ${dayLabel.toLocaleLowerCase('ru-RU')}` : label; const shownLabel = dayLabel ? `${label} · ${dayLabel.toLocaleLowerCase('ru-RU')}` : label;
card.innerHTML = ` card.innerHTML = `
<span class="channel-system-event-card__label">${escapeHtml(shownLabel)}</span> <span class="channel-system-event-card__label">${escapeHtml(shownLabel)}</span>
`; `;
card.addEventListener('click', () => { if (event.kind !== 'deleted') card.addEventListener('click', () => {
openChannelMetaDetailsModal({ openChannelMetaDetailsModal({
title: label, title: label,
channel: { channel: {
@@ -2193,6 +2197,13 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
const messagesCount = Math.max(0, Number(channelData.messagesCount || (Array.isArray(channelData.posts) ? channelData.posts.length : 0) || 0)); const messagesCount = Math.max(0, Number(channelData.messagesCount || (Array.isArray(channelData.posts) ? channelData.posts.length : 0) || 0));
const readCount = Math.max(0, Math.min(Number(channelData.readCount || 0), messagesCount)); const readCount = Math.max(0, Math.min(Number(channelData.readCount || 0), messagesCount));
if (channelData?.channel?.deleted) {
const deletedNotice = document.createElement('div');
deletedNotice.className = 'card status-line is-unavailable';
deletedNotice.textContent = 'Канал удалён владельцем. История доступна для просмотра.';
screen.append(deletedNotice);
}
if (channelData.reverseChannelMissingWarning) { if (channelData.reverseChannelMissingWarning) {
const reverseWarning = document.createElement('p'); const reverseWarning = document.createElement('p');
reverseWarning.className = 'channel-head-meta'; reverseWarning.className = 'channel-head-meta';
+1
View File
@@ -108,6 +108,7 @@ function isStoriesChannel(summaryOrChannel = null) {
function isVisibleChannelSummary(summary) { function isVisibleChannelSummary(summary) {
if (!summary?.channel) return false; if (!summary?.channel) return false;
if (isStoriesChannel(summary)) return false; if (isStoriesChannel(summary)) return false;
if (summary?.channel?.deleted) return false;
const ownerLogin = String(summary.channel.ownerLogin || '').trim(); const ownerLogin = String(summary.channel.ownerLogin || '').trim();
const channelName = String(summary.channel.channelName || '').trim(); const channelName = String(summary.channel.channelName || '').trim();
return !!ownerLogin && !!channelName; return !!ownerLogin && !!channelName;
+24 -1
View File
@@ -1,6 +1,7 @@
import { showToast } from '../services/channels-ux.js'; import { showToast } from '../services/channels-ux.js';
import { createTopBar } from '../components/topbar.js'; import { createTopBar } from '../components/topbar.js';
import { import {
authService,
isSessionInvalidError, isSessionInvalidError,
refreshSessions, refreshSessions,
setAuthError, setAuthError,
@@ -149,10 +150,32 @@ export function render({navigate, chrome}) {
empty.textContent = 'Других сеансов нет.'; empty.textContent = 'Других сеансов нет.';
sessionsBlock.append(empty); sessionsBlock.append(empty);
} else { } else {
const closeAll = document.createElement('button');
closeAll.className = 'shine-btn shine-btn--settings';
closeAll.type = 'button';
closeAll.textContent = 'Закрыть все остальные сеансы';
closeAll.addEventListener('click', async () => {
if (!window.confirm('Все остальные активные сеансы будут закрыты. Продолжить?')) return;
closeAll.disabled = true;
try {
const result = await authService.closeOtherSessions();
await refreshSessions();
buildList();
showToast(`Закрыто сеансов: ${Number(result?.closedCount || 0)}`);
} catch (error) {
closeAll.disabled = false;
if (isSessionInvalidError(error)) {
await terminateCurrentSession({ infoMessage: 'Сессия на этом устройстве уже завершена. Выполните вход заново.' });
return;
}
setAuthError(error.message);
showToast(error.message, { kind: 'error' });
}
});
const othersList = document.createElement('div'); const othersList = document.createElement('div');
othersList.className = 'nav-list'; othersList.className = 'nav-list';
others.forEach((session) => othersList.append(createSessionItem(session, false))); others.forEach((session) => othersList.append(createSessionItem(session, false)));
sessionsBlock.append(othersList); sessionsBlock.append(closeAll, othersList);
} }
}; };
+61 -12
View File
@@ -10,7 +10,7 @@ export const pageMeta = { id:'key-rotation-view', title:'Смена ключей
const POLL_MS=1800; const POLL_MS=1800;
function h(v){return String(v??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));} function h(v){return String(v??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));}
function short(v){const s=String(v||'');return s.length>20?`${s.slice(0,10)}…${s.slice(-8)}`:s;} function short(v){const s=String(v||'');return s.length>20?`${s.slice(0,10)}…${s.slice(-8)}`:s;}
function stageText(s){return ({COPYING_CHAIN:'Копирование новой цепочки',CHAIN_READY:'Новая цепочка готова',ROTATING_PDA:'Ожидание Solana',PDA_ROTATED:'PDA обновлена',REBUILDING_SERVER:'Перестройка сервера',WALLET_MIGRATION:'Перенос средств',MESSAGE_MIGRATION:'Перешифрование сообщений',FINALIZING:'Завершение',COMPLETE:'Готово',NONE:'Новая ротация'})[s]||s;} function stageText(s){return ({COPYING_CHAIN:'Публикация TECH_FORK',CHAIN_READY:'Новая цепочка готова',ROTATING_PDA:'Ожидание Solana',PDA_ROTATED:'PDA обновлена',REBUILDING_SERVER:'Перестройка сервера',WALLET_MIGRATION:'Перенос средств',MESSAGE_MIGRATION:'Перешифрование сообщений',FINALIZING:'Завершение',COMPLETE:'Готово',NONE:'Новая ротация'})[s]||s;}
function input(label,type='password'){const wrap=document.createElement('label');wrap.className='stack';const t=document.createElement('span');t.className='field-label';t.textContent=label;const el=document.createElement('input');el.className='text-input';el.type=type;wrap.append(t,el);return {wrap,el};} function input(label,type='password'){const wrap=document.createElement('label');wrap.className='stack';const t=document.createElement('span');t.className='field-label';t.textContent=label;const el=document.createElement('input');el.className='text-input';el.type=type;wrap.append(t,el);return {wrap,el};}
export function render({navigate,chrome}){ export function render({navigate,chrome}){
@@ -31,7 +31,7 @@ export function render({navigate,chrome}){
function note(text){const c=document.createElement('div');c.className='card';c.textContent=text;return c;} function note(text){const c=document.createElement('div');c.className='card';c.textContent=text;return c;}
async function renderNone(){ async function renderNone(){
const head=note('Выберите последний блок, которому вы доверяете. Всё до него будет точно перепубликовано новым blockchain key, после чего добавится TECH_FORK.'); const head=note('Выберите последний блок, которому вы доверяете. Новый fork начнётся после него одним TECH_FORK, подписанным новым blockchain key; старый префикс цепочки не перепубликуется.');
const oldP=input('Текущий пароль'); const newP=input('Новый пароль'); const new2=input('Повторите новый пароль'); const oldP=input('Текущий пароль'); const newP=input('Новый пароль'); const new2=input('Повторите новый пароль');
const reason=document.createElement('select');reason.className='text-input';for(const r of KEY_ROTATION_REASONS){const o=document.createElement('option');o.value=String(r.code);o.textContent=r.label;reason.append(o);} const reason=document.createElement('select');reason.className='text-input';for(const r of KEY_ROTATION_REASONS){const o=document.createElement('option');o.value=String(r.code);o.textContent=r.label;reason.append(o);}
const reasonWrap=document.createElement('label');reasonWrap.className='stack';reasonWrap.innerHTML='<span class="field-label">Причина</span>';reasonWrap.append(reason); const reasonWrap=document.createElement('label');reasonWrap.className='stack';reasonWrap.innerHTML='<span class="field-label">Причина</span>';reasonWrap.append(reason);
@@ -42,22 +42,26 @@ export function render({navigate,chrome}){
more.addEventListener('click',()=>void load()); more.addEventListener('click',()=>void load());
const start=document.createElement('button');start.className='primary-btn';start.type='button';start.textContent='Начать смену ключей'; const start=document.createElement('button');start.className='primary-btn';start.type='button';start.textContent='Начать смену ключей';
const error=document.createElement('div');error.className='meta-muted'; const error=document.createElement('div');error.className='meta-muted';
start.addEventListener('click',async()=>{start.disabled=true;error.textContent='';try{if(!selected)throw new Error('Выберите последний доверенный блок');if(!oldP.el.value||!newP.el.value)throw new Error('Введите текущий и новый пароль');if(newP.el.value!==new2.el.value)throw new Error('Новые пароли не совпадают');if(oldP.el.value===newP.el.value)throw new Error('Новый пароль должен отличаться');cachedOldBundle=await derive(oldP.el.value);await verifyOldPassword(cachedOldBundle);cachedNewBundle=await derive(newP.el.value);const s=await client.start({newRootKey:cachedNewBundle.rootPair.publicKeyB64,newBlockchainKey:cachedNewBundle.blockchainPair.publicKeyB64,newClientKey:cachedNewBundle.clientPair.publicKeyB64,forkFromBlock:selected.blockNumber,forkFromHash:selected.blockHash,reasonCode:Number(reason.value),comment:comment.value});await runCopy(s); }catch(e){error.textContent=e?.message||String(e);start.disabled=false;}}); start.addEventListener('click',async()=>{start.disabled=true;error.textContent='';try{if(!selected)throw new Error('Выберите последний доверенный блок');if(!oldP.el.value||!newP.el.value)throw new Error('Введите текущий и новый пароль');if(newP.el.value!==new2.el.value)throw new Error('Новые пароли не совпадают');if(oldP.el.value===newP.el.value)throw new Error('Новый пароль должен отличаться');if(!window.confirm('После запуска все остальные сеансы этого аккаунта будут закрыты. Продолжить?')){start.disabled=false;return;}cachedOldBundle=await derive(oldP.el.value);await verifyOldPassword(cachedOldBundle);cachedNewBundle=await derive(newP.el.value);const stateNow=await client.start({newRootKey:cachedNewBundle.rootPair.publicKeyB64,newBlockchainKey:cachedNewBundle.blockchainPair.publicKeyB64,newClientKey:cachedNewBundle.clientPair.publicKeyB64,forkFromBlock:selected.blockNumber,forkFromHash:selected.blockHash,reasonCode:Number(reason.value),comment:comment.value});await runCopy(stateNow); }catch(e){error.textContent=e?.message||String(e);start.disabled=false;}});
setRoot(head,oldP.wrap,newP.wrap,new2.wrap,reasonWrap,comment,list,more,start,error);void load(); setRoot(head,oldP.wrap,newP.wrap,new2.wrap,reasonWrap,comment,list,more,start,error);void load();
} }
async function askNewPasswordAndCopy(s){ async function askNewPasswordAndCopy(s){
const card=statusCard(s), p=input('Новый пароль');const go=document.createElement('button');go.className='primary-btn';go.textContent='Продолжить копирование';const err=document.createElement('div');err.className='meta-muted';go.addEventListener('click',async()=>{go.disabled=true;try{cachedNewBundle=await derive(p.el.value);if(cachedNewBundle.blockchainPair.publicKeyB64!==s.newBlockchainKey)throw new Error('Этот пароль выводит другой новый blockchain key');await runCopy(s);}catch(e){err.textContent=e?.message||e;go.disabled=false;}});const abort=document.createElement('button');abort.className='secondary-btn';abort.textContent='Прервать смену ключей';abort.addEventListener('click',async()=>{await client.abort();await refresh();});setRoot(card,note('Для продолжения на этом устройстве введите тот же новый пароль, который использовался при запуске.'),p.wrap,go,abort,err); const card=statusCard(s), p=input('Новый пароль');const go=document.createElement('button');go.className='primary-btn';go.textContent='Продолжить публикацию TECH_FORK';const err=document.createElement('div');err.className='meta-muted';go.addEventListener('click',async()=>{go.disabled=true;try{cachedNewBundle=await derive(p.el.value);if(cachedNewBundle.blockchainPair.publicKeyB64!==s.newBlockchainKey)throw new Error('Этот пароль выводит другой новый blockchain key');await runCopy(s);}catch(e){err.textContent=e?.message||e;go.disabled=false;}});const abort=document.createElement('button');abort.className='secondary-btn';abort.textContent='Прервать смену ключей';abort.addEventListener('click',async()=>{await client.abort();await refresh();});setRoot(card,note('Для продолжения на этом устройстве введите тот же новый пароль, который использовался при запуске.'),p.wrap,go,abort,err);
} }
async function runCopy(s){ async function runCopy(s){
const card=statusCard(s), info=note('Создаётся новая копия выбранной части цепочки в Arweave/Turbo. Обычные записи аккаунта в это время заблокированы.');setRoot(card,info); const card=statusCard(s), info=note('Создаётся и публикуется TECH_FORK нового сегмента в Arweave/Turbo. Обычные записи аккаунта в это время заблокированы.');setRoot(card,info);
try{await client.copyCandidateChain({rotation:s,newBundle:cachedNewBundle,onProgress:({current,total})=>{card.querySelectorAll('.meta-muted')[1].textContent=`Прогресс: ${current} / ${total}`;}});await client.waitUntilPublished({onProgress:({current,total})=>{card.querySelectorAll('.meta-muted')[1].textContent=`Опубликовано: ${current} / ${total}`;}});await client.finishChain();await refresh();}catch(e){root.append(note(e?.message||String(e)));const retry=document.createElement('button');retry.className='primary-btn';retry.textContent='Повторить / продолжить';retry.addEventListener('click',()=>void refresh());root.append(retry);} try{await client.copyCandidateChain({rotation:s,newBundle:cachedNewBundle,onProgress:({current,total})=>{card.querySelectorAll('.meta-muted')[1].textContent=`Прогресс: ${current} / ${total}`;}});await client.waitUntilPublished({onProgress:({current,total})=>{card.querySelectorAll('.meta-muted')[1].textContent=`Опубликовано: ${current} / ${total}`;}});await client.finishChain();await refresh();}catch(e){root.append(note(e?.message||String(e)));const retry=document.createElement('button');retry.className='primary-btn';retry.textContent='Повторить / продолжить';retry.addEventListener('click',()=>void refresh());root.append(retry);}
} }
async function renderChainReady(s){ async function renderChainReady(s){
const oldP=input('Текущий пароль');const newP=input('Новый пароль');const go=document.createElement('button');go.className='primary-btn';go.textContent='Изменить ключи в Solana';const abort=document.createElement('button');abort.className='secondary-btn';abort.textContent='Прервать смену ключей';const err=document.createElement('div');err.className='meta-muted'; if(cachedOldBundle&&cachedNewBundle){
go.addEventListener('click',async()=>{go.disabled=true;try{cachedOldBundle=await derive(oldP.el.value);cachedNewBundle=await derive(newP.el.value);await client.rotatePda({login,solanaEndpoint,oldBundle:cachedOldBundle,newBundle:cachedNewBundle,storagePwd});await refresh();}catch(e){err.textContent=e?.message||String(e);go.disabled=false;}});abort.addEventListener('click',async()=>{await client.abort();await refresh();});setRoot(statusCard(s),note('Новая цепочка полностью готова. Следующий шаг — точка невозврата: старый ключ восстановления временно используется для атомарной смены recovery + client + blockchain fork, а новое PDA подпишет новый blockchain key. Приватный ключ восстановления на устройстве не сохраняется.'),oldP.wrap,newP.wrap,go,abort,err); setRoot(statusCard(s),note('Новая цепочка готова. Ключи в Solana меняются автоматически в рамках той же процедуры.'));
try{await client.rotatePda({login,solanaEndpoint,oldBundle:cachedOldBundle,newBundle:cachedNewBundle,storagePwd});await refresh();return;}catch(e){root.append(note(e?.message||String(e)));}
}
const oldP=input('Текущий пароль');const newP=input('Новый пароль');const go=document.createElement('button');go.className='primary-btn';go.textContent='Продолжить смену ключей';const abort=document.createElement('button');abort.className='secondary-btn';abort.textContent='Прервать смену ключей';const err=document.createElement('div');err.className='meta-muted';
go.addEventListener('click',async()=>{go.disabled=true;try{cachedOldBundle=await derive(oldP.el.value);cachedNewBundle=await derive(newP.el.value);await client.rotatePda({login,solanaEndpoint,oldBundle:cachedOldBundle,newBundle:cachedNewBundle,storagePwd});await refresh();}catch(e){err.textContent=e?.message||String(e);go.disabled=false;}});abort.addEventListener('click',async()=>{await client.abort();await refresh();});setRoot(statusCard(s),note('Процедура была перезапущена на другом этапе. Введите старый и новый пароль, чтобы продолжить автоматическую смену ключей в Solana.'),oldP.wrap,newP.wrap,go,abort,err);
} }
function pollView(s){setRoot(statusCard(s),note(s.rotationStatus==='REBUILDING_SERVER'?'Сервер перестраивает текущую рабочую историю по новому fork.':'Ожидаем подтверждение нового состояния PDA в Solana.'));timer=setTimeout(()=>void refresh(),POLL_MS);} function pollView(s){setRoot(statusCard(s),note(s.rotationStatus==='REBUILDING_SERVER'?'Сервер перестраивает текущую рабочую историю по новому fork.':'Ожидаем подтверждение нового состояния PDA в Solana.'));timer=setTimeout(()=>void refresh(),POLL_MS);}
@@ -65,7 +69,7 @@ export function render({navigate,chrome}){
const oldP=cachedOldBundle?null:input('Старый пароль'); const oldP=cachedOldBundle?null:input('Старый пароль');
const newP=cachedNewBundle?null:input('Новый пароль'); const newP=cachedNewBundle?null:input('Новый пароль');
const info=note('После смены blockchain key меняется и Solana-кошелёк. На этом шаге можно перевести весь доступный SOL со старого кошелька на новый за вычетом сетевой комиссии.'); const info=note('После смены blockchain key меняется и Solana-кошелёк. На этом шаге можно перевести весь доступный SOL со старого кошелька на новый за вычетом сетевой комиссии.');
const warning=note('Сейчас автоматически переносится только SOL. Миграцию AR/Turbo при смене blockchain key нужно доработать отдельно.'); const warning=note('Автоматически переносится только SOL. Другие активы и средства автоматически не переносятся; при необходимости переведите их со старых адресов вручную.');
const details=document.createElement('div');details.className='card stack';details.innerHTML='<span class="meta-muted">Проверьте старый и новый кошельки.</span>'; const details=document.createElement('div');details.className='card stack';details.innerHTML='<span class="meta-muted">Проверьте старый и новый кошельки.</span>';
const prepare=document.createElement('button');prepare.className='secondary-btn';prepare.type='button';prepare.textContent='Проверить кошельки'; const prepare=document.createElement('button');prepare.className='secondary-btn';prepare.type='button';prepare.textContent='Проверить кошельки';
const transfer=document.createElement('button');transfer.className='primary-btn';transfer.type='button';transfer.textContent='Перевести SOL и продолжить';transfer.disabled=true; const transfer=document.createElement('button');transfer.className='primary-btn';transfer.type='button';transfer.textContent='Перевести SOL и продолжить';transfer.disabled=true;
@@ -101,12 +105,12 @@ export function render({navigate,chrome}){
const result=await transferAllSol({endpoint:solanaEndpoint,fromKeypair:oldWallet.keypair,toAddress:newWallet.address}); const result=await transferAllSol({endpoint:solanaEndpoint,fromKeypair:oldWallet.keypair,toAddress:newWallet.address});
details.insertAdjacentHTML('beforeend',`<span class="meta-muted">${result.skipped?'Перевод не потребовался.':`Переведено ${h(formatSol(Number(result.lamports)/1_000_000_000,9))} SOL. Tx: ${h(result.signature)}`}</span>`); details.insertAdjacentHTML('beforeend',`<span class="meta-muted">${result.skipped?'Перевод не потребовался.':`Переведено ${h(formatSol(Number(result.lamports)/1_000_000_000,9))} SOL. Tx: ${h(result.signature)}`}</span>`);
} }
const next=await client.continuePlaceholder(); const next=await client.continueRotation({walletMigrationStatus:'COMPLETE'});
if(String(next?.rotationStatus||'')==='COMPLETE'){navigate('my-blockchain-view');return;} if(String(next?.rotationStatus||'')==='COMPLETE'){navigate('my-blockchain-view');return;}
await refresh(); await refresh();
}catch(e){err.textContent=e?.message||String(e);transfer.disabled=false;prepare.disabled=false;skip.disabled=false;}}); }catch(e){err.textContent=e?.message||String(e);transfer.disabled=false;prepare.disabled=false;skip.disabled=false;}});
skip.addEventListener('click',async()=>{skip.disabled=true;transfer.disabled=true;prepare.disabled=true;err.textContent='';try{ skip.addEventListener('click',async()=>{skip.disabled=true;transfer.disabled=true;prepare.disabled=true;err.textContent='';try{
const next=await client.continuePlaceholder(); const next=await client.continueRotation({walletMigrationStatus:'SKIPPED'});
if(String(next?.rotationStatus||'')==='COMPLETE'){navigate('my-blockchain-view');return;} if(String(next?.rotationStatus||'')==='COMPLETE'){navigate('my-blockchain-view');return;}
await refresh(); await refresh();
}catch(e){err.textContent=e?.message||String(e);skip.disabled=false;transfer.disabled=!oldWallet;prepare.disabled=false;}}); }catch(e){err.textContent=e?.message||String(e);skip.disabled=false;transfer.disabled=!oldWallet;prepare.disabled=false;}});
@@ -115,8 +119,53 @@ export function render({navigate,chrome}){
if(cachedOldBundle&&cachedNewBundle)void prepareWallets().catch(e=>{err.textContent=e?.message||String(e);}); if(cachedOldBundle&&cachedNewBundle)void prepareWallets().catch(e=>{err.textContent=e?.message||String(e);});
} }
function placeholderView(s){const text='Перешифрование старых личных сообщений новым client key пока не реализовано. Этот этап сейчас будет отмечен как NOT_IMPLEMENTED и пропущен.';const go=document.createElement('button');go.className='primary-btn';go.textContent='Продолжить';go.addEventListener('click',async()=>{go.disabled=true;try{const next=await client.continuePlaceholder();if(String(next?.rotationStatus||'')==='COMPLETE'){navigate('my-blockchain-view');return;}await refresh();}catch(e){go.disabled=false;root.append(note(e?.message||String(e)));}});setRoot(statusCard(s),note(text),go);} async function renderMessageMigration(s){
const oldP=cachedOldBundle?null:input('Старый пароль');
const newP=cachedNewBundle?null:input('Новый пароль');
const progress=note('Подготовка перешифрования личных сообщений…');
const go=document.createElement('button');go.className='primary-btn';go.type='button';go.textContent='Продолжить перешифрование';
const err=document.createElement('div');err.className='meta-muted';
const resolveBundles=async()=>{
if(!cachedOldBundle){if(!oldP?.el.value)throw new Error('Введите старый пароль');cachedOldBundle=await derive(oldP.el.value);}
if(!cachedNewBundle){if(!newP?.el.value)throw new Error('Введите новый пароль');cachedNewBundle=await derive(newP.el.value);}
if(String(cachedOldBundle?.clientPair?.publicKeyB64||'')!==String(s.oldClientKey||''))throw new Error('Старый пароль выводит другой client key');
if(String(cachedNewBundle?.clientPair?.publicKeyB64||'')!==String(s.newClientKey||''))throw new Error('Новый пароль выводит другой client key');
};
const run=async()=>{
go.disabled=true;err.textContent='';await resolveBundles();
const cutoff=Number(s.updatedAtMs||0);if(!cutoff)throw new Error('Сервер не вернул время начала миграции сообщений');
let processed=0;
const contacts=await authService.listContacts();
const items=Array.isArray(contacts?.dialogs)?contacts.dialogs:Array.isArray(contacts)?contacts:[];
const peers=[...new Set(items.map(x=>String(x?.login||x?.peerLogin||'').trim()).filter(Boolean))];
for(let i=0;i<peers.length;i++){
const peer=peers[i];
while(true){
progress.textContent=`Перешифрование сообщений: ${processed}. Диалог ${i+1}/${peers.length}: ${peer}`;
const page=await authService.getDirectMessages({peerLogin:peer,limit:100,reencryptedBeforeMs:cutoff});
const messages=Array.isArray(page?.messages)?page.messages:[];
if(messages.length===0)break;
for(const m of messages){
const blobB64=await authService.buildReencryptedLocalDm({
blobB64:m.blobB64,login,
oldClientPrivatePkcs8B64:cachedOldBundle.clientPair.privatePkcs8B64,
newClientPrivatePkcs8B64:cachedNewBundle.clientPair.privatePkcs8B64,
reencryptedAtMs:cutoff,
});
await authService.reencryptDirectMessage({blobB64});processed++;
progress.textContent=`Перешифровано сообщений: ${processed}. Диалог ${i+1}/${peers.length}: ${peer}`;
}
}
}
const next=await client.continueRotation({});
if(String(next?.rotationStatus||'')==='COMPLETE'){navigate('my-blockchain-view');return;}
await refresh();
};
go.addEventListener('click',()=>void run().catch(e=>{err.textContent=e?.message||String(e);go.disabled=false;}));
const nodes=[statusCard(s),note('Локальные входящие и исходящие копии будут приведены к новому client key. Клиент сначала пробует старый ключ, а для сообщений, уже пришедших после смены PDA, — новый. На сервер собеседника повторная отправка не выполняется.'),progress];if(oldP)nodes.push(oldP.wrap);if(newP)nodes.push(newP.wrap);nodes.push(go,err);setRoot(...nodes);
if(cachedOldBundle&&cachedNewBundle)void run().catch(e=>{err.textContent=e?.message||String(e);go.disabled=false;});
}
async function refresh(){if(disposed)return;if(timer){clearTimeout(timer);timer=null;}try{const s=await client.status();const st=String(s.rotationStatus||'NONE');if(st==='NONE'){await renderNone();return;}if(st==='COPYING_CHAIN'){if(cachedNewBundle)await runCopy(s);else await askNewPasswordAndCopy(s);return;}if(st==='CHAIN_READY'){await renderChainReady(s);return;}if(['ROTATING_PDA','PDA_ROTATED','REBUILDING_SERVER'].includes(st)){pollView(s);return;}if(st==='WALLET_MIGRATION'){await renderWalletMigration(s);return;}if(st==='MESSAGE_MIGRATION'){placeholderView(s);return;}if(st==='FINALIZING'){const next=await client.continuePlaceholder();if(String(next?.rotationStatus||'')==='COMPLETE'){navigate('my-blockchain-view');return;}await refresh();return;}if(st==='COMPLETE'){setRoot(note('Смена ключей завершена.'));return;}setRoot(note(`Неизвестное состояние ротации: ${st}`));}catch(e){setRoot(note(`Не удалось прочитать состояние смены ключей: ${e?.message||e}`));}} async function refresh(){if(disposed)return;if(timer){clearTimeout(timer);timer=null;}try{const s=await client.status();const st=String(s.rotationStatus||'NONE');if(st==='NONE'){await renderNone();return;}if(st==='COPYING_CHAIN'){if(cachedNewBundle)await runCopy(s);else await askNewPasswordAndCopy(s);return;}if(st==='CHAIN_READY'){await renderChainReady(s);return;}if(['ROTATING_PDA','PDA_ROTATED','REBUILDING_SERVER'].includes(st)){pollView(s);return;}if(st==='WALLET_MIGRATION'){await renderWalletMigration(s);return;}if(st==='MESSAGE_MIGRATION'){await renderMessageMigration(s);return;}if(st==='FINALIZING'){const next=await client.continueRotation({});if(String(next?.rotationStatus||'')==='COMPLETE'){navigate('my-blockchain-view');return;}await refresh();return;}if(st==='COMPLETE'){setRoot(note('Смена ключей завершена.'));return;}setRoot(note(`Неизвестное состояние ротации: ${st}`));}catch(e){setRoot(note(`Не удалось прочитать состояние смены ключей: ${e?.message||e}`));}}
void refresh();screen.cleanup=()=>{disposed=true;if(timer)clearTimeout(timer);};return screen; void refresh();screen.cleanup=()=>{disposed=true;if(timer)clearTimeout(timer);};return screen;
} }
+17 -2
View File
@@ -31,6 +31,8 @@ export function render({ navigate, route, chrome }) {
const initialKind = String(route?.params?.kind || '').trim(); const initialKind = String(route?.params?.kind || '').trim();
let activeKind = initialKind; let activeKind = initialKind;
const isFriendsScreen = initialKind === 'friends' || initialKind === 'close_friends'; const isFriendsScreen = initialKind === 'friends' || initialKind === 'close_friends';
const isChannelsScreen = initialKind === 'channels_owned' || initialKind === 'channels_following';
let includeDeleted = false;
const screen = document.createElement('section'); const screen = document.createElement('section');
screen.className = 'stack'; screen.className = 'stack';
@@ -45,6 +47,12 @@ export function render({ navigate, route, chrome }) {
back: { label: '←', onClick: () => navigateBack() }, back: { label: '←', onClick: () => navigateBack() },
})); }));
if (isChannelsScreen) {
const filter = document.createElement('label');
filter.className = 'profile-list-deleted-filter';
filter.innerHTML = '<input type="checkbox" id="profile-list-show-deleted"> <span>Показать удалённые</span>';
screen.append(filter);
}
if (isFriendsScreen) { if (isFriendsScreen) {
const tabs = document.createElement('div'); const tabs = document.createElement('div');
tabs.innerHTML = friendTabsHtml(activeKind); tabs.innerHTML = friendTabsHtml(activeKind);
@@ -90,7 +98,7 @@ export function render({ navigate, route, chrome }) {
body.replaceChildren(); body.replaceChildren();
try { try {
if (kind === 'channels_owned' || kind === 'channels_following') { if (kind === 'channels_owned' || kind === 'channels_following') {
const payload = await authService.listUserProfileChannels(login, kind === 'channels_owned' ? 'owned' : 'following', 200, 0); const payload = await authService.listUserProfileChannels(login, kind === 'channels_owned' ? 'owned' : 'following', 200, 0, includeDeleted);
if (generation !== loadGeneration) return; if (generation !== loadGeneration) return;
const rows = Array.isArray(payload?.channels) ? payload.channels : []; const rows = Array.isArray(payload?.channels) ? payload.channels : [];
rows.forEach((row) => { rows.forEach((row) => {
@@ -100,7 +108,7 @@ export function render({ navigate, route, chrome }) {
el.append(renderUserAvatar({ login: row.ownerLogin, firstName: row.displayName, lastName: '', avatar: parseAvatar(row.avatarAr), size: 'md' })); el.append(renderUserAvatar({ login: row.ownerLogin, firstName: row.displayName, lastName: '', avatar: parseAvatar(row.avatarAr), size: 'md' }));
const t = document.createElement('div'); const t = document.createElement('div');
t.className = 'profile-list-row-text'; t.className = 'profile-list-row-text';
t.innerHTML = `<b>${String(row.displayName || row.slug || '')}</b><small>${String(row.ownerLogin || '')} / ${String(row.slug || '')}</small>`; t.innerHTML = `<b>${String(row.displayName || row.slug || '')}${row.deleted ? ' · Удалён' : ''}</b><small>${String(row.ownerLogin || '')} / ${String(row.slug || '')}</small>`;
el.append(t); el.append(t);
el.addEventListener('click', () => navigate(`channel/${encodeURIComponent(row.ownerBlockchainName)}/${Number(row.rootBlockNumber || 0)}/${encodeURIComponent(row.rootBlockHashHex || '')}/about`)); el.addEventListener('click', () => navigate(`channel/${encodeURIComponent(row.ownerBlockchainName)}/${Number(row.rootBlockNumber || 0)}/${encodeURIComponent(row.rootBlockHashHex || '')}/about`));
body.append(el); body.append(el);
@@ -121,6 +129,13 @@ export function render({ navigate, route, chrome }) {
} }
} }
if (isChannelsScreen) {
screen.querySelector('#profile-list-show-deleted')?.addEventListener('change', (event) => {
includeDeleted = !!event.currentTarget.checked;
void load(activeKind);
});
}
if (isFriendsScreen) { if (isFriendsScreen) {
screen.addEventListener('click', (event) => { screen.addEventListener('click', (event) => {
const tab = event.target.closest('[data-friend-kind]'); const tab = event.target.closest('[data-friend-kind]');
+119 -10
View File
@@ -62,6 +62,7 @@ const MSG_SUBTYPE_TEXT_EDIT_REPLY = 21;
const MSG_SUBTYPE_TEXT_RATING = 30; const MSG_SUBTYPE_TEXT_RATING = 30;
const MSG_SUBTYPE_TEXT_REPOST = 50; const MSG_SUBTYPE_TEXT_REPOST = 50;
const MSG_SUBTYPE_TEXT_CHANNEL_META = 90; const MSG_SUBTYPE_TEXT_CHANNEL_META = 90;
const MSG_SUBTYPE_TEXT_CHANNEL_DELETE = 92;
const MSG_SUBTYPE_TEXT_ENTRYPOINT = 100; const MSG_SUBTYPE_TEXT_ENTRYPOINT = 100;
const MSG_SUBTYPE_TEXT_EXERCISE = 110; const MSG_SUBTYPE_TEXT_EXERCISE = 110;
const MSG_SUBTYPE_TEXT_SERVICE = 120; const MSG_SUBTYPE_TEXT_SERVICE = 120;
@@ -1453,6 +1454,12 @@ export class AuthService {
if (response.status !== 200) throw opError('CloseActiveSession', response); if (response.status !== 200) throw opError('CloseActiveSession', response);
} }
async closeOtherSessions() {
const response = await this.ws.request('CloseOtherSessions', {});
if (response.status !== 200) throw opError('CloseOtherSessions', response);
return response.payload || {};
}
async getTrustedDeviceLoginSettings() { async getTrustedDeviceLoginSettings() {
const response = await this.ws.request('GetTrustedDeviceLoginSettings', {}); const response = await this.ws.request('GetTrustedDeviceLoginSettings', {});
if (response.status !== 200) throw opError('GetTrustedDeviceLoginSettings', response); if (response.status !== 200) throw opError('GetTrustedDeviceLoginSettings', response);
@@ -2489,6 +2496,7 @@ export class AuthService {
MSG_SUBTYPE_TEXT_EDIT_POST, MSG_SUBTYPE_TEXT_EDIT_POST,
MSG_SUBTYPE_TEXT_REPOST, MSG_SUBTYPE_TEXT_REPOST,
MSG_SUBTYPE_TEXT_CHANNEL_META, MSG_SUBTYPE_TEXT_CHANNEL_META,
MSG_SUBTYPE_TEXT_CHANNEL_DELETE,
MSG_SUBTYPE_TEXT_ENTRYPOINT, MSG_SUBTYPE_TEXT_ENTRYPOINT,
MSG_SUBTYPE_TEXT_EXERCISE, MSG_SUBTYPE_TEXT_EXERCISE,
MSG_SUBTYPE_TEXT_SERVICE, MSG_SUBTYPE_TEXT_SERVICE,
@@ -2631,6 +2639,40 @@ export class AuthService {
} }
async addBlockChannelDelete({ login, channel, storagePwd }) {
const cleanLogin = (login || '').trim();
if (!cleanLogin) throw new Error('Missing login');
const selector = channel || {};
const owner = String(selector?.ownerBlockchainName || '').trim();
const root = Number(selector?.channelRootBlockNumber);
const key = `channel-line:${cleanLogin}:${owner}:${root}`;
return this.runLineWriteLocked(key, async () => {
const user = await this.ensureChainInitializedForLineOps(cleanLogin, storagePwd);
const blockchainName = String(user?.blockchainName || `${cleanLogin}-${BCH_SUFFIX}`).trim();
const tail = await this.resolveChannelLineTail({ login: cleanLogin, blockchainName, channel: selector });
const bodyBytes = makeTextLineBodyBytesAllowEmpty({
lineCode: tail.lineCode,
prevLineNumber: tail.prevLineNumber,
prevLineHashHex: tail.prevLineHashHex,
thisLineNumber: tail.thisLineNumber,
text: '',
});
const payload = await this.addBlockSigned({
login: cleanLogin,
storagePwd,
msgType: MSG_TYPE_TEXT,
msgSubType: MSG_SUBTYPE_TEXT_CHANNEL_DELETE,
msgVersion: 1,
bodyBytes,
channelSlug: tail.channelSlug,
});
this.rememberChannelLineTail(blockchainName, tail.lineCode, payload, tail.thisLineNumber);
return { ...payload, channel: { ownerBlockchainName: tail.ownerBlockchainName, channelRootBlockNumber: tail.lineCode, channelRootBlockHash: tail.rootHashHex } };
});
}
onEvent(op, handler) { onEvent(op, handler) {
if (!op || typeof handler !== 'function') return () => {}; if (!op || typeof handler !== 'function') return () => {};
if (!this.eventListeners.has(op)) { if (!this.eventListeners.has(op)) {
@@ -2688,18 +2730,22 @@ export class AuthService {
revisionTimeMs = 0, revisionTimeMs = 0,
reencryptedAtMs = 0, reencryptedAtMs = 0,
bodyBytes = new Uint8Array(0), bodyBytes = new Uint8Array(0),
signerPrivatePkcs8B64 = '',
}) { }) {
const cleanSignerLogin = this.normalizeDmLogin(signerLogin); const cleanSignerLogin = this.normalizeDmLogin(signerLogin);
const cleanFromLogin = this.normalizeDmLogin(fromLogin); const cleanFromLogin = this.normalizeDmLogin(fromLogin);
const cleanToLogin = this.normalizeDmLogin(toLogin); const cleanToLogin = this.normalizeDmLogin(toLogin);
if (!cleanSignerLogin || !cleanFromLogin || !cleanToLogin) throw new Error('Не передан signerLogin/fromLogin/toLogin'); if (!cleanSignerLogin || !cleanFromLogin || !cleanToLogin) throw new Error('Не передан signerLogin/fromLogin/toLogin');
if (!storagePwd) throw new Error('Не передан storagePwd для подписи'); if (!storagePwd && !String(signerPrivatePkcs8B64 || '').trim()) throw new Error('Не передан ключ для подписи');
if (!(bodyBytes instanceof Uint8Array) || bodyBytes.length > DM_MAX_ENCRYPTED_BODY_BYTES) { if (!(bodyBytes instanceof Uint8Array) || bodyBytes.length > DM_MAX_ENCRYPTED_BODY_BYTES) {
throw new Error(`body должен быть 0..${DM_MAX_ENCRYPTED_BODY_BYTES} байт`); throw new Error(`body должен быть 0..${DM_MAX_ENCRYPTED_BODY_BYTES} байт`);
} }
const secrets = await loadEncryptedUserSecrets(cleanSignerLogin, storagePwd); let clientPriv = String(signerPrivatePkcs8B64 || '').trim();
const clientPriv = secrets?.clientKey || secrets?.clientKey; if (!clientPriv) {
const secrets = await loadEncryptedUserSecrets(cleanSignerLogin, storagePwd);
clientPriv = String(secrets?.clientKey || '').trim();
}
if (!clientPriv) throw new Error('Не найден приватный clientKey'); if (!clientPriv) throw new Error('Не найден приватный clientKey');
const privateKey = await importPkcs8Ed25519(clientPriv); const privateKey = await importPkcs8Ed25519(clientPriv);
@@ -2736,13 +2782,13 @@ export class AuthService {
return classifyDmDecryptFailure(error); return classifyDmDecryptFailure(error);
} }
async decryptSignedMessageContent({ parsed, blobB64 = '', login, storagePwd }) { async decryptSignedMessageContent({ parsed, blobB64 = '', login, storagePwd, clientPrivatePkcs8B64 = '' }) {
const parsedBlock = parsed || this.parseSignedMessageBlob(blobB64); const parsedBlock = parsed || this.parseSignedMessageBlob(blobB64);
const messageType = Number(parsedBlock?.messageType || 0); const messageType = Number(parsedBlock?.messageType || 0);
if (messageType !== DM_TYPE_INCOMING && messageType !== DM_TYPE_OUTGOING_COPY) { if (messageType !== DM_TYPE_INCOMING && messageType !== DM_TYPE_OUTGOING_COPY) {
return { text: '', plainBytes: new Uint8Array(0) }; return { text: '', plainBytes: new Uint8Array(0) };
} }
if (!storagePwd) throw new Error('Не передан storagePwd для расшифровки'); if (!storagePwd && !String(clientPrivatePkcs8B64 || '').trim()) throw new Error('Не передан ключ для расшифровки');
const cleanLogin = String(login || '').trim(); const cleanLogin = String(login || '').trim();
if (!cleanLogin) throw new Error('Не передан login для расшифровки'); if (!cleanLogin) throw new Error('Не передан login для расшифровки');
@@ -2751,8 +2797,11 @@ export class AuthService {
throw new Error('Неподдерживаемый метод шифрования DM'); throw new Error('Неподдерживаемый метод шифрования DM');
} }
const secrets = await loadEncryptedUserSecrets(cleanLogin, storagePwd); let clientPrivPkcs8 = String(clientPrivatePkcs8B64 || '').trim();
const clientPrivPkcs8 = String(secrets?.clientKey || '').trim(); if (!clientPrivPkcs8) {
const secrets = await loadEncryptedUserSecrets(cleanLogin, storagePwd);
clientPrivPkcs8 = String(secrets?.clientKey || '').trim();
}
if (!clientPrivPkcs8) throw new Error('Не найден приватный clientKey'); if (!clientPrivPkcs8) throw new Error('Не найден приватный clientKey');
const recipientSeed = extractEd25519SeedFromPkcs8B64(clientPrivPkcs8); const recipientSeed = extractEd25519SeedFromPkcs8B64(clientPrivPkcs8);
const recipientX25519Priv = ed25519SeedToX25519Private(recipientSeed); const recipientX25519Priv = ed25519SeedToX25519Private(recipientSeed);
@@ -2970,7 +3019,7 @@ export class AuthService {
}; };
} }
async getDirectMessages({ peerLogin, limit = 50, beforeTimeMs = 0, beforeMessageKey = '' } = {}) { async getDirectMessages({ peerLogin, limit = 50, beforeTimeMs = 0, beforeMessageKey = '', reencryptedBeforeMs = 0 } = {}) {
const payload = { const payload = {
peerLogin: String(peerLogin || '').trim(), peerLogin: String(peerLogin || '').trim(),
limit: Number(limit || 0), limit: Number(limit || 0),
@@ -2982,11 +3031,71 @@ export class AuthService {
if (String(beforeMessageKey || '').trim()) { if (String(beforeMessageKey || '').trim()) {
payload.beforeMessageKey = String(beforeMessageKey || '').trim(); payload.beforeMessageKey = String(beforeMessageKey || '').trim();
} }
if (Number.isFinite(Number(reencryptedBeforeMs)) && Number(reencryptedBeforeMs) > 0) {
payload.reencryptedBeforeMs = Math.trunc(Number(reencryptedBeforeMs));
}
const response = await this.ws.request('GetDirectMessages', payload); const response = await this.ws.request('GetDirectMessages', payload);
if (response.status !== 200) throw opError('GetDirectMessages', response); if (response.status !== 200) throw opError('GetDirectMessages', response);
return response.payload || {}; return response.payload || {};
} }
async reencryptDirectMessage({ blobB64 }) {
const response = await this.ws.request('ReencryptDirectMessage', { blobB64: String(blobB64 || '').trim() });
if (response.status !== 200) throw opError('ReencryptDirectMessage', response);
return response.payload || {};
}
async buildReencryptedLocalDm({ blobB64, login, oldClientPrivatePkcs8B64, newClientPrivatePkcs8B64, reencryptedAtMs }) {
const parsed = this.parseSignedMessageBlob(blobB64);
const messageType = Number(parsed?.messageType || 0);
if (messageType !== DM_TYPE_INCOMING && messageType !== DM_TYPE_OUTGOING_COPY) throw new Error('Можно перешифровать только type=1/2');
const cleanLogin = this.normalizeDmLogin(login);
const owned = messageType === DM_TYPE_INCOMING
? this.normalizeDmLogin(parsed.toLogin) === cleanLogin
: this.normalizeDmLogin(parsed.fromLogin) === cleanLogin;
if (!owned) throw new Error('Сообщение не принадлежит текущему локальному архиву');
let decrypted;
try {
decrypted = await this.decryptSignedMessageContent({
parsed,
login: cleanLogin,
clientPrivatePkcs8B64: oldClientPrivatePkcs8B64,
});
} catch (oldKeyError) {
// Сообщение могло прийти уже после смены PDA и быть зашифровано новым client key.
// В этом случае нормализуем его в текущую эпоху миграции тем же новым ключом.
try {
decrypted = await this.decryptSignedMessageContent({
parsed,
login: cleanLogin,
clientPrivatePkcs8B64: newClientPrivatePkcs8B64,
});
} catch (newKeyError) {
const error = new Error('Не удалось расшифровать сообщение ни старым, ни новым client key');
error.cause = newKeyError;
throw error;
}
}
const newPublicKeyB64 = await publicKeyB64FromPkcs8Ed25519(newClientPrivatePkcs8B64);
const encryptedBody = await buildDmEncryptedBodyBytes({
plainBytes: decrypted.plainBytes,
recipientClientKeyB64: newPublicKeyB64,
});
const block = await this.buildSignedDmBlock({
signerLogin: cleanLogin,
fromLogin: parsed.fromLogin,
toLogin: parsed.toLogin,
timeMs: parsed.timeMs,
nonce: parsed.nonce,
messageType,
revisionTimeMs: parsed.revisionTimeMs,
reencryptedAtMs,
bodyBytes: encryptedBody,
signerPrivatePkcs8B64: newClientPrivatePkcs8B64,
});
return bytesToBase64(block);
}
async ackSessionDelivery(messageKey) { async ackSessionDelivery(messageKey) {
const response = await this.ws.request('AckSessionDelivery', { messageKey }); const response = await this.ws.request('AckSessionDelivery', { messageKey });
if (response.status !== 200) throw opError('AckSessionDelivery', response); if (response.status !== 200) throw opError('AckSessionDelivery', response);
@@ -3087,8 +3196,8 @@ export class AuthService {
return response.payload || {}; return response.payload || {};
} }
async listUserProfileChannels(login, mode, limit = 100, offset = 0) { async listUserProfileChannels(login, mode, limit = 100, offset = 0, includeDeleted = false) {
const response = await this.ws.request('ListUserProfileChannels', { login, mode, limit, offset }); const response = await this.ws.request('ListUserProfileChannels', { login, mode, limit, offset, includeDeleted: !!includeDeleted });
if (response.status !== 200) throw opError('ListUserProfileChannels', response); if (response.status !== 200) throw opError('ListUserProfileChannels', response);
return response.payload || {}; return response.payload || {};
} }
+1 -2
View File
@@ -81,7 +81,7 @@ export class KeyRotationClient {
async status() { return assertOk(await this.auth.ws.request('KeyRotationStatus', {}), 'KeyRotationStatus'); } async status() { return assertOk(await this.auth.ws.request('KeyRotationStatus', {}), 'KeyRotationStatus'); }
async start(args) { return assertOk(await this.auth.ws.request('KeyRotationStart', args), 'KeyRotationStart'); } async start(args) { return assertOk(await this.auth.ws.request('KeyRotationStart', args), 'KeyRotationStart'); }
async abort() { return assertOk(await this.auth.ws.request('KeyRotationAbort', {}), 'KeyRotationAbort'); } async abort() { return assertOk(await this.auth.ws.request('KeyRotationAbort', {}), 'KeyRotationAbort'); }
async continuePlaceholder() { return assertOk(await this.auth.ws.request('KeyRotationContinue', {}), 'KeyRotationContinue'); } async continueRotation(args={}) { return assertOk(await this.auth.ws.request('KeyRotationContinue', args), 'KeyRotationContinue'); }
async finishChain() { return assertOk(await this.auth.ws.request('KeyRotationFinishChain', {}), 'KeyRotationFinishChain'); } async finishChain() { return assertOk(await this.auth.ws.request('KeyRotationFinishChain', {}), 'KeyRotationFinishChain'); }
async notifyPdaRotation(signature) { return assertOk(await this.auth.ws.request('KeyRotationRotatePda', { pdaRotationSignature: signature }), 'KeyRotationRotatePda'); } async notifyPdaRotation(signature) { return assertOk(await this.auth.ws.request('KeyRotationRotatePda', { pdaRotationSignature: signature }), 'KeyRotationRotatePda'); }
async getMyBlockchain({ beforeBlock=null, limit=50, includeBlockBytes=false }={}) { async getMyBlockchain({ beforeBlock=null, limit=50, includeBlockBytes=false }={}) {
@@ -185,7 +185,6 @@ export class KeyRotationClient {
if(storagePwd) { if(storagePwd) {
await updateEncryptedUserSecrets(login, storagePwd, (current)=>({ await updateEncryptedUserSecrets(login, storagePwd, (current)=>({
...(current||{}), ...(current||{}),
rootKey:newBundle.rootPair.privatePkcs8B64,
blockchainKey:newBundle.blockchainPair.privatePkcs8B64, blockchainKey:newBundle.blockchainPair.privatePkcs8B64,
clientKey:newBundle.clientPair.privatePkcs8B64, clientKey:newBundle.clientPair.privatePkcs8B64,
})); }));