Compare commits

..
32 Commits
Author SHA256 Message Date
AidarKC bd52a23bec Ограничить домены email бесплатной регистрации 2026-11-05 03:27:52 +03:00
AidarKC e84ab41fe6 Упростить полноэкранную регистрацию 2026-11-05 00:07:52 +03:00
AidarKC 41d5e79f83 Добавить трёхшаговый UI регистрации 2026-11-05 00:04:05 +03:00
AidarKC c13734cbc9 Добавить email-подтверждение бесплатной регистрации 2026-11-04 13:39:07 +03:00
AidarKC e78402c860 Документировать создание HEADER после регистрации 2026-10-29 13:24:13 +03:00
AidarKC 2ce80eeaef Добавить создание HEADER-блока после регистрации 2026-10-29 13:24:05 +03:00
AidarKC 551bdc2d65 Документировать Base64 ключ blockchain state 2026-10-29 13:12:30 +03:00
AidarKC f507bdb343 Нормализовать ключ free-блокчейна в Base64 2026-10-29 13:11:52 +03:00
AidarKC 395aa62bda Промежуточно: синхронизировать регистр логинов 2026-10-29 13:10:12 +03:00
AidarKC d2b2876a79 Обновить публичные ссылки и аватары каналов 2026-10-28 20:03:34 +03:00
AidarKC 8bb7d39c76 Недоделано: канонизировать login в заголовке блокчейна 2026-10-28 20:02:38 +03:00
AidarKC e296217f21 Учитывать регистр логина в состоянии блокчейна 2026-10-28 19:21:33 +03:00
AidarKC c0257f4be2 Восстанавливать blockchain state free-пользователей 2026-10-28 19:16:01 +03:00
AidarKC 7b88b61b22 Смена пароля работает: восстановить ротацию ключей 2026-10-28 19:00:46 +03:00
AidarKC ab61787ee7 Исправить чистый старт PostgreSQL и Solana sync 2026-10-28 12:51:43 +03:00
AidarKC 219a65ae27 Очистить временный PDA-очиститель и обновить T3 логин 2026-10-28 12:45:35 +03:00
AidarKC 94d4665185 Исправить регистрацию free-пользователей без учёта регистра
НЕ ПРОВЕРЕНО: учтены логины с большими и маленькими буквами.

Добавлен временный devnet-смарт-контракт для очистки тестового аккаунта от старых логинов; после сброса его необходимо удалить и восстановить штатный контракт.
2026-10-28 12:19:19 +03:00
AidarKC ce97171d5a Унифицировать платный статус регистрации 2026-10-28 11:28:59 +03:00
AidarKC a22f590395 апдейт по регистрации 2026-10-28 11:27:42 +03:00
AidarKC a520c5c5e1 Регистрация: бесплатная регистрация работает 2026-10-24 16:17:34 +03:00
AidarKC cab26bbf41 Регистрация V2: не проверено end-to-end 2026-10-23 19:21:52 +03:00
AidarKC 6c8159c5f7 Доработка логина и темы 2026-10-23 12:18:27 +03:00
AidarKC df0e9cef9b Ещё доделали UI, Solana gateway, связи и push-уведомления 2026-10-21 11:49:31 +03:00
AidarKC 7a6ab3b35a Поправил пуши для личных сообщений 2026-10-21 11:47:27 +03:00
AidarKC aa5addb5d9 Solana RPC gateway для клиента и сервера 2026-10-18 00:03:46 +03:00
AidarKC b67d06ce43 Связи: сохранять переключатель при обновлении шапки 2026-10-17 22:59:43 +03:00
AidarKC 8d9a580f50 Связи: перенести переключатель версии в шапку 2026-10-17 22:57:10 +03:00
AidarKC 45eb77f431 Связи: исправить импорты прежней карты 2026-10-17 22:54:04 +03:00
AidarKC 2be6fe3ff9 Связи: переключение между прежней и новой картой 2026-10-17 22:46:52 +03:00
AidarKC a380900ec8 Merge remote-tracking branch 'origin/ui-polish' into Доработка-ЮАЙ-до-МВП
# Conflicts:
#	VERSION.properties
2026-10-17 22:43:54 +03:00
AidarKC e77aaa3675 Убрал лишние скетчи из проекта 2026-10-15 18:04:54 +03:00
AidarKC d25894149b Скетчи не по делу: ручной монитор и тесты потенциометра 2026-10-13 19:04:15 +03:00
225 changed files with 13463 additions and 1915 deletions
+10
View File
@@ -116,3 +116,13 @@ SHiNE-bundle-*.zip
# Рабочие бэкапы/превью-ассеты UI — не для репозитория
*.bak.png
shine-UI/assets/navbar_preview.png
# Private local configuration: keep on disk, never push to GitHub
/SHiNE-server/src/main/resources/application.properties
/application.properties
/deploy/backup/scheme/
/shine-solana/shine/create-SHiNE-DAO/dao.config.mainnet.env
**/.env
**/.env.*
!**/.env.example
!**/.env.sample
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODE="${1:-potentiometer-adc-test}"
PORT="${PORT:-}"
case "$MODE" in
potentiometer-adc-test)
SKETCH_DIR="$ROOT_DIR/test_sketches/potentiometer_adc_test"
BUILD_DIR="$ROOT_DIR/.arduino-build/build-potentiometer-adc-test"
;;
buzzer-gpio6-test)
SKETCH_DIR="$ROOT_DIR/test_sketches/buzzer_gpio6_test"
BUILD_DIR="$ROOT_DIR/.arduino-build/build-buzzer-gpio6-test"
;;
*)
echo "Unknown mode: $MODE" >&2
echo "Known modes: potentiometer-adc-test, buzzer-gpio6-test" >&2
exit 2
;;
esac
if [[ -z "$PORT" ]]; then
PORT="$(arduino-cli board list | awk '/ttyACM|ttyUSB/ {print $1; exit}')"
fi
if [[ -z "$PORT" ]]; then
echo "No serial port found. Set PORT=/dev/ttyACM0 explicitly." >&2
exit 1
fi
FQBN="esp32:esp32:esp32s3:USBMode=hwcdc,CDCOnBoot=cdc,UploadSpeed=921600,CPUFreq=240,FlashMode=dio,FlashSize=16M,PartitionScheme=app3M_fat9M_16MB,PSRAM=opi"
echo "== Mode: $MODE"
echo "== Sketch: $SKETCH_DIR"
echo "== Port: $PORT"
echo "== FQBN: $FQBN"
arduino-cli compile \
--fqbn "$FQBN" \
--build-path "$BUILD_DIR" \
"$SKETCH_DIR"
arduino-cli upload \
--fqbn "$FQBN" \
-p "$PORT" \
--input-dir "$BUILD_DIR" \
"$SKETCH_DIR"
echo
echo "== Done."
@@ -0,0 +1,3 @@
# AGENTS
This folder contains a temporary GPIO6 buzzer diagnostic for ESP32-S3-LCD-2. Keep screen/serial strings in English.
@@ -0,0 +1,51 @@
#include <Arduino.h>
// Buzzer module wiring: GND -> GND, VCC -> 3V3, I/O -> P1 IO6 / GPIO6.
static constexpr uint8_t PIN_BUZZER = 6;
static constexpr uint32_t STEP_MS = 1800;
static uint8_t gStep = 0;
static uint32_t gChangedMs = 0;
static void applyStep(uint8_t step) {
ledcDetach(PIN_BUZZER);
pinMode(PIN_BUZZER, OUTPUT);
digitalWrite(PIN_BUZZER, LOW);
delay(80);
switch (step) {
case 0:
pinMode(PIN_BUZZER, OUTPUT);
digitalWrite(PIN_BUZZER, HIGH);
Serial.println("TEST 1: GPIO6 HIGH - active-high module should sound");
break;
case 1:
pinMode(PIN_BUZZER, OUTPUT);
digitalWrite(PIN_BUZZER, LOW);
Serial.println("TEST 2: GPIO6 LOW - active-low module should sound");
break;
case 2:
ledcAttach(PIN_BUZZER, 1800, 8);
ledcWriteTone(PIN_BUZZER, 1800);
ledcWrite(PIN_BUZZER, 180);
Serial.println("TEST 3: GPIO6 PWM 1800 Hz - passive module should sound");
break;
default:
pinMode(PIN_BUZZER, OUTPUT);
digitalWrite(PIN_BUZZER, LOW);
Serial.println("SILENCE");
break;
}
}
void setup() {
Serial.begin(115200);
Serial.println("GPIO6 BUZZER TEST: HIGH, LOW, PWM, SILENCE. Each step lasts 1.8 seconds.");
applyStep(gStep);
gChangedMs = millis();
}
void loop() {
if (millis() - gChangedMs < STEP_MS) return;
gStep = (gStep + 1) % 4;
applyStep(gStep);
gChangedMs = millis();
}
@@ -0,0 +1,17 @@
# AGENTS
## Назначение папки
Эта папка содержит отдельный тестовый Arduino-скетч `potentiometer_adc_test.ino` для Waveshare `ESP32-S3-LCD-2`.
Скетч проверяет переменный резистор на обычных GPIO/ADC, без использования USB `D+ / D-`.
## Обязательная синхронизация
При любом изменении `potentiometer_adc_test.ino` обязательно обновлять рядом лежащий `README.md`.
Если меняются экранные тексты, режимы, пины подключения, правила расчёта, touch-кнопки или serial-команды, описание в `README.md` должно быть обновлено в том же наборе изменений.
## Язык экрана
Экранные строки в скетче оставлять на английском языке.
@@ -0,0 +1,73 @@
# Potentiometer ADC Test for ESP32-S3-LCD-2
Тестовый скетч для Waveshare `ESP32-S3-LCD-2`.
Назначение: проверить переменный резистор `RP 6045-B50K` через обычные GPIO/ADC, без использования USB `D+ / D-`.
## Пины
Используются пины с разъёма `P1` платы:
- `GPIO2 / IO2` — ADC-вход, сюда подключается ползунок потенциометра.
- `GPIO6 / IO6` — DRIVE-выход для грубого 2-проводного режима.
- `3V3` — питание потенциометра для 3-проводного режима, находится на разъёме `P2`.
- `GND` — земля.
Не подавать `5V` на `GPIO2` или `GPIO6`: GPIO ESP32-S3 не являются 5V tolerant.
## Режимы
Переключение:
- touch-кнопка `3-WIRE`;
- touch-кнопка `2-WIRE`;
- серийная команда `m`;
- короткое нажатие `BOOT / GPIO0`.
Сброс min/max:
- touch-кнопка `RESET`;
- серийная команда `r`.
## 3-Wire Mode
Правильное подключение:
- один край потенциометра -> `3V3`;
- второй край потенциометра -> `GND`;
- средний ползунок -> `GPIO2 / IO2`.
Скетч показывает напряжение на ползунке, raw ADC, абсолютное положение от `0..3.3V`, калиброванное положение между найденными min/max и примерное сопротивление участка `0..50 kΩ`.
## 2-Wire Mode
Грубое подключение:
- один край потенциометра -> `GPIO6 / IO6`;
- средний ползунок -> `GPIO2 / IO2`;
- второй край не подключать.
`GPIO6` выдаёт `HIGH`, `GPIO2` читается как ADC с внутренней подтяжкой вниз. Такой режим показывает движение ползунка, но не даёт точного сопротивления: внутренняя подтяжка ESP32 имеет большой разброс.
## Экранные данные
На экране выводятся:
- режим и схема пинов;
- raw ADC и millivolts;
- абсолютный процент от `0..3300 mV`;
- калиброванный процент по найденному min/max;
- min/max/span;
- EMA-сглаживание;
- примерная оценка сопротивления;
- статус `OPEN/LOW/MID/HIGH/SATURATED/NO SPAN`;
- координаты последнего touch;
- serial-подсказка.
## Сборка
Из папки `main-device`:
```bash
./burn.sh potentiometer-adc-test
```
@@ -0,0 +1,348 @@
#include <Arduino.h>
#include <Arduino_GFX_Library.h>
#include <Wire.h>
#include <bsp_cst816.h>
#define PIN_LCD_SCLK 39
#define PIN_LCD_MOSI 38
#define PIN_LCD_MISO 40
#define PIN_LCD_DC 42
#define PIN_LCD_RST -1
#define PIN_LCD_CS 45
#define PIN_LCD_BL 1
#define PIN_TP_SDA 48
#define PIN_TP_SCL 47
#define PIN_ADC_WIPER 2
#define PIN_DRIVE_2WIRE 6
#define PIN_BOOT_BUTTON 0
static const uint16_t DISP_W = 320;
static const uint16_t DISP_H = 240;
static const uint32_t ADC_FULL_MV = 3300;
static const float POT_OHMS = 50000.0f;
static const float ROUGH_PULLDOWN_OHMS = 45000.0f;
static const uint16_t C_BG = 0x0841;
static const uint16_t C_PANEL = 0x18E3;
static const uint16_t C_CARD = 0x2126;
static const uint16_t C_TEXT = 0xF7BE;
static const uint16_t C_MUTE = 0x8C71;
static const uint16_t C_ACCENT = 0x05DF;
static const uint16_t C_OK = 0x47E8;
static const uint16_t C_WARN = 0xFD20;
static const uint16_t C_BAD = 0xF986;
static const uint16_t C_BORDER = 0x4208;
struct Rect {
int16_t x;
int16_t y;
int16_t w;
int16_t h;
};
enum class Mode : uint8_t {
ThreeWire,
TwoWire,
};
struct Sample {
uint16_t raw;
uint32_t mv;
uint16_t rawMinBurst;
uint16_t rawMaxBurst;
};
Arduino_DataBus *bus = new Arduino_ESP32SPI(
PIN_LCD_DC, PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_MOSI, PIN_LCD_MISO);
Arduino_GFX *gfx = new Arduino_ST7789(
bus, PIN_LCD_RST, 1, true, 240, 320);
static const Rect BTN_3WIRE = {10, 38, 94, 30};
static const Rect BTN_2WIRE = {113, 38, 94, 30};
static const Rect BTN_RESET = {216, 38, 94, 30};
static Mode gMode = Mode::ThreeWire;
static uint32_t gLastUiMs = 0;
static uint32_t gLastSerialMs = 0;
static uint32_t gMinMv = 0xFFFFFFFF;
static uint32_t gMaxMv = 0;
static float gEmaMv = 0.0f;
static bool gHasEma = false;
static bool gTouchOk = false;
static uint16_t gLastTouchX = 0;
static uint16_t gLastTouchY = 0;
static bool gBootWasDown = false;
static uint32_t gBootLastChangeMs = 0;
static void drawText(int16_t x, int16_t y, const char *text, uint16_t color, uint8_t size = 1) {
gfx->setTextSize(size);
gfx->setTextColor(color);
gfx->setCursor(x, y);
gfx->print(text);
}
static void drawButton(const Rect &r, const char *label, bool active) {
uint16_t fill = active ? C_ACCENT : C_CARD;
uint16_t text = active ? C_BG : C_TEXT;
gfx->fillRoundRect(r.x, r.y, r.w, r.h, 6, fill);
gfx->drawRoundRect(r.x, r.y, r.w, r.h, 6, active ? C_ACCENT : C_BORDER);
int16_t tx = r.x + 10;
int16_t ty = r.y + 10;
drawText(tx, ty, label, text, 1);
}
static bool contains(const Rect &r, uint16_t x, uint16_t y) {
return x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h;
}
static const char *modeName() {
return gMode == Mode::ThreeWire ? "3-WIRE" : "2-WIRE";
}
static void resetRange() {
gMinMv = 0xFFFFFFFF;
gMaxMv = 0;
gHasEma = false;
}
static void configurePins() {
pinMode(PIN_ADC_WIPER, INPUT);
analogReadResolution(12);
analogSetPinAttenuation(PIN_ADC_WIPER, ADC_11db);
if (gMode == Mode::TwoWire) {
pinMode(PIN_DRIVE_2WIRE, OUTPUT);
digitalWrite(PIN_DRIVE_2WIRE, HIGH);
pinMode(PIN_ADC_WIPER, INPUT_PULLDOWN);
} else {
pinMode(PIN_DRIVE_2WIRE, INPUT);
pinMode(PIN_ADC_WIPER, INPUT);
}
}
static void setMode(Mode mode) {
if (gMode == mode) return;
gMode = mode;
configurePins();
resetRange();
}
static Sample readSample() {
const uint8_t count = 32;
uint32_t rawSum = 0;
uint32_t mvSum = 0;
uint16_t rawMin = 4095;
uint16_t rawMax = 0;
for (uint8_t i = 0; i < count; i++) {
uint16_t raw = analogRead(PIN_ADC_WIPER);
uint32_t mv = analogReadMilliVolts(PIN_ADC_WIPER);
rawSum += raw;
mvSum += mv;
if (raw < rawMin) rawMin = raw;
if (raw > rawMax) rawMax = raw;
delayMicroseconds(250);
}
Sample s;
s.raw = rawSum / count;
s.mv = mvSum / count;
s.rawMinBurst = rawMin;
s.rawMaxBurst = rawMax;
return s;
}
static uint8_t percentFromMv(uint32_t mv) {
if (mv >= ADC_FULL_MV) return 100;
return (uint8_t)((mv * 100UL + ADC_FULL_MV / 2) / ADC_FULL_MV);
}
static uint8_t calibratedPercent(uint32_t mv, uint32_t span) {
if (span < 10 || gMinMv == 0xFFFFFFFF || mv <= gMinMv) return 0;
uint32_t pct = ((mv - gMinMv) * 100UL + span / 2) / span;
return (uint8_t)min<uint32_t>(pct, 100);
}
static const char *statusText(uint32_t mv, uint32_t span, uint8_t pctAbs) {
if (mv < 30) return "OPEN/GND";
if (mv > 3250) return "SATURATED";
if (span < 20) return "NO SPAN";
if (pctAbs < 15) return "LOW";
if (pctAbs > 85) return "HIGH";
return "MID";
}
static float estimateOhms(uint32_t mv) {
if (gMode == Mode::ThreeWire) {
return POT_OHMS * ((float)percentFromMv(mv) / 100.0f);
}
if (mv < 5) return -1.0f;
if (mv >= ADC_FULL_MV) return 0.0f;
return ROUGH_PULLDOWN_OHMS * ((float)ADC_FULL_MV / (float)mv - 1.0f);
}
static void drawStaticUi() {
gfx->fillScreen(C_BG);
drawText(10, 8, "POT ADC TEST", C_TEXT, 2);
drawText(210, 12, "ESP32-S3-LCD-2", C_MUTE, 1);
drawButton(BTN_3WIRE, "3-WIRE", gMode == Mode::ThreeWire);
drawButton(BTN_2WIRE, "2-WIRE", gMode == Mode::TwoWire);
drawButton(BTN_RESET, "RESET", false);
gfx->drawRoundRect(8, 76, 304, 64, 8, C_BORDER);
gfx->drawRoundRect(8, 148, 304, 54, 8, C_BORDER);
gfx->drawRoundRect(8, 208, 304, 24, 6, C_BORDER);
}
static void drawBar(uint8_t pct, uint16_t color) {
int x = 18;
int y = 123;
int w = 284;
int h = 10;
gfx->fillRect(x, y, w, h, C_BORDER);
gfx->fillRect(x, y, (w * pct) / 100, h, color);
}
static void updateUi() {
Sample s = readSample();
if (s.mv < gMinMv) gMinMv = s.mv;
if (s.mv > gMaxMv) gMaxMv = s.mv;
uint32_t span = (gMaxMv > gMinMv) ? (gMaxMv - gMinMv) : 0;
if (!gHasEma) {
gEmaMv = (float)s.mv;
gHasEma = true;
} else {
gEmaMv = gEmaMv * 0.85f + (float)s.mv * 0.15f;
}
uint8_t pctAbs = percentFromMv(s.mv);
uint8_t pctCal = calibratedPercent(s.mv, span);
float ohms = estimateOhms(s.mv);
const char *status = statusText(s.mv, span, pctAbs);
uint16_t statusColor = strcmp(status, "MID") == 0 ? C_OK :
strcmp(status, "NO SPAN") == 0 ? C_WARN :
strcmp(status, "SATURATED") == 0 ? C_BAD : C_ACCENT;
char line[96];
gfx->fillRect(9, 77, 302, 62, C_BG);
snprintf(line, sizeof(line), "%s ADC=IO2 DRIVE=IO6", modeName());
drawText(16, 84, line, C_ACCENT, 1);
snprintf(line, sizeof(line), "raw:%4u mv:%4lu ema:%4lu",
s.raw, (unsigned long)s.mv, (unsigned long)(gEmaMv + 0.5f));
drawText(16, 101, line, C_TEXT, 1);
snprintf(line, sizeof(line), "abs:%3u%% cal:%3u%% jitter:%u",
pctAbs, pctCal, (unsigned)(s.rawMaxBurst - s.rawMinBurst));
drawText(16, 115, line, C_TEXT, 1);
drawBar(gMode == Mode::ThreeWire ? pctAbs : pctCal, statusColor);
gfx->fillRect(9, 149, 302, 52, C_BG);
snprintf(line, sizeof(line), "min:%4lu max:%4lu span:%4lu mV",
(unsigned long)gMinMv, (unsigned long)gMaxMv, (unsigned long)span);
drawText(16, 156, line, C_TEXT, 1);
if (ohms < 0) {
snprintf(line, sizeof(line), "ohm: open/too high status:%s", status);
} else {
snprintf(line, sizeof(line), "ohm:%6.1fk%s status:%s",
ohms / 1000.0f, gMode == Mode::TwoWire ? " rough" : "", status);
}
drawText(16, 172, line, statusColor, 1);
snprintf(line, sizeof(line), "touch:%s x:%u y:%u serial:m/r",
gTouchOk ? "ok" : "off", gLastTouchX, gLastTouchY);
drawText(16, 188, line, C_MUTE, 1);
gfx->fillRect(9, 209, 302, 22, C_BG);
if (gMode == Mode::ThreeWire) {
drawText(16, 216, "Wire: 3V3-edge GND-edge IO2-wiper", C_MUTE, 1);
} else {
drawText(16, 216, "Wire: IO6-edge IO2-wiper third pin open", C_MUTE, 1);
}
Serial.printf("mode=%s raw=%u mv=%lu ema=%.1f abs=%u cal=%u min=%lu max=%lu span=%lu jitter=%u status=%s\n",
modeName(), s.raw, (unsigned long)s.mv, gEmaMv, pctAbs, pctCal,
(unsigned long)gMinMv, (unsigned long)gMaxMv, (unsigned long)span,
(unsigned)(s.rawMaxBurst - s.rawMinBurst), status);
}
static void handleTouch() {
bsp_touch_read();
uint16_t x = 0;
uint16_t y = 0;
if (!bsp_touch_get_coordinates(&x, &y)) return;
gLastTouchX = x;
gLastTouchY = y;
if (contains(BTN_3WIRE, x, y)) {
setMode(Mode::ThreeWire);
drawStaticUi();
} else if (contains(BTN_2WIRE, x, y)) {
setMode(Mode::TwoWire);
drawStaticUi();
} else if (contains(BTN_RESET, x, y)) {
resetRange();
}
}
static void handleBootButton() {
bool down = digitalRead(PIN_BOOT_BUTTON) == LOW;
uint32_t now = millis();
if (down != gBootWasDown && now - gBootLastChangeMs > 40) {
gBootWasDown = down;
gBootLastChangeMs = now;
if (!down) {
setMode(gMode == Mode::ThreeWire ? Mode::TwoWire : Mode::ThreeWire);
drawStaticUi();
}
}
}
static void handleSerial() {
while (Serial.available() > 0) {
char c = (char)Serial.read();
if (c == 'm' || c == 'M') {
setMode(gMode == Mode::ThreeWire ? Mode::TwoWire : Mode::ThreeWire);
drawStaticUi();
} else if (c == 'r' || c == 'R') {
resetRange();
}
}
}
void setup() {
Serial.begin(115200);
delay(100);
Serial.println("ESP32-S3-LCD-2 potentiometer ADC test");
Serial.println("Commands: m=switch mode, r=reset min/max");
pinMode(PIN_BOOT_BUTTON, INPUT_PULLUP);
configurePins();
if (!gfx->begin()) {
Serial.println("gfx->begin() failed");
}
pinMode(PIN_LCD_BL, OUTPUT);
digitalWrite(PIN_LCD_BL, HIGH);
Wire.begin(PIN_TP_SDA, PIN_TP_SCL);
gTouchOk = bsp_touch_init(&Wire, 1, DISP_W, DISP_H);
drawStaticUi();
}
void loop() {
handleSerial();
handleBootButton();
if (gTouchOk) handleTouch();
uint32_t now = millis();
if (now - gLastUiMs >= 250) {
updateUi();
gLastUiMs = now;
}
if (now - gLastSerialMs >= 5000) {
Serial.println("Hint: m switches 3-WIRE/2-WIRE, r resets min/max. Never feed 5V into IO2/IO6.");
gLastSerialMs = now;
}
}
@@ -47,7 +47,6 @@ case "${MODE}" in
lvgl-official-based-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_official_based_test" ;;
lvgl-subserver-touch-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_subserver_touch_test" ;;
lvgl-russian-font-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_russian_font_test" ;;
breath-dual-mode-monitor) SKETCH_DIR="${ROOT_DIR}/test_sketches/breath_dual_mode_monitor" ;;
usb-contact-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/usb_contact_sensor_test" ;;
usb-contact-debug-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/usb_contact_sensor_debug_test" ;;
usb-contact-resistance-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/usb_contact_resistance_test" ;;
@@ -55,21 +54,13 @@ case "${MODE}" in
lvgl-nav-minimal-test) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_main" ;;
*)
echo "Unknown mode: ${MODE}" >&2
echo "Use one of: hello, widgets, audio, simple, argon2, homeserver-ui, shine-homeserver-main, shine-homeserver-ui-main, legacy-homeserver-ui, text-test, gfx-text-test, gfx-layout-test, lvgl-basic-test, lvgl-interaction-test, lvgl-touch-debug-test, lvgl-official-based-test, lvgl-subserver-touch-test, lvgl-russian-font-test, breath-dual-mode-monitor, usb-contact-test, usb-contact-debug-test, usb-contact-resistance-test, usb-contact-screen-start-stub" >&2
echo "Use one of: hello, widgets, audio, simple, argon2, homeserver-ui, shine-homeserver-main, shine-homeserver-ui-main, legacy-homeserver-ui, text-test, gfx-text-test, gfx-layout-test, lvgl-basic-test, lvgl-interaction-test, lvgl-touch-debug-test, lvgl-official-based-test, lvgl-subserver-touch-test, lvgl-russian-font-test, usb-contact-test, usb-contact-debug-test, usb-contact-resistance-test, usb-contact-screen-start-stub" >&2
exit 2
;;
esac
if [[ -z "${PORT}" ]]; then
if ! PORT="$(detect_port)"; then
echo "Failed to auto-detect ESP32 port. Set PORT=/dev/ttyACM0 ./burn.sh ${MODE}" >&2
exit 3
fi
fi
echo "== Mode: ${MODE}"
echo "== Sketch: ${SKETCH_DIR}"
echo "== Port: ${PORT}"
echo "== FQBN: ${FQBN}"
mkdir -p "${BUILD_DIR}" "${OUT_DIR}"
@@ -93,6 +84,20 @@ if ! arduino-cli compile "${compile_args[@]}"; then
arduino-cli compile --clean "${compile_args[@]}"
fi
if [[ "${NO_UPLOAD:-0}" == "1" ]]; then
echo "== Done: compiled without upload (NO_UPLOAD=1)."
exit 0
fi
if [[ -z "${PORT}" ]]; then
if ! PORT="$(detect_port)"; then
echo "Failed to auto-detect ESP32 port. Set PORT=/dev/ttyACM0 ./burn.sh ${MODE}" >&2
exit 3
fi
fi
echo "== Port: ${PORT}"
arduino-cli upload \
-p "${PORT}" \
--fqbn "${FQBN}" \
@@ -15,7 +15,6 @@
- `lvgl_official_based_test/` - минимальный наш экран поверх максимально близкой к официальному `05_LVGL_Widgets` инициализации
- `lvgl_subserver_touch_test/` - старый гибридный тест: `LVGL`-экран с инициализацией дисплея и чтением touch из старого `shine_homeserver_ui`; подтверждён на реальном устройстве
- `lvgl_russian_font_test/` - тест кастомного кириллического `LVGL`-шрифта с русскими кнопками, длинными строками и рабочим touch
- `breath_dual_mode_monitor/` - dual-mode breath monitor в стиле GFX-скетча: старт USB-датчика или внешних кнопок `KEY3/BOOT`, настройки лимита и громкости, повторяющиеся звуковые предупреждения
- `usb_contact_sensor_test/` - тест переключения нативных USB D-/D+ (`GPIO19/20`) в режим простого замыкаемого контакта после нажатия Start; после перезагрузки снова обычный USB
- `usb_contact_sensor_debug_test/` - debug-версия теста замыкания контакта: экранная кнопка проверяет touch, а переход в sensor mode выполняется физической кнопкой BOOT
- `usb_contact_resistance_test/` - тест измерения сопротивления между USB D-/D+ через ADC на GPIO20; рассчитан на внешний известный резистор 10 kΩ с D+ на GND
@@ -33,7 +32,6 @@
- `./burn.sh lvgl-official-based-test`
- `./burn.sh lvgl-subserver-touch-test`
- `./burn.sh lvgl-russian-font-test`
- `./burn.sh breath-dual-mode-monitor`
- `./burn.sh usb-contact-test`
- `./burn.sh usb-contact-debug-test`
- `./burn.sh usb-contact-resistance-test`
@@ -125,7 +125,11 @@ Initial screen:
- title: `BREATH MONITOR`
- state: `READY`
- action button: `START USB SENSOR`
- action button: `START BUTTONS`
- action button: `START MANUAL MONITOR`
- action button: `START POT 3-WIRE`
- action button: `START POT 2-WIRE`
- action button: `START POT CAL`
- action button: `START PIN DIAG`
After `START USB SENSOR`:
@@ -137,15 +141,54 @@ After `START USB SENSOR`:
- a short `KEY3 / GPIO18` press opens or closes settings in USB sensor mode
- the bottom line shows the durations of the last 5 accepted USB sensor cycles
After `START BUTTONS`:
After `START MANUAL MONITOR`:
- `KEY3 / GPIO18` is the external `INHALE` button, active LOW
- `BOOT / GPIO0` is the external `EXHALE` button, active LOW
- do not hold `BOOT` while booting or resetting the board
- the mode title is `MANUAL MONITOR`
- accepted manual phases strictly alternate: `INHALE`, then `EXHALE`; a repeated current button or `EXHALE` before the first `INHALE` is ignored without a beep or timer reset
- each accepted button press plays one quiet confirmation beep and starts a fresh `Phase time` timer for that inhale or exhale
- the working screen does not show touch `INHALE`/`EXHALE` buttons
- long-holding `KEY3 / INHALE` for about 850 ms opens settings; the long press still counts as an inhale press
- while settings are open, the next `KEY3 / INHALE` press closes settings and also counts as an inhale press
After `START POT 3-WIRE`:
- `GPIO19 / USB D-` is configured as `OUTPUT HIGH` and works as the 3.3 V side of the potentiometer test
- `GPIO20 / USB D+` is configured as ADC input and must be connected to the potentiometer wiper
- `USB GND` must be connected to the other edge pin of the potentiometer
- the screen shows position `0..100%`, a bar, ADC raw value, measured millivolts, and estimated `0..50 kΩ` resistance
- if ADC saturates or reaches an unsafe high-voltage threshold, the firmware releases `D-` and `D+` to `INPUT`, beeps, and shows `USB/PIN FAULT`
- this is only best-effort software protection; ESP32-S3 GPIO pins are not 5 V tolerant, so external wiring must still prevent 5 V from reaching `D+` or `D-`
After `START POT 2-WIRE`:
- `GPIO19 / USB D-` is configured as `OUTPUT HIGH`
- `GPIO20 / USB D+` is configured as ADC input with internal pulldown
- connect only two potentiometer pins between `D-` and `D+`: the wiper and one edge pin
- the screen shows rough position, raw ADC, millivolts, and rough estimated resistance
- this mode is intentionally approximate because the ESP32 internal pulldown value is not precise and can vary between boards
- use `START POT 3-WIRE` for stable and more linear future breath sensing
After `START POT CAL`:
- `GPIO19 / USB D-` is configured as `OUTPUT HIGH`
- `GPIO20 / USB D+` is configured as ADC input with internal pulldown
- connect only two potentiometer pins between `D-` and `D+`: the wiper and one edge pin
- the firmware tracks the observed minimum and maximum ADC millivolts
- the screen shows a calibrated `0..100%` position within the observed range, current millivolts, raw ADC, min-max range, and state
- `KEY3 / GPIO18` resets the learned min-max calibration
- this mode is for relative position testing on weak or shifted USB-pin ranges; it does not report real resistance
After `START PIN DIAG`:
- the firmware runs two alternating USB pin drive/read checks
- Test A drives `GPIO19 / USB D-` HIGH and reads `GPIO20 / USB D+` as ADC
- Test B drives `GPIO20 / USB D+` HIGH and reads `GPIO19 / USB D-` as ADC
- shorting `D-` and `D+` should make the ADC side rise if the pins are actually controllable as GPIO
- if both tests stay near 0 mV, the USB cable/host, USB PHY, or board wiring is likely holding the lines and the USB data pins are not usable as an analog sensor in that setup
In both modes:
- one breathing cycle is measured from one `EXHALE` tap to the next `EXHALE` tap
@@ -156,4 +199,5 @@ In both modes:
- the lower numeric fields use a larger font than before
- if the average of the last up to 5 completed cycles is shorter than the selected limit, warning beeps are played like in the USB contact breath monitor
- if the current cycle reaches 60 seconds, 5 loud warning beeps are played, then after 5 seconds another 5 loud warning beeps are played, repeating until the user changes phase / exits the long cycle
- in manual monitor mode, a single loud warning beep is also played at 35, 40, 45, 50, and 55 seconds of an unchanged inhale or exhale; the repeated five-beep alarm starts at 60 seconds
- settings keep the same sliders: limit `5/7/10/15/20` seconds, quiet cycle tick volume `0..10`, and alert volume `0..10`
@@ -2,6 +2,7 @@ package server.archive;
import blockchain.Ans104DataItem;
import blockchain.BchBlockEntry;
import server.archive.registration.VerifiedFreeRegistrationImporter;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
@@ -9,6 +10,7 @@ import org.slf4j.LoggerFactory;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
import server.sync.BlockchainResyncGuard;
import shine.db.DbController;
import utils.config.AppConfig;
import shine.db.dao.ArweaveBlockImportDAO;
import shine.db.dao.BlockchainStateDAO;
import shine.db.dao.BlocksDAO;
@@ -36,7 +38,7 @@ import java.time.Duration;
import java.util.*;
/**
* Discovers individual App=test5591 DataItems and imports the exact signed ANS-104 bytes.
* Discovers individual App=test5592 DataItems and imports the exact signed ANS-104 bytes.
* The importer is transport-agnostic: a DataItem may have reached Arweave through Turbo
* or inside a direct server-created ANS-104 bundle.
*/
@@ -50,6 +52,8 @@ public final class ArweaveBlockSyncService {
.connectTimeout(Duration.ofSeconds(20))
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
private final VerifiedFreeRegistrationImporter registrationImporter = new VerifiedFreeRegistrationImporter(
AppConfig.getInstance().getBoolean("freeRegistration.email.allowReuse", false));
private final ArweaveBlockImportDAO importDAO = ArweaveBlockImportDAO.getInstance();
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
private final SolanaUserPdaCurrentDAO usersDAO = SolanaUserPdaCurrentDAO.getInstance();
@@ -68,6 +72,7 @@ public final class ArweaveBlockSyncService {
public void runCycle() throws Exception {
recoverInterruptedCanonicalRebuilds();
discover();
discoverFreeRegistrations();
drainQueue();
}
@@ -116,6 +121,12 @@ public final class ArweaveBlockSyncService {
try {
DownloadedDataItem downloaded = downloadSignedDataItem(dataItemId);
if (isRegistrationItem(downloaded.rawDataItem())) {
registrationImporter.importSigned(downloaded.rawDataItem(),
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
unresolvedDownloads.remove(dataItemId);
continue; // Не парсить регистрацию как BchBlockEntry.
}
unresolvedDownloads.remove(dataItemId);
if (importDAO.enqueueIfMissing(id32, downloaded.rootTxId(), height, downloaded.rawDataItem(), System.currentTimeMillis())) discovered++;
} catch (RetryableDataItemDownloadException e) {
@@ -172,6 +183,18 @@ public final class ArweaveBlockSyncService {
continue;
}
if (isRegistrationItem(downloaded.rawDataItem())) {
try {
registrationImporter.importSigned(downloaded.rawDataItem(),
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
unresolvedDownloads.remove(pending.dataItemId());
} catch (Exception e) {
unresolvedDownloads.remove(pending.dataItemId());
unresolvedDownloads.put(pending.dataItemId(), pending);
log.debug("Registration {} awaits namespace/DB sync or retry: {}", pending.dataItemId(), e.getMessage());
}
continue;
}
if (importDAO.enqueueIfMissing(pending.id32(), downloaded.rootTxId(), pending.height(),
downloaded.rawDataItem(), System.currentTimeMillis())) {
queued++;
@@ -474,10 +497,84 @@ public final class ArweaveBlockSyncService {
}finally{BlockchainResyncGuard.end(activeName);}
}
/** Независимый GraphQL курсор для t=reg: не смешивается с блоковой очередью. */
private void discoverFreeRegistrations() throws Exception {
long stored;
try (Connection c = DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement(
"SELECT last_block_height FROM free_registration_arweave_sync_state WHERE id=1");
ResultSet rs = ps.executeQuery()) {
stored = rs.next() ? rs.getLong(1) : 0;
}
long minHeight = Math.max(cfg.syncStartBlockHeight(), stored);
long high = minHeight;
long retryFrom = Long.MAX_VALUE;
String cursor = null;
int count = 0;
do {
JsonNode response = graphQlPage(minHeight, cursor, true);
if (response.has("errors")) throw new IOException("Registration GraphQL errors: " + response.path("errors"));
JsonNode txs = response.path("data").path("transactions");
JsonNode edges = txs.path("edges");
if (!edges.isArray()) throw new IOException("Registration GraphQL returned no edges");
String next = null;
for (JsonNode edge : edges) {
next = edge.path("cursor").asText(null);
JsonNode node = edge.path("node");
String id = node.path("id").asText("").trim();
long height = node.path("block").path("height").asLong(-1);
if (id.isBlank() || height < 0) continue; // мгновенный Turbo-импорт не зависит от height
high = Math.max(high, height);
try {
byte[] idBytes = B64URL.decode(id);
if (idBytes.length != 32) throw new IllegalArgumentException("Malformed id");
DownloadedDataItem item = downloadSignedDataItem(id);
if (!isRegistrationItem(item.rawDataItem()))
throw new IllegalArgumentException("GraphQL registration tag is not present in signed bytes");
registrationImporter.importSigned(item.rawDataItem(),
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
count++;
} catch (RetryableDataItemDownloadException e) {
retryFrom = Math.min(retryFrom, height);
log.debug("Registration DataItem {} is not downloadable yet", id);
} catch (IllegalArgumentException e) {
log.warn("Rejecting invalid registration DataItem {}: {}", id, e.getMessage());
} catch (Exception e) {
retryFrom = Math.min(retryFrom, height);
log.warn("Registration DataItem {} import deferred: {}", id, e.getMessage());
}
}
cursor = txs.path("pageInfo").path("hasNextPage").asBoolean(false) ? next : null;
if (txs.path("pageInfo").path("hasNextPage").asBoolean(false) && (cursor == null || cursor.isBlank()))
throw new IOException("Registration GraphQL cursor missing");
} while (cursor != null);
long checkpoint = retryFrom == Long.MAX_VALUE ? high : Math.min(high, retryFrom);
try (Connection c = DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement("""
UPDATE free_registration_arweave_sync_state
SET last_block_height=?, updated_at_ms=? WHERE id=1
""")) {
ps.setLong(1, checkpoint); ps.setLong(2, System.currentTimeMillis()); ps.executeUpdate();
}
if (count > 0) log.info("Registration discovery verified {} DataItems; checkpoint={}", count, checkpoint);
}
private static boolean isRegistrationItem(byte[] raw) {
Ans104DataItem item = new Ans104DataItem(raw);
return item.tags().contains(new Ans104DataItem.Tag("t", "reg"));
}
private JsonNode graphQlPage(long minHeight, String cursor) throws Exception {
return graphQlPage(minHeight, cursor, false);
}
private JsonNode graphQlPage(long minHeight, String cursor, boolean registrationsOnly) throws Exception {
String after = cursor == null ? "null" : "\"" + escapeGraphQl(cursor) + "\"";
String query = "query { transactions(tags:[{name:\"" + ArweaveBlocksConfig.TEST_TAG_NAME + "\",values:[\""
+ ArweaveBlocksConfig.TEST_TAG_VALUE + "\"]}], block:{min:" + minHeight + "}, first:"
String tagFilter = "{name:\"" + ArweaveBlocksConfig.TEST_TAG_NAME + "\",values:[\""
+ ArweaveBlocksConfig.TEST_TAG_VALUE + "\"]}" +
(registrationsOnly ? ",{name:\"t\",values:[\"reg\"]}" : "");
String query = "query { transactions(tags:[" + tagFilter + "], block:{min:" + minHeight + "}, first:"
+ cfg.syncPageSize() + ", after:" + after
+ ", sort:HEIGHT_ASC) { pageInfo { hasNextPage } edges { cursor node { id block { height } } } } }";
String body = MAPPER.writeValueAsString(Map.of("query", query));
@@ -0,0 +1,50 @@
package server.archive.registration;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;
/** Список разрешённых доменов для бесплатной регистрации; читается при старте Java-сервера. */
public final class AllowedEmailDomains {
// Обычные ASCII-домены (в том числе punycode), без масок, пробелов и URL.
private static final Pattern DOMAIN = Pattern.compile(
"(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+");
private final Set<String> domains;
private AllowedEmailDomains(Set<String> domains) {
this.domains = Set.copyOf(domains);
}
/** Ошибки чтения, пустой или неверный список — ошибка запуска регистрации (fail-closed). */
public static AllowedEmailDomains load(Path file) throws IOException {
if (!Files.isRegularFile(file))
throw new IOException("Email domain allowlist is missing: " + file.toAbsolutePath());
Set<String> result = new HashSet<>();
int lineNumber = 0;
for (String line : Files.readAllLines(file, StandardCharsets.UTF_8)) {
lineNumber++;
String domain = line.strip().toLowerCase(Locale.ROOT);
if (domain.isEmpty() || domain.startsWith("#")) continue;
if (!DOMAIN.matcher(domain).matches())
throw new IOException("Invalid allowed email domain at " + file + ":" + lineNumber);
result.add(domain);
}
if (result.isEmpty())
throw new IOException("Email domain allowlist is empty: " + file.toAbsolutePath());
return new AllowedEmailDomains(result);
}
/** Сопоставление строго по части после одного символа @, без wildcard и суффиксов. */
public boolean permits(String email) {
if (email == null) return false;
String value = email.strip().toLowerCase(Locale.ROOT);
int at = value.indexOf('@');
if (at <= 0 || at != value.lastIndexOf('@')) return false;
return domains.contains(value.substring(at + 1));
}
}
@@ -0,0 +1,139 @@
package server.archive.registration;
import server.archive.ArweaveBlocksConfig;
import server.archive.TurboDataItemUploader;
import server.logic.ws_protocol.JSON.handlers.registration.RegistrationApiBridge;
import server.logic.ws_protocol.JSON.handlers.registration.Net_Registration_Request;
import shine.db.DbController;
import utils.config.AppConfig;
import javax.sql.DataSource;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/** Единственная точка подключения API без циклической зависимости Gradle-модулей. */
public final class FreeRegistrationApiBootstrap {
private static volatile FreeRegistrationWorkflow workflow;
private static volatile LocalRegistrarSigner signer;
private FreeRegistrationApiBootstrap() {}
public static synchronized void startOrThrow() throws Exception {
if (workflow != null) return;
AppConfig cfg=AppConfig.getInstance();
LocalRegistrarSigner newSigner=null;
FreeRegistrationIssuer issuer=null;
FreeRegistrationPublisher publisher=null;
RegistrationEmailSender emailSender=null;
AllowedEmailDomains allowedEmailDomains=null;
if (cfg.getBoolean("freeRegistration.enabled",false)) {
String domainsFile = cfg.getStringOrEmpty("freeRegistration.email.allowedDomainsFile");
if (domainsFile.isBlank()) domainsFile = "allowed-email-domains.txt";
// Относительный путь — от WorkingDirectory процесса Java.
allowedEmailDomains = AllowedEmailDomains.load(Path.of(domainsFile));
boolean allowEmailReuse=cfg.getBoolean("freeRegistration.email.allowReuse",false);
// Не выводить seed/path в журнал ни при успешном старте, ни при ошибке.
ArweaveBlocksConfig transport=ArweaveBlocksConfig.load();
if(transport.publishMode()!=ArweaveBlocksConfig.PublishMode.TURBO)
throw new IllegalStateException("Free registration requires Turbo transport");
newSigner=LocalRegistrarSigner.fromConfig(cfg);
issuer=new FreeRegistrationIssuer(dbSource(),newSigner,allowEmailReuse);
publisher=new FreeRegistrationPublisher(issuer,new TurboDataItemUploader(transport),
new VerifiedFreeRegistrationImporter(allowEmailReuse));
// Секрет берём ТОЛЬКО из окружения, не из файлов репозитория.
String resendKey=System.getenv("RESEND_API_KEY");
if(resendKey==null || resendKey.isBlank())
resendKey=cfg.getStringOrEmpty("freeRegistration.email.apiKey");
emailSender=new ResendRegistrationEmailSender(resendKey,
cfg.getStringOrEmpty("freeRegistration.email.from").isBlank()
? "SHiNE <noreply@shineup.me>"
: cfg.getStringOrEmpty("freeRegistration.email.from"));
}
FreeRegistrationWorkflow newWorkflow=new FreeRegistrationWorkflow(issuer,publisher,emailSender,
cfg.getBoolean("freeRegistration.email.allowTestCode",false),
cfg.getBoolean("freeRegistration.email.allowReuse",false), allowedEmailDomains);
RegistrationApiBridge.install((op,req)->dispatch(newWorkflow,op,req));
signer=newSigner; workflow=newWorkflow;
}
public static synchronized void close() {
RegistrationApiBridge.uninstall();
workflow=null;
if(signer!=null) signer.close();
signer=null;
}
public static Map<String,Object> dispatch(FreeRegistrationWorkflow w, String op,Net_Registration_Request req) throws Exception {
Map<String,Object> out=new LinkedHashMap<>();
switch(op) {
case "GetNamespaces" -> {
out.put("namespaces",w.listNamespaces().stream().map(ns->Map.of(
"name",ns.namespace(), "type",ns.type(), "minLocalLength",ns.minLoginLength(),
"registrationFeeLamports",ns.priceLamports(), "defaultServerLogin",ns.serverLogin()==null?"":ns.serverLogin()
)).toList());
}
case "CheckRegistrationLogin" -> {
var info=w.checkLogin(req.getFullLogin());
out.put("loginAvailable",info.loginAvailable());
out.put("namespaceType",info.namespaceType());
out.put("minLocalLength",info.minLocalLength());
out.put("registrationFeeLamports",info.registrationFeeLamports());
}
case "CheckRegistrationEmail" -> {
var check=w.checkEmail(req.getEmail());
out.put("emailAvailable",check.emailAvailable());
out.put("emailStatus",check.emailStatus());
}
case "StartFreeRegistration" -> {
var state=w.start(req.getFullLogin(),decodeKey(req.getRootPublicKeyB64()),
decodeKey(req.getBlockchainPublicKeyB64()),decodeKey(req.getClientPublicKeyB64()),req.getEmail());
out.put("challengeId",state.challengeId()); out.put("expiresAtMs",state.expiresAtMs());
}
case "ConfirmFreeRegistration" -> {
var value=w.confirm(req.getChallengeId(),req.getCode());
out.put("fullLogin",value.fullLogin());out.put("dataItemId",value.dataItemId());
out.put("publicationStatus",value.state());out.put("chainConfirmed",false);
}
case "GetRegistrationStatus" -> {
var value=w.getStatus(req.getFullLogin());
out.put("registrationStatus",value.status());
out.put("dataItemId",value.dataItemId()==null?"":value.dataItemId());
out.put("publicationStatus",value.publicationStatus()==null?"":value.publicationStatus());
// Публичная историческая часть сертификата для бесплатного → Solana upgrade.
if("FREE_CERT".equals(value.status())) {
out.put("innerSignature64B64",value.innerSignature64B64()==null?"":value.innerSignature64B64());
out.put("rootPublicKey",value.rootPublicKey()==null?"":value.rootPublicKey());
out.put("blockchainPublicKey",value.blockchainPublicKey()==null?"":value.blockchainPublicKey());
out.put("clientPublicKey",value.clientPublicKey()==null?"":value.clientPublicKey());
out.put("defaultServerLogin",value.defaultServerLogin()==null?"":value.defaultServerLogin());
}
}
default -> throw new IllegalArgumentException("Unknown registration operation");
}
return out;
}
private static byte[] decodeKey(String base64) {
if(base64==null || base64.length()>64)throw new IllegalArgumentException("Invalid public key");
byte[] decoded=Base64.getDecoder().decode(base64);
if(decoded.length!=32)throw new IllegalArgumentException("Invalid public key length");
return decoded;
}
private static DataSource dbSource() {
return new DataSource() {
@Override public Connection getConnection() throws SQLException {return DbController.getInstance().getConnection();}
@Override public Connection getConnection(String u,String p) throws SQLException {throw new SQLFeatureNotSupportedException();}
@Override public PrintWriter getLogWriter(){return null;}
@Override public void setLogWriter(PrintWriter p){}
@Override public void setLoginTimeout(int t){}
@Override public int getLoginTimeout(){return 0;}
@Override public Logger getParentLogger(){return Logger.getGlobal();}
@Override public <T> T unwrap(Class<T> type) throws SQLException {throw new SQLFeatureNotSupportedException();}
@Override public boolean isWrapperFor(Class<?> type){return false;}
};
}
}
@@ -0,0 +1,115 @@
package server.archive.registration;
import blockchain.Ans104DataItem;
import blockchain.ShineProtocolTags;
import utils.crypto.Ed25519Util;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.Normalizer;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
/** Строгое формирование и проверка двух подписей нового независимого DataItem `t=reg`. */
public final class FreeRegistrationCertificateV1 {
private static final byte[] DOMAIN = "SHiNE_FREE_REG_V1\0".getBytes(StandardCharsets.UTF_8);
private static final List<Ans104DataItem.Tag> TAGS = List.of(
new Ans104DataItem.Tag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE),
new Ans104DataItem.Tag("t", "reg"),
new Ans104DataItem.Tag("Protocol", "SHiNE-Free-Registration-V1"));
public record Verified(String login, byte[] rootKey, byte[] blockchainKey,
byte[] clientKey, byte[] innerSignature,
byte[] emailSha256, byte[] owner32, String idBase64Url) {}
private FreeRegistrationCertificateV1() {}
public static String validateLogin(String login) {
if (login == null || !login.matches("[A-Za-z0-9_]+@[a-z0-9_]+") || login.length() > 30)
throw new IllegalArgumentException("Full login must use ASCII letters (any local-part case), lowercase namespace, <= 30 bytes");
return login;
}
public static byte[] identityFields(String login, byte[] root32, byte[] blockchain32, byte[] client32) {
byte[] name = validateLogin(login).getBytes(StandardCharsets.UTF_8);
require32(root32); require32(blockchain32); require32(client32);
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(1); out.write(0); out.write(name.length); out.writeBytes(name);
out.writeBytes(root32); out.writeBytes(blockchain32); out.writeBytes(client32);
return out.toByteArray();
}
public static byte[] innerMessage(byte[] identity) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.writeBytes(DOMAIN); out.writeBytes(identity);
return out.toByteArray();
}
public static String normalizeEmail(String email) {
if (email == null) throw new IllegalArgumentException("Email is required");
String value = Normalizer.normalize(email.strip(), Normalizer.Form.NFC).toLowerCase(Locale.ROOT);
if (value.isBlank() || value.indexOf('@') < 1 || value.contains(" "))
throw new IllegalArgumentException("Invalid email");
return value;
}
public static byte[] emailHash(String email) {
return sha256(normalizeEmail(email).getBytes(StandardCharsets.UTF_8));
}
public static byte[] issue(String login, byte[] root32, byte[] blockchain32,
byte[] client32, String email, RegistrarSigner signer) {
byte[] fields = identityFields(login, root32, blockchain32, client32);
byte[] inner = signer.sign(innerMessage(fields));
if (inner.length != 64) throw new IllegalStateException("Invalid inner signature length");
ByteArrayOutputStream payload = new ByteArrayOutputStream();
payload.writeBytes(fields);
payload.writeBytes(inner);
payload.writeBytes(emailHash(email));
byte[] data = payload.toByteArray();
byte[] owner = signer.publicKey32();
require32(owner);
byte[] outer = signer.sign(Ans104DataItem.buildSigningMessage(owner, TAGS, data));
byte[] raw = Ans104DataItem.serializeEd25519(outer, owner, TAGS, data);
verify(raw, owner);
return raw;
}
public static Verified verify(byte[] signedDataItem, byte[] registrarPublicKey32) {
require32(registrarPublicKey32);
Ans104DataItem item = new Ans104DataItem(signedDataItem);
if (!item.ownerEquals(registrarPublicKey32) || !item.verifySignature())
throw new IllegalArgumentException("Invalid outer ANS-104 registrar signature");
if (!item.tags().equals(TAGS) || item.target().length != 0 || item.anchor().length != 0)
throw new IllegalArgumentException("Unexpected registration tags/target/anchor");
byte[] data = item.data();
if (data.length < 3 + 96 + 64 + 32 || data[0] != 1 || data[1] != 0)
throw new IllegalArgumentException("Invalid certificate version/length");
int len = data[2] & 0xff;
if (data.length != 3 + len + 96 + 64 + 32)
throw new IllegalArgumentException("Invalid certificate byte length");
String login = validateLogin(new String(data, 3, len, StandardCharsets.UTF_8));
int offset = 3 + len;
byte[] root = Arrays.copyOfRange(data, offset, offset+32); offset += 32;
byte[] blockchain = Arrays.copyOfRange(data, offset, offset+32); offset += 32;
byte[] client = Arrays.copyOfRange(data, offset, offset+32); offset += 32;
byte[] innerSig = Arrays.copyOfRange(data, offset, offset+64); offset += 64;
byte[] emailSha = Arrays.copyOfRange(data, offset, offset+32);
byte[] fields = Arrays.copyOfRange(data, 0, 3 + len + 96);
if (!Ed25519Util.verify(innerMessage(fields), innerSig, registrarPublicKey32))
throw new IllegalArgumentException("Invalid inner certificate signature");
return new Verified(login, root, blockchain, client, innerSig, emailSha,
item.owner32(), Base64.getUrlEncoder().withoutPadding().encodeToString(item.id32()));
}
private static void require32(byte[] key) {
if (key == null || key.length != 32) throw new IllegalArgumentException("Expected 32-byte public key");
}
private static byte[] sha256(byte[] data) {
try { return MessageDigest.getInstance("SHA-256").digest(data); }
catch (Exception e) { throw new IllegalStateException("SHA-256 unavailable", e); }
}
}
@@ -0,0 +1,74 @@
package server.archive.registration;
import sync.util.Base58Util;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Arrays;
/** Выдача (без публикации). Stage 8 публикует через Turbo и импортирует тот же raw DataItem. */
public final class FreeRegistrationIssuer {
private final DataSource db;
private final RegistrarSigner signer;
private final boolean allowEmailReuse;
public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer) {
this(db, signer, false);
}
public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer, boolean allowEmailReuse) {
this.db = java.util.Objects.requireNonNull(db);
this.signer = java.util.Objects.requireNonNull(signer);
this.allowEmailReuse = allowEmailReuse;
}
/** Выдаётся только после успешной проверки challenge в FreeRegistrationWorkflow. */
synchronized byte[] issue(String fullLogin, byte[] root32, byte[] blockchain32,
byte[] client32, String email) throws Exception {
FreeRegistrationCertificateV1.validateLogin(fullLogin);
String namespace = fullLogin.substring(fullLogin.indexOf('@') + 1);
byte[] expectedEmail = FreeRegistrationCertificateV1.emailHash(email);
try (Connection conn = db.getConnection()) {
conn.setReadOnly(true);
String sql = """
SELECT namespace_type, min_localpart_len, registrar_pubkey, default_server_login
FROM shine_namespace_current WHERE namespace = ?
""";
try (PreparedStatement statement = conn.prepareStatement(sql)) {
statement.setString(1, namespace);
try (ResultSet rs = statement.executeQuery()) {
if (!rs.next() || rs.getInt("namespace_type") != 2 ||
fullLogin.indexOf('@') < rs.getInt("min_localpart_len"))
throw new IllegalArgumentException("Free namespace is unavailable");
byte[] nsPub = Base58Util.decode(rs.getString("registrar_pubkey"));
if (!Arrays.equals(nsPub, signer.publicKey32()))
throw new IllegalStateException("Registrar public key does not match on-chain namespace");
String server = rs.getString("default_server_login");
if (server == null || server.isBlank())
throw new IllegalStateException("Free namespace server is not configured");
}
}
try (PreparedStatement ps = conn.prepareStatement(
"SELECT 1 FROM user_identity_current WHERE normalized_login = ?")) {
ps.setString(1, fullLogin.toLowerCase(java.util.Locale.ROOT));
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) throw new IllegalArgumentException("Login is already registered");
}
}
if (!allowEmailReuse) {
try (PreparedStatement ps = conn.prepareStatement(
"SELECT 1 FROM free_registration_certificate WHERE email_sha256 = ?")) {
ps.setBytes(1, expectedEmail);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) throw new IllegalArgumentException("Email hash already registered");
}
}
}
}
// Это только подписанный артефакт, не активная регистрация. Перед Turbo
// и локальным импортом обязательно повторять уникальность в транзакции БД.
return FreeRegistrationCertificateV1.issue(fullLogin, root32, blockchain32, client32, email, signer);
}
}
@@ -0,0 +1,30 @@
package server.archive.registration;
import server.archive.TurboDataItemUploader;
import blockchain.Ans104DataItem;
/** Отдельный транспорт регистрации. Публикация не является пользовательским AddBlock. */
public final class FreeRegistrationPublisher {
private final FreeRegistrationIssuer issuer;
private final TurboDataItemUploader uploader;
private final VerifiedFreeRegistrationImporter importer;
public FreeRegistrationPublisher(FreeRegistrationIssuer issuer, TurboDataItemUploader uploader,
VerifiedFreeRegistrationImporter importer) {
this.issuer = java.util.Objects.requireNonNull(issuer);
this.uploader = java.util.Objects.requireNonNull(uploader);
this.importer = java.util.Objects.requireNonNull(importer);
}
/** Для повтора ПОСЛЕ потери ACK передавайте точно те же signedBytes. */
public VerifiedFreeRegistrationImporter.ImportResult publishSigned(byte[] signedBytes) throws Exception {
Ans104DataItem parsed = new Ans104DataItem(signedBytes);
importer.validateForUpload(signedBytes); // строго до HTTP/Turbo списания кредитов
// Импорт на этой точке вызовет полную проверку обеих подписей и namespace
// ПОСЛЕ успешного ACK Turbo, а не до окончательного подтверждения Arweave.
TurboDataItemUploader.UploadResult acknowledged = uploader.upload(signedBytes, parsed.id32());
String expectedId = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(parsed.id32());
if (!expectedId.equals(acknowledged.dataItemId()))
throw new IllegalStateException("Unexpected Turbo DataItem id");
return importer.importSigned(signedBytes, VerifiedFreeRegistrationImporter.Provenance.TURBO_ACCEPTED);
}
}
@@ -0,0 +1,250 @@
package server.archive.registration;
import shine.db.DbController;
import java.security.SecureRandom;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/** Внутренний state machine публичных операций регистрации v2. */
public final class FreeRegistrationWorkflow {
public record NamespaceInfo(String namespace, int type, int minLoginLength, String priceLamports, String serverLogin) {}
public record Availability(boolean nameFree, boolean emailHashFree) {}
public record LoginCheck(boolean loginAvailable, int namespaceType, int minLocalLength, String registrationFeeLamports) {}
public record EmailCheck(boolean emailAvailable, String emailStatus) {}
public record Started(String challengeId, long expiresAtMs) {}
public record Completed(String fullLogin, String dataItemId, String state, boolean alreadyImported) {}
public record State(String status, String dataItemId, String publicationStatus, String innerSignature64B64,
String rootPublicKey, String blockchainPublicKey, String clientPublicKey,
String defaultServerLogin) {}
private record Draft(String login, byte[] root, byte[] blockchain, byte[] client, String email,
long expiresAtMs, byte[] codeHash, int attempts, boolean delivered,
boolean verified, byte[] signedBytes) {
Draft update(int attempts, boolean delivered, boolean verified, byte[] signedBytes) {
return new Draft(login, root, blockchain, client, email, expiresAtMs,
codeHash, attempts, delivered, verified, signedBytes);
}
}
private final Map<String, Draft> pending = new ConcurrentHashMap<>();
// Не храним в БД почтовые адреса, пока регистрация не завершилась.
private final Map<String, Long> recentEmails = new HashMap<>();
private final Map<String, Long> recentLogins = new HashMap<>();
private final java.util.ArrayDeque<Long> globalSendTimes = new java.util.ArrayDeque<>();
private static final long TTL_MS = Duration.ofHours(1).toMillis();
private static final long EMAIL_COOLDOWN_MS = Duration.ofMinutes(1).toMillis();
private static final long GLOBAL_WINDOW_MS = Duration.ofHours(1).toMillis();
private static final int MAX_EMAILS_PER_HOUR = 60;
private static final int MAX_ATTEMPTS = 5;
private static final int MAX_PENDING = 512;
private static final SecureRandom RANDOM = new SecureRandom();
private final FreeRegistrationIssuer issuer;
private final FreeRegistrationPublisher publisher;
private final RegistrationEmailSender emailSender;
private final boolean allowTestCode;
private final boolean allowEmailReuse;
private final AllowedEmailDomains allowedEmailDomains;
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse,
AllowedEmailDomains allowedEmailDomains) {
if ((issuer == null) != (publisher == null)) throw new IllegalArgumentException("Signer/publisher mismatch");
if (issuer != null && emailSender == null) throw new IllegalArgumentException("Email sender is required");
if (emailSender != null && allowedEmailDomains == null)
throw new IllegalArgumentException("Allowed email domain list is required");
this.allowedEmailDomains = allowedEmailDomains;
this.issuer = issuer;
this.publisher = publisher;
this.emailSender = emailSender;
this.allowTestCode = allowTestCode;
this.allowEmailReuse = allowEmailReuse;
}
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse) {
this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse,
emailSender == null ? null : loadDefaultEmailDomains());
}
private static AllowedEmailDomains loadDefaultEmailDomains() {
try {
return AllowedEmailDomains.load(java.nio.file.Path.of("allowed-email-domains.txt"));
} catch (java.io.IOException e) {
throw new IllegalStateException("Cannot load allowed email domains", e);
}
}
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
RegistrationEmailSender emailSender, boolean allowTestCode) {
this(issuer, publisher, emailSender, allowTestCode, false);
}
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
RegistrationEmailSender emailSender) {
this(issuer, publisher, emailSender, false);
}
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher) {
this(issuer, publisher, null);
}
public List<NamespaceInfo> listNamespaces() throws Exception {
List<NamespaceInfo> result = new ArrayList<>();
try (Connection c = DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement("""
SELECT namespace,namespace_type,min_localpart_len,registration_fee_lamports,default_server_login
FROM shine_namespace_current ORDER BY namespace
"""); ResultSet rs = ps.executeQuery()) {
while (rs.next()) result.add(new NamespaceInfo(rs.getString(1),rs.getInt(2),rs.getInt(3),
rs.getString(4),rs.getString(5)));
}
return List.copyOf(result);
}
public LoginCheck checkLogin(String login) throws Exception {
FreeRegistrationCertificateV1.validateLogin(login);
String namespace=login.substring(login.indexOf('@')+1);
try (Connection c=DbController.getInstance().getConnection()) {
int type, minimum; String fee;
try (PreparedStatement p=c.prepareStatement("SELECT namespace_type,min_localpart_len,registration_fee_lamports FROM shine_namespace_current WHERE namespace=?")) {
p.setString(1,namespace);
try (ResultSet rs=p.executeQuery()) {
if (!rs.next()) throw new IllegalArgumentException("Namespace is unavailable");
type=rs.getInt(1); minimum=rs.getInt(2); fee=rs.getString(3);
if (login.indexOf('@') < minimum) throw new IllegalArgumentException("Login shorter than namespace minimum");
}
}
try (PreparedStatement p=c.prepareStatement("SELECT 1 FROM user_identity_current WHERE normalized_login=?")) {
p.setString(1, login.toLowerCase(java.util.Locale.ROOT));
try (ResultSet rs=p.executeQuery()) { return new LoginCheck(!rs.next(),type,minimum,fee); }
}
}
}
public EmailCheck checkEmail(String email) throws Exception {
// До запроса к БД: отсутствие разрешения не должно раскрывать занятость email.
String normalizedEmail = FreeRegistrationCertificateV1.normalizeEmail(email);
if (allowedEmailDomains == null || !allowedEmailDomains.permits(normalizedEmail))
return new EmailCheck(false, "DOMAIN_NOT_ALLOWED");
byte[] hash=FreeRegistrationCertificateV1.emailHash(normalizedEmail);
if (allowEmailReuse) return new EmailCheck(true, "AVAILABLE");
try (Connection c=DbController.getInstance().getConnection();
PreparedStatement p=c.prepareStatement("SELECT 1 FROM free_registration_certificate WHERE email_sha256=?")) {
p.setBytes(1,hash);
try(ResultSet rs=p.executeQuery()) { return rs.next() ? new EmailCheck(false, "ALREADY_REGISTERED")
: new EmailCheck(true, "AVAILABLE"); }
}
}
/** Устаревший внутренний helper: внешний API использует две отдельные операции. */
public Availability availability(String login,String email) throws Exception {
return new Availability(checkLogin(login).loginAvailable(),checkEmail(email).emailAvailable());
}
public Started start(String login, byte[] root, byte[] blockchain, byte[] client, String email) throws Exception {
if (issuer == null || publisher == null || emailSender == null)
throw new IllegalStateException("Free registration is disabled");
FreeRegistrationCertificateV1.identityFields(login,root,blockchain,client);
LoginCheck checked = checkLogin(login);
if (checked.namespaceType()!=2 || !checked.loginAvailable())
throw new IllegalStateException("Login is unavailable");
if (!checkEmail(email).emailAvailable()) throw new IllegalStateException("Email is unavailable");
String cleanEmail=FreeRegistrationCertificateV1.normalizeEmail(email);
String normalizedLogin=login.toLowerCase(java.util.Locale.ROOT);
byte[] id=new byte[32]; RANDOM.nextBytes(id);
String challenge=Base64.getUrlEncoder().withoutPadding().encodeToString(id);
String code=RegistrationEmailCode.generate();
long now=System.currentTimeMillis();
long expires=now+TTL_MS;
Draft draft=new Draft(login,root.clone(),blockchain.clone(),client.clone(),cleanEmail,
expires,RegistrationEmailCode.hash(challenge,code),0,false,false,null);
synchronized (this) {
pending.entrySet().removeIf(e->e.getValue().expiresAtMs < now);
recentEmails.entrySet().removeIf(e->e.getValue() < now-TTL_MS);
recentLogins.entrySet().removeIf(e->e.getValue() < now-TTL_MS);
while(!globalSendTimes.isEmpty() && globalSendTimes.peekFirst() < now-GLOBAL_WINDOW_MS)
globalSendTimes.removeFirst();
if (pending.size() >= MAX_PENDING) throw new IllegalStateException("Too many pending registrations");
if (now-recentEmails.getOrDefault(cleanEmail,0L) < EMAIL_COOLDOWN_MS ||
now-recentLogins.getOrDefault(normalizedLogin,0L) < EMAIL_COOLDOWN_MS)
throw new IllegalStateException("Please wait before requesting another code");
if (globalSendTimes.size() >= MAX_EMAILS_PER_HOUR)
throw new IllegalStateException("Email verification temporarily limited");
recentEmails.put(cleanEmail,now);
recentLogins.put(normalizedLogin,now);
globalSendTimes.addLast(now);
pending.put(challenge,draft);
}
try {
// Не блокируем monitor workflow на время HTTP-запроса к Resend.
emailSender.sendVerificationCode(cleanEmail,code);
} catch (Exception e) {
synchronized (this) {
pending.remove(challenge);
recentEmails.remove(cleanEmail,now);
recentLogins.remove(normalizedLogin,now);
globalSendTimes.removeFirstOccurrence(now);
}
throw e;
}
synchronized (this) {
// Новый успешно отправленный код заменяет старые заявки на тот же login/email.
pending.entrySet().removeIf(e -> !e.getKey().equals(challenge) &&
(e.getValue().email.equals(cleanEmail) ||
e.getValue().login.equalsIgnoreCase(login)));
pending.computeIfPresent(challenge,(key,d)->d.update(d.attempts,true,d.verified,d.signedBytes));
}
return new Started(challenge,expires);
}
boolean isValidVerificationCode(byte[] expectedHash, String challenge, String code) {
return (allowTestCode && "777777".equals(code))
|| RegistrationEmailCode.matches(expectedHash, challenge, code);
}
public synchronized Completed confirm(String challenge, String code) throws Exception {
if (publisher == null) throw new IllegalStateException("Free registration disabled");
if (challenge == null || challenge.isBlank())
throw new IllegalArgumentException("Registration challenge missing");
Draft d=pending.get(challenge);
if (d==null || d.expiresAtMs < System.currentTimeMillis()) {
pending.remove(challenge); throw new IllegalArgumentException("Registration challenge missing or expired");
}
if (!d.delivered) throw new IllegalStateException("Verification email is not delivered yet");
if (!d.verified) {
if (!isValidVerificationCode(d.codeHash, challenge, code)) {
if (d.attempts+1 >= MAX_ATTEMPTS) pending.remove(challenge);
else pending.put(challenge,d.update(d.attempts+1,true,false,d.signedBytes));
throw new IllegalArgumentException("Invalid email code");
}
// Если Turbo не ответит, подтверждённая заявка может быть повторена до TTL.
d=d.update(d.attempts,true,true,d.signedBytes);
pending.put(challenge,d);
}
byte[] signed=d.signedBytes;
if(signed==null) {
signed=issuer.issue(d.login,d.root,d.blockchain,d.client,d.email);
d=d.update(d.attempts,true,true,signed);
pending.put(challenge,d);
}
VerifiedFreeRegistrationImporter.ImportResult result=publisher.publishSigned(signed);
// Повтор использует тот же подписанный DataItem, без смены ключей и адреса email.
return new Completed(result.login(),result.dataItemId(),"TURBO_ACCEPTED",result.alreadyImported());
}
public State getStatus(String login) throws Exception {
FreeRegistrationCertificateV1.validateLogin(login);
try (Connection c=DbController.getInstance().getConnection();
PreparedStatement p=c.prepareStatement("""
SELECT i.registration_status,i.free_data_item_id,f.publication_status,f.inner_signature,
i.root_key,i.blockchain_key,i.client_key,n.default_server_login
FROM user_identity_current i
LEFT JOIN free_registration_certificate f ON f.data_item_id=i.free_data_item_id
LEFT JOIN shine_namespace_current n ON n.namespace=i.namespace
WHERE i.normalized_login=?
""")) {
p.setString(1,login.toLowerCase(java.util.Locale.ROOT));
try (ResultSet r=p.executeQuery()) {
return r.next()?new State(r.getString(1),r.getString(2),r.getString(3),
r.getBytes(4)==null?null:Base64.getEncoder().encodeToString(r.getBytes(4)),
r.getString(5),r.getString(6),r.getString(7),r.getString(8))
:new State("NOT_FOUND",null,null,null,null,null,null,null);
}
}
}
}
@@ -0,0 +1,43 @@
package server.archive.registration;
import utils.crypto.Ed25519Util;
import utils.config.AppConfig;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Base64;
/** Временный signer. Файл вне Git: одно значение Base64 от 32-байтного Ed25519 seed. */
public final class LocalRegistrarSigner implements RegistrarSigner {
private final byte[] seed32;
private final byte[] publicKey32;
private boolean closed;
public LocalRegistrarSigner(byte[] seed) {
if (seed == null || seed.length != 32) throw new IllegalArgumentException("Registrar seed must be 32 bytes");
this.seed32 = seed.clone();
this.publicKey32 = Ed25519Util.derivePublicKey(seed32);
}
public static LocalRegistrarSigner fromConfig(AppConfig config) throws Exception {
if (!config.getBoolean("freeRegistration.enabled", false))
throw new IllegalStateException("Free registration is disabled");
String path = config.getStringOrEmpty("freeRegistration.registrarSeedFile");
if (path.isEmpty()) throw new IllegalStateException("Registrar key path is not configured");
byte[] seed = Base64.getDecoder().decode(Files.readString(Path.of(path), StandardCharsets.UTF_8).trim());
try { return new LocalRegistrarSigner(seed); }
finally { Arrays.fill(seed, (byte) 0); }
}
@Override public synchronized byte[] publicKey32() { return publicKey32.clone(); }
@Override public synchronized byte[] sign(byte[] message) {
if (closed) throw new IllegalStateException("Signer closed");
return Ed25519Util.sign(message, seed32);
}
@Override public synchronized void close() {
Arrays.fill(seed32, (byte) 0);
closed = true;
}
}
@@ -0,0 +1,8 @@
package server.archive.registration;
/** Интерфейс приватного регистратора: private key не передаётся в бизнес-логику. */
public interface RegistrarSigner extends AutoCloseable {
byte[] publicKey32();
byte[] sign(byte[] message);
@Override default void close() {}
}
@@ -0,0 +1,31 @@
package server.archive.registration;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HexFormat;
/** Одноразовый код не сохраняется в открытом виде и не попадает в журнал. */
final class RegistrationEmailCode {
private static final SecureRandom RANDOM = new SecureRandom();
private RegistrationEmailCode() {}
static String generate() {
return String.format(java.util.Locale.ROOT, "%06d", RANDOM.nextInt(1_000_000));
}
static byte[] hash(String challengeId, String code) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
return md.digest((challengeId + ":" + code).getBytes(StandardCharsets.UTF_8));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 unavailable", e);
}
}
static boolean matches(byte[] expectedHash, String challengeId, String submitted) {
return submitted != null && submitted.matches("[0-9]{6}") &&
MessageDigest.isEqual(expectedHash, hash(challengeId, submitted));
}
}
@@ -0,0 +1,7 @@
package server.archive.registration;
/** Отправка кода. Детали внешнего почтового провайдера не влияют на протокол регистрации. */
@FunctionalInterface
public interface RegistrationEmailSender {
void sendVerificationCode(String recipient, String code) throws Exception;
}
@@ -0,0 +1,63 @@
package server.archive.registration;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Map;
/** Транзакционная отправка через Resend: HTTP API, без SMTP и внешней Java SDK. */
public final class ResendRegistrationEmailSender implements RegistrationEmailSender {
private static final URI ENDPOINT = URI.create("https://api.resend.com/emails");
private static final String SUBJECT = "SHiNE — код подтверждения email";
private final HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5)).build();
private final ObjectMapper mapper = new ObjectMapper();
private final String apiKey;
private final String from;
public ResendRegistrationEmailSender(String apiKey, String from) {
if (apiKey == null || apiKey.isBlank())
throw new IllegalStateException("Resend API key is required for free registration");
if (from == null || from.isBlank())
throw new IllegalStateException("Sender email is missing");
this.apiKey = apiKey.trim();
this.from = from.trim();
}
@Override
public void sendVerificationCode(String recipient, String code) throws Exception {
if (recipient == null || recipient.isBlank() || !code.matches("[0-9]{6}"))
throw new IllegalArgumentException("Invalid email verification request");
String text = "Добро пожаловать в SHiNE!\n\n"
+ "Для завершения регистрации введите код подтверждения:\n\n"
+ code + "\n\n"
+ "Код действителен в течение 1 часа.\n\n"
+ "Если вы не регистрировались в SHiNE, просто проигнорируйте это письмо.\n\n"
+ "Команда SHiNE";
String html = "<div style=\"font-family:Arial,sans-serif;max-width:520px;margin:auto;"
+ "padding:24px;color:#1d2433;line-height:1.6\">"
+ "<h2 style=\"margin:0 0 20px\">Добро пожаловать в SHiNE!</h2>"
+ "<p>Для завершения регистрации введите код подтверждения:</p>"
+ "<p style=\"font-size:32px;font-weight:700;letter-spacing:6px\">" + code + "</p>"
+ "<p>Код действителен в течение 1 часа.</p>"
+ "<p style=\"color:#5d6470\">Если вы не регистрировались в SHiNE, "
+ "просто проигнорируйте это письмо.</p><p>Команда SHiNE</p></div>";
String json = mapper.writeValueAsString(Map.of(
"from", from, "to", new String[]{recipient}, "subject", SUBJECT,
"text", text, "html", html));
HttpRequest request = HttpRequest.newBuilder(ENDPOINT)
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(12))
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
// Тело ошибки не выводим: нельзя логировать email или токен провайдера.
HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
if (response.statusCode() < 200 || response.statusCode() >= 300)
throw new IllegalStateException("Resend delivery rejected (HTTP " + response.statusCode() + ")");
}
}
@@ -0,0 +1,184 @@
package server.archive.registration;
import shine.db.DbController;
import sync.util.Base58Util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Base64;
/** Только верифицированный сертификат. Локальная БД — проекция Arweave/Solana. */
public final class VerifiedFreeRegistrationImporter {
public enum Provenance { TURBO_ACCEPTED, ARWEAVE_CONFIRMED }
public record ImportResult(String login, String dataItemId, boolean alreadyImported, Provenance provenance) {}
private final boolean allowEmailReuse;
public VerifiedFreeRegistrationImporter() {
this(false);
}
public VerifiedFreeRegistrationImporter(boolean allowEmailReuse) {
this.allowEmailReuse = allowEmailReuse;
}
/** Предварительная проверка ДО Turbo: не расходовать кредиты на чужую/битую запись. */
public FreeRegistrationCertificateV1.Verified validateForUpload(byte[] raw) throws Exception {
if (raw == null || raw.length < 200 || raw.length > 16_384)
throw new IllegalArgumentException("Invalid registration size");
blockchain.Ans104DataItem item = new blockchain.Ans104DataItem(raw);
String login = extractCanonicalLogin(item);
try (Connection c = DbController.getInstance().getConnection()) {
String namespace = login.substring(login.indexOf('@') + 1);
var cert = FreeRegistrationCertificateV1.verify(raw, readRegistrar(c, namespace, login));
try (PreparedStatement ps = c.prepareStatement(
"SELECT free_data_item_id FROM user_identity_current WHERE normalized_login=?")) {
ps.setString(1, login.toLowerCase(java.util.Locale.ROOT));
try (ResultSet rs = ps.executeQuery()) {
if (rs.next() && !cert.idBase64Url().equals(rs.getString(1)))
throw new IllegalArgumentException("Login is already registered");
}
}
if (!allowEmailReuse) {
try (PreparedStatement ps = c.prepareStatement(
"SELECT data_item_id FROM free_registration_certificate WHERE email_sha256=?")) {
ps.setBytes(1, cert.emailSha256());
try (ResultSet rs = ps.executeQuery()) {
if (rs.next() && !cert.idBase64Url().equals(rs.getString(1)))
throw new IllegalArgumentException("Email hash belongs to another account");
}
}
}
return cert;
}
}
/** Единая точка импорта: один и тот же raw ANS-104 из Turbo и Arweave. */
public ImportResult importSigned(byte[] raw, Provenance provenance) throws Exception {
if (raw == null || raw.length > 16_384 || raw.length < 200)
throw new IllegalArgumentException("Invalid registration data item size");
// Сначала разбираем/проверяем структурный контейнер, затем сверяем owner с on-chain namespace.
blockchain.Ans104DataItem item = new blockchain.Ans104DataItem(raw);
String login = extractCanonicalLogin(item);
String namespace = login.substring(login.indexOf('@') + 1);
try (Connection c = DbController.getInstance().getConnection()) {
boolean oldAutoCommit = c.getAutoCommit();
c.setAutoCommit(false);
try {
byte[] registrar = readRegistrar(c, namespace, login);
FreeRegistrationCertificateV1.Verified cert = FreeRegistrationCertificateV1.verify(raw, registrar);
String id = cert.idBase64Url();
String publication = provenance == Provenance.ARWEAVE_CONFIRMED ? "ARWEAVE_CONFIRMED" : "TURBO_ACCEPTED";
long now = System.currentTimeMillis();
// Защита от коллизий и двойного импорта: имя и email захвачены индексами UNIQUE.
try (PreparedStatement check = c.prepareStatement("""
SELECT f.raw_signed_data_item, f.publication_status, u.root_key, u.client_key,
u.blockchain_key FROM free_registration_certificate f
JOIN user_identity_current u ON u.login=f.login
WHERE f.data_item_id=? FOR UPDATE OF f
""")) {
check.setString(1, id);
try (ResultSet r = check.executeQuery()) {
if (r.next()) {
if (!Arrays.equals(raw, r.getBytes(1)))
throw new SQLException("DataItem id collision with different raw bytes");
if (!r.getString(3).equals(Base58Util.encode(cert.rootKey())) ||
!r.getString(4).equals(Base58Util.encode(cert.clientKey())) ||
!r.getString(5).equals(Base58Util.encode(cert.blockchainKey())))
throw new SQLException("Accepted identity keys conflict with certificate");
if (provenance == Provenance.ARWEAVE_CONFIRMED) {
try (PreparedStatement up = c.prepareStatement("""
UPDATE free_registration_certificate SET publication_status='ARWEAVE_CONFIRMED',last_seen_at_ms=?
WHERE data_item_id=?
""")) {
up.setLong(1, now); up.setString(2, id); up.executeUpdate();
}
}
c.commit();
return new ImportResult(login, id, true, provenance);
}
}
}
try (PreparedStatement insert = c.prepareStatement("""
INSERT INTO user_identity_current (
login, normalized_login, namespace, registration_source, registration_status,
solana_pda_address, free_data_item_id, root_key, client_key, blockchain_key,
blockchain_name, is_server, registered_at_ms, updated_at_ms)
VALUES (?, ?, ?, 'ARWEAVE', 'FREE_CERT', NULL, ?, ?, ?, ?, ?, false, ?, ?)
""")) {
insert.setString(1, login); insert.setString(2, login.toLowerCase(java.util.Locale.ROOT)); insert.setString(3, namespace);
insert.setString(4, id); insert.setString(5, Base58Util.encode(cert.rootKey()));
insert.setString(6, Base58Util.encode(cert.clientKey()));
insert.setString(7, Base58Util.encode(cert.blockchainKey()));
insert.setString(8, login.toLowerCase(java.util.Locale.ROOT) + "-001"); insert.setLong(9, now); insert.setLong(10, now);
insert.executeUpdate();
}
// blockchain_state — обязательная runtime-проекция новой цепочки.
// Без неё первый пользовательский AddBlock (например, «О себе») будет
// отклонён ещё до проверки подписи.
try (PreparedStatement insert = c.prepareStatement("""
INSERT INTO blockchain_state_store (
login, fork_number, blockchain_key, size_limit, file_size_bytes,
last_block_number, last_block_hash, updated_at_ms)
VALUES (?, 1, ?, 100000, 0, -1, ?, ?)
""")) {
insert.setString(1, login);
// blockchain_state — runtime-слой: его ключ всегда Base64(32),
// как и у пользователей, импортированных из Solana PDA.
insert.setString(2, Base64.getEncoder().encodeToString(cert.blockchainKey()));
insert.setBytes(3, new byte[32]);
insert.setLong(4, now);
insert.executeUpdate();
}
try (PreparedStatement insert = c.prepareStatement("""
INSERT INTO free_registration_certificate (
data_item_id, login, namespace, email_sha256, inner_signature,
raw_signed_data_item, publication_status, registered_at_ms, last_seen_at_ms)
VALUES (?,?,?,?,?,?,?,?,?)
""")) {
insert.setString(1, id); insert.setString(2, login); insert.setString(3, namespace);
insert.setBytes(4, cert.emailSha256()); insert.setBytes(5, cert.innerSignature());
insert.setBytes(6, raw); insert.setString(7, publication);
insert.setLong(8, now); insert.setLong(9, now); insert.executeUpdate();
}
c.commit();
return new ImportResult(login, id, false, provenance);
} catch (Exception e) {
c.rollback(); throw e;
} finally { c.setAutoCommit(oldAutoCommit); }
}
}
private static String extractCanonicalLogin(blockchain.Ans104DataItem item) {
boolean marker = item.tags().contains(new blockchain.Ans104DataItem.Tag("t", "reg"));
if (!marker) throw new IllegalArgumentException("Not a registration DataItem");
byte[] bytes = item.data();
if (bytes.length < 3 || bytes[0] != 1 || bytes[1] != 0) throw new IllegalArgumentException("Bad certificate header");
int len = bytes[2] & 0xff;
if (len < 3 || len > 30 || bytes.length < 3 + len + 96 + 64 + 32)
throw new IllegalArgumentException("Invalid certificate login length");
return FreeRegistrationCertificateV1.validateLogin(
new String(bytes, 3, len, java.nio.charset.StandardCharsets.UTF_8));
}
private static byte[] readRegistrar(Connection c, String namespace, String login) throws Exception {
try (PreparedStatement ps = c.prepareStatement("""
SELECT registrar_pubkey, min_localpart_len, default_server_login
FROM shine_namespace_current WHERE namespace=? AND namespace_type=2
""")) {
ps.setString(1, namespace);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) throw new IllegalStateException("Unknown/free namespace not yet synchronized");
if (login.indexOf('@') < rs.getInt("min_localpart_len"))
throw new IllegalArgumentException("Login shorter than namespace minimum");
if (rs.getString("default_server_login") == null || rs.getString("default_server_login").isBlank())
throw new IllegalArgumentException("Namespace has no access server");
byte[] key = Base58Util.decode(rs.getString("registrar_pubkey"));
if (key.length != 32) throw new IllegalArgumentException("Invalid registrar pubkey");
return key;
}
}
}
}
@@ -0,0 +1 @@
0200a9de19b3551ace117973b80d632503bf2a55f0aa2490deb1474a280b675fa01bb2ccb5890faadcb213d3882fb21a7af13702526a569f7807b1c8b6963c0be402174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd500000300000000000000390000000000000006064170701074657374353539310274067265671050726f746f636f6c345348694e452d467265652d526567697374726174696f6e2d563100010008626f62406672656503a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b829acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd72543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559de2edfcd8b1b7a1823f56b827ddfa8a3682793e036141b526467ae346e220d08757d0a878a2f722562e6d3132ef9df04b1ab9e2f65d72bb0f48c17b7ada3e5a0acbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956
@@ -0,0 +1,43 @@
package server.archive;
import server.archive.registration.*;
import blockchain.Ans104DataItem;
import blockchain.ShineProtocolTags;
import utils.crypto.Ed25519Util;
import java.util.Arrays;
import java.util.HexFormat;
/** Standalone test (no legacy signed fixture): certificate issue/verify for CURRENT App tag. */
public final class FreeRegistrationCertificateV1Check {
static final HexFormat HEX = HexFormat.of();
public static void main(String[] args) throws Exception {
byte[] seed = Ed25519Util.generatePrivateKeyFromString("TEST-only-reg-v1-check");
byte[] root = HEX.parseHex("03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8");
byte[] chain = HEX.parseHex("29acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd7");
byte[] client = HEX.parseHex("2543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559d");
try (var signer = new LocalRegistrarSigner(seed)) {
byte[] cert = FreeRegistrationCertificateV1.issue("SuperMan@free", root, chain, client,
" Alice.Example+Tag@Example.COM ", signer);
var item = new Ans104DataItem(cert);
if (!item.hasTag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE))
throw new AssertionError("Current App tag missing");
var result = FreeRegistrationCertificateV1.verify(cert, signer.publicKey32());
if (!"SuperMan@free".equals(result.login()) || !Arrays.equals(result.rootKey(), root)
|| !Arrays.equals(result.blockchainKey(), chain) || !Arrays.equals(result.clientKey(), client))
throw new AssertionError("Certificate identity corrupted");
if (!Arrays.equals(result.emailSha256(), HEX.parseHex(
"cbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956")))
throw new AssertionError("Email normalization differs");
byte[] bad = cert.clone(); bad[bad.length - 1] ^= 1;
try { FreeRegistrationCertificateV1.verify(bad, signer.publicKey32());
throw new AssertionError("Email bit flip accepted"); }
catch (IllegalArgumentException expected) {}
bad = cert.clone(); bad[bad.length - 40] ^= 1;
try { FreeRegistrationCertificateV1.verify(bad, signer.publicKey32());
throw new AssertionError("Inner signature tampering accepted"); }
catch (IllegalArgumentException expected) {}
}
System.out.println("PASS: current App=" + ShineProtocolTags.APP_TAG_VALUE
+ ", Java registrar inner+outer Ed25519, original case, email, tamper rejection");
}
}
@@ -0,0 +1,41 @@
package server.archive;
import server.archive.registration.*;
import javax.sql.DataSource;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HexFormat;
/** Только проверки без БД/сети; полное E2E требует PostgreSQL и Turbo. */
public final class FreeRegistrationWorkflowLocalCheck {
public static void main(String[] args) throws Exception {
var signer = new RegistrarSigner() {
public byte[] publicKey32() { return new byte[32]; }
public byte[] sign(byte[] message) { return new byte[64]; }
};
DataSource noDb = new DataSource() {
public java.sql.Connection getConnection() throws java.sql.SQLException { throw new java.sql.SQLException("No database in local test"); }
public java.sql.Connection getConnection(String u, String p) throws java.sql.SQLException { return getConnection(); }
public java.io.PrintWriter getLogWriter() {return null;}
public void setLogWriter(java.io.PrintWriter x) {}
public void setLoginTimeout(int x) {}
public int getLoginTimeout() {return 0;}
public java.util.logging.Logger getParentLogger() {return java.util.logging.Logger.getAnonymousLogger();}
public <T> T unwrap(Class<T> iface) throws java.sql.SQLException {throw new java.sql.SQLException("unsupported");}
public boolean isWrapperFor(Class<?> iface) {return false;}
};
var issuer = new FreeRegistrationIssuer(noDb, signer);
var importer = new VerifiedFreeRegistrationImporter();
var workflow = new FreeRegistrationWorkflow(issuer,
new FreeRegistrationPublisher(issuer, new TurboDataItemUploader(ArweaveBlocksConfig.load()), importer),
(email, code) -> { throw new AssertionError("No real email in an offline check"); },
false, false, AllowedEmailDomains.load(Files.isRegularFile(Path.of("allowed-email-domains.txt"))
? Path.of("allowed-email-domains.txt") : Path.of("../allowed-email-domains.txt")));
try { workflow.confirm("unknown", "123456"); throw new AssertionError("Missing challenge accepted"); }
catch (IllegalArgumentException expected) { }
try { importer.importSigned(new byte[]{1,2,3}, VerifiedFreeRegistrationImporter.Provenance.TURBO_ACCEPTED);
throw new AssertionError("Invalid bytes accepted"); }
catch (IllegalArgumentException expected) { }
System.out.println("PASS: workflow missing challenge + reject invalid signed bytes");
}
}
@@ -0,0 +1,47 @@
package server.archive.registration;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
/** Самостоятельный офлайн-тест: javac AllowedEmailDomains.java AllowedEmailDomainsCheck.java + java. */
public final class AllowedEmailDomainsCheck {
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("shine-email-domains-test-");
try {
Path file = dir.resolve("allowed-email-domains.txt");
Files.writeString(file, "# Test\n Gmail.com \nproton.me\n\n", StandardCharsets.UTF_8);
AllowedEmailDomains allowed = AllowedEmailDomains.load(file);
expect(allowed.permits("User@GMAIL.COM"), "case insensitive match");
expect(allowed.permits(" user@proton.me "), "trimmed match");
expect(!allowed.permits("user@gmail.com.evil.org"), "suffix bypass");
expect(!allowed.permits("user@sub.gmail.com"), "subdomain bypass");
expect(!allowed.permits("user@other.com"), "unknown domain");
expect(!allowed.permits("user@@gmail.com"), "invalid multiple @");
expect(!allowed.permits("@gmail.com"), "missing local part");
expect(!allowed.permits(null), "null address");
Files.writeString(file, "# no domains\n \n", StandardCharsets.UTF_8);
expectLoadFailure(file, "empty file");
Files.writeString(file, "*.gmail.com\n", StandardCharsets.UTF_8);
expectLoadFailure(file, "wildcard not allowed");
Files.writeString(file, "gmail.com\ninvalid_domain\n", StandardCharsets.UTF_8);
expectLoadFailure(file, "invalid line not ignored");
Files.delete(file);
expectLoadFailure(file, "missing file");
System.out.println("PASS: allowed email domains, strict matching, fail-closed");
} finally {
try (var files = Files.list(dir)) { files.forEach(path -> {try {Files.deleteIfExists(path);}catch(Exception ex){throw new RuntimeException(ex);}}); }
Files.deleteIfExists(dir);
}
}
private static void expect(boolean condition, String scenario) {
if (!condition) throw new AssertionError(scenario);
}
private static void expectLoadFailure(Path file, String scenario) throws Exception {
try {
AllowedEmailDomains.load(file);
throw new AssertionError("Invalid allowlist accepted: " + scenario);
} catch (java.io.IOException expected) { }
}
}
@@ -0,0 +1,17 @@
package server.archive.registration;
/** Локальная проверка генератора и сверки кода без БД/HTTP. */
public final class RegistrationEmailCodeCheck {
public static void main(String[] args) {
for (int i=0; i<1000; ++i) {
String code = RegistrationEmailCode.generate();
if (!code.matches("[0-9]{6}")) throw new AssertionError("Wrong length");
byte[] hash = RegistrationEmailCode.hash("challenge-id", code);
if (!RegistrationEmailCode.matches(hash, "challenge-id", code)) throw new AssertionError("Cannot verify");
if (RegistrationEmailCode.matches(hash, "another-challenge", code)) throw new AssertionError("Challenge replay");
if (RegistrationEmailCode.matches(hash, "challenge-id", "1111")) throw new AssertionError("Old demo code accepted");
if (RegistrationEmailCode.matches(hash, "challenge-id", "bad")) throw new AssertionError("Bad code accepted");
}
System.out.println("PASS: email code generation and challenge binding");
}
}
@@ -0,0 +1,21 @@
package server.archive.registration;
/** Offline проверка часового TTL на уровне UX отдельно; bypass должен быть строго opt-in. */
public final class RegistrationEmailSettingsCheck {
public static void main(String[] args) {
byte[] digest = RegistrationEmailCode.hash("challenge", "123456");
var safe = new FreeRegistrationWorkflow(null, null, null, false);
var test = new FreeRegistrationWorkflow(null, null, null, true);
if (safe.isValidVerificationCode(digest, "challenge", "777777"))
throw new AssertionError("Cheat unexpectedly enabled by default");
if (!test.isValidVerificationCode(digest, "challenge", "777777"))
throw new AssertionError("Explicit test code not accepted");
if (!safe.isValidVerificationCode(digest, "challenge", "123456"))
throw new AssertionError("Real code rejected");
if (test.isValidVerificationCode(digest, "challenge", "1111"))
throw new AssertionError("Old demo code unexpectedly accepted");
if (test.isValidVerificationCode(digest, "challenge", "777778"))
throw new AssertionError("Invalid code unexpectedly accepted");
System.out.println("PASS: real code and opt-in test code");
}
}
@@ -9,7 +9,7 @@ package blockchain;
public final class ShineProtocolTags {
private ShineProtocolTags() {}
public static final String NAMESPACE = "test5591";
public static final String NAMESPACE = "test5592";
public static final String APP_TAG_NAME = "App";
public static final String APP_TAG_VALUE = NAMESPACE;
public static final String CHANNEL_TAG_NAME = "c";
@@ -78,8 +78,14 @@ public final class HeaderBody implements BodyRecord {
public HeaderBody check() {
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
if (login == null || login.isBlank()) throw new IllegalArgumentException("Login is blank");
if (!login.matches("^[A-Za-z0-9_]+$")) throw new IllegalArgumentException("Login must match ^[A-Za-z0-9_]+$");
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
// В HEADER хранится неизменяемое написание зарегистрированного login@namespace.
// Namespace остаётся lowercase, регистр локальной части сохраняется байт-в-байт.
boolean legacyLogin = login.matches("^[A-Za-z0-9_]+$");
boolean namespacedLogin = loginUtf8.length <= 30 && login.matches("^[A-Za-z0-9_]+@[a-z0-9_]+$");
if (!legacyLogin && !namespacedLogin) {
throw new IllegalArgumentException("Login must be legacy [A-Za-z0-9_]+ or registered-case login@namespace (max 30 bytes)");
}
if (loginUtf8.length == 0 || loginUtf8.length > 255) throw new IllegalArgumentException("Login utf8 len must be 1..255");
requireNonZeroKey(initialBlockchainKey32);
return this;
@@ -98,6 +98,38 @@ final class TargetLoginFormatTest {
assertArrayEquals(INITIAL_KEY, parsed.initialBlockchainKey32);
}
@Test
void namespacedHeaderRoundTripAcceptsPaidAndFreeUsers() {
for (String login : new String[]{"alice@free", "AlexSmith@shine", "a_B@free", "abcdefghijklmnopqrstuvwxy@free"}) {
HeaderBody source = new HeaderBody(login, INITIAL_KEY);
HeaderBody parsed = new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER, source.toBytes()).check();
assertEquals(login, parsed.login);
assertArrayEquals(INITIAL_KEY, parsed.initialBlockchainKey32);
}
}
@Test
void namespacedHeaderRejectsMalformedOrOversizedLogin() {
for (String login : new String[]{"alice@", "@shine", "alice@@free", "alice@FREE", "alice.free@shine", "abcdefghijklmnopqrstuvwxyz@free"}) {
assertThrows(IllegalArgumentException.class, () -> new HeaderBody(login, INITIAL_KEY), login);
}
}
@Test
void signedReferencesPreserveArbitraryLoginCaseWithoutServerSideCaseEnforcement() {
// Адресация не зависит от регистра, но блок сохраняет выбранные автором байты.
for (String login : new String[]{"AlexSmith@shine", "alexsmith@shine"}) {
TextReplyBody reply = new TextReplyBody(MsgSubType.TEXT_REPLY, login, 1, 42, HASH, "тест");
assertEquals(login, new TextReplyBody(MsgSubType.TEXT_REPLY, TextReplyBody.VER, reply.toBytes()).check().toLogin());
ReactionBody like = new ReactionBody(MsgSubType.REACTION_LIKE, login, 1, 42, HASH);
assertEquals(login, new ReactionBody(MsgSubType.REACTION_LIKE, ReactionBody.VER, like.toBytes()).check().toLogin());
ConnectionBody follow = new ConnectionBody(0, HASH, 1, MsgSubType.CONNECTION_FOLLOW, login, 1, 0, HASH);
assertEquals(login, new ConnectionBody(MsgSubType.CONNECTION_FOLLOW, ConnectionBody.VER, follow.toBytes()).check().toLogin());
}
}
private static byte[] hash(int seed) {
byte[] out = new byte[32];
Arrays.fill(out, (byte) seed);
@@ -23,9 +23,23 @@ public final class DatabaseInitializer {
public static final int SCHEMA_VERSION_1 = 1;
public static final int SCHEMA_VERSION_31 = 31;
public static final int SCHEMA_VERSION_32 = 32;
public static final int SCHEMA_VERSION_33 = 33;
public static final int SCHEMA_VERSION_34 = 34;
public static final int SCHEMA_VERSION_35 = 35;
public static final int SCHEMA_VERSION_36 = 36;
public static final int SCHEMA_VERSION_37 = 37;
public static final int SCHEMA_VERSION_38 = 38;
public static final int SCHEMA_VERSION_39 = 39;
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql";
public static final String POSTGRES_MIGRATION_V33_RESOURCE = "postgres/migration_v33.sql";
public static final String POSTGRES_MIGRATION_V34_RESOURCE = "postgres/migration_v34.sql";
public static final String POSTGRES_MIGRATION_V35_RESOURCE = "postgres/migration_v35.sql";
public static final String POSTGRES_MIGRATION_V36_RESOURCE = "postgres/migration_v36.sql";
public static final String POSTGRES_MIGRATION_V37_RESOURCE = "postgres/migration_v37.sql";
public static final String POSTGRES_MIGRATION_V38_RESOURCE = "postgres/migration_v38.sql";
public static final String POSTGRES_MIGRATION_V39_RESOURCE = "postgres/migration_v39.sql";
private DatabaseInitializer() {}
@@ -125,10 +139,39 @@ public final class DatabaseInitializer {
runSqlScript(conn, POSTGRES_MIGRATION_V32_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion != SCHEMA_VERSION_32) {
throw new SQLException(
"Unsupported SHiNE DB v2 schema version: expected 32, found " + currentVersion);
if (currentVersion == SCHEMA_VERSION_32) {
runSqlScript(conn, POSTGRES_MIGRATION_V33_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_33) {
runSqlScript(conn, POSTGRES_MIGRATION_V34_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_34) {
runSqlScript(conn, POSTGRES_MIGRATION_V35_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_35) {
runSqlScript(conn, POSTGRES_MIGRATION_V36_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_36) {
runSqlScript(conn, POSTGRES_MIGRATION_V37_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_37) {
runSqlScript(conn, POSTGRES_MIGRATION_V38_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_38) {
runSqlScript(conn, POSTGRES_MIGRATION_V39_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion != SCHEMA_VERSION_39) {
throw new SQLException(
"Unsupported SHiNE DB v2 schema version: expected 39, found " + currentVersion);
}
normalizeBlockchainStateKeysToBase64(conn);
}
}
@@ -208,6 +251,38 @@ public final class DatabaseInitializer {
}
}
/**
* blockchain_state — runtime-проекция: публичный blockchain key хранится
* строго как Base64(32). Ранний импорт free-регистраций ошибочно сохранял
* Base58, поэтому нормализация выполняется идемпотентно при старте.
*/
private static void normalizeBlockchainStateKeysToBase64(Connection conn) throws SQLException {
record StateKey(String login, int forkNumber, String key) {}
List<StateKey> entries = new ArrayList<>();
try (Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT login, fork_number, blockchain_key FROM blockchain_state_store")) {
while (rs.next()) {
entries.add(new StateKey(rs.getString("login"), rs.getInt("fork_number"), rs.getString("blockchain_key")));
}
}
try (var update = conn.prepareStatement("""
UPDATE blockchain_state_store
SET blockchain_key = ?
WHERE login = ? AND fork_number = ?
""")) {
for (StateKey entry : entries) {
String normalized = KeyEncodingUtil.normalizeKeyToBase64_32(entry.key());
if (normalized == null || normalized.equals(entry.key())) continue;
update.setString(1, normalized);
update.setString(2, entry.login());
update.setInt(3, entry.forkNumber());
update.addBatch();
}
update.executeBatch();
}
}
private static void runSqlScript(Connection conn, String resourcePath) throws SQLException {
String sqlScript = loadClasspathResource(resourcePath);
List<String> statements = splitSqlStatements(sqlScript);
@@ -43,7 +43,7 @@ public final class BlockchainStateDAO {
last_block_hash,
updated_at_ms
FROM blockchain_state
WHERE login = ? AND fork_number = ?
WHERE LOWER(login) = LOWER(?) AND fork_number = ?
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -197,7 +197,7 @@ public final class BlockchainStateDAO {
file_size_bytes = file_size_bytes + ?,
updated_at_ms = ?
WHERE
login = ? AND fork_number = ?
LOWER(login) = LOWER(?) AND fork_number = ?
AND (file_size_bytes + ?) <= size_limit
""";
@@ -164,9 +164,9 @@ public final class ConnectionsStateDAO {
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, login);
ps.setString(1, login.trim().toLowerCase(java.util.Locale.ROOT));
ps.setInt(2, relType);
ps.setString(3, toLogin);
ps.setString(3, toLogin.trim().toLowerCase(java.util.Locale.ROOT));
if (toBlockNumber == null) ps.setNull(4, java.sql.Types.INTEGER); else ps.setInt(4, toBlockNumber);
ps.setBytes(5, toBlockHash);
ps.executeUpdate();
@@ -213,7 +213,7 @@ public final class CurrentUsersDAO {
String sql = """
SELECT su.login, coalesce(up.first_name, '') AS first_name,
coalesce(up.last_name, '') AS last_name, coalesce(up.ava_ar, '') AS ava_ar
FROM solana_user_pda_current su
FROM user_identity_current su
LEFT JOIN user_profile_state up ON lower(up.login) = lower(su.login)
WHERE (? IS NULL OR su.is_server = ?)
AND (
@@ -1,5 +1,6 @@
package shine.db.dao;
import shine.db.DbController;
import shine.db.MsgSubType;
import shine.db.entities.SignedMessageEntry;
@@ -17,6 +18,7 @@ import java.util.Map;
public final class DmDialogStateDAO {
private static volatile DmDialogStateDAO instance;
private final DbController db = DbController.getInstance();
private DmDialogStateDAO() {}
@@ -129,6 +131,26 @@ public final class DmDialogStateDAO {
return out;
}
/** Снимок счётчика после записи DM. Используется только сервером для push/WS, не отдаёт текст сообщения. */
public NotificationState getNotificationState(String ownerLogin, String peerLogin) throws SQLException {
try (Connection c = db.getConnection();
PreparedStatement ps = c.prepareStatement("""
SELECT unread_count, updated_at_ms
FROM dm_dialog_state
WHERE LOWER(owner_login) = LOWER(?) AND LOWER(peer_login) = LOWER(?)
LIMIT 1
""")) {
ps.setString(1, normalize(ownerLogin));
ps.setString(2, normalize(peerLogin));
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) return null;
return new NotificationState(Math.max(0, rs.getInt("unread_count")), rs.getLong("updated_at_ms"));
}
}
}
public record NotificationState(int unreadCount, long versionMs) {}
public void refreshFromEntry(Connection c, SignedMessageEntry entry) throws SQLException {
if (entry == null) return;
refreshConversationPair(c, entry.getFromLogin(), entry.getToLogin());
@@ -274,7 +296,7 @@ public final class DmDialogStateDAO {
last_message_time_ms = EXCLUDED.last_message_time_ms,
unread_count = EXCLUDED.unread_count,
last_read_receipt_time_ms = EXCLUDED.last_read_receipt_time_ms,
updated_at_ms = EXCLUDED.updated_at_ms
updated_at_ms = GREATEST(dm_dialog_state.updated_at_ms + 1, EXCLUDED.updated_at_ms)
""")) {
ps.setString(1, summary.ownerLogin());
ps.setString(2, summary.peerLogin());
@@ -0,0 +1,58 @@
package shine.db.dao;
import shine.db.DbController;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/** Единая авторитетная проекция: FREE_CERT не притворяется Solana PDA. */
public final class RegistrationIdentityDAO {
public record ResolvedIdentity(String fullLogin, String rootKey, String blockchainKey,
String clientKey, String registrationSource, String registrationStatus,
String namespace, String accessServerLogin, boolean hasSolanaPda) {
public boolean isFree() { return "FREE_CERT".equals(registrationStatus); }
}
private static final RegistrationIdentityDAO INSTANCE = new RegistrationIdentityDAO();
public static RegistrationIdentityDAO getInstance() { return INSTANCE; }
private RegistrationIdentityDAO() {}
public ResolvedIdentity get(String login) throws SQLException {
try (Connection c = DbController.getInstance().getConnection()) { return get(c, login); }
}
public ResolvedIdentity get(Connection c, String login) throws SQLException {
if (login == null || login.isBlank()) return null;
try (PreparedStatement ps = c.prepareStatement("""
SELECT i.login, i.root_key, i.blockchain_key, i.client_key,
i.registration_source, i.registration_status, i.namespace,
i.solana_pda_address, n.default_server_login,
s.server_login AS actual_access_server
FROM user_identity_current i
LEFT JOIN shine_namespace_current n ON n.namespace=i.namespace
LEFT JOIN user_access_servers_current s ON s.user_login=i.login
WHERE i.normalized_login=LOWER(BTRIM(?))
ORDER BY s.server_login ASC
LIMIT 1
""")) {
ps.setString(1, login);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) return null;
boolean hasPda = rs.getString("solana_pda_address") != null;
String status = rs.getString("registration_status");
String server = "FREE_CERT".equals(status) ? rs.getString("default_server_login")
: rs.getString("actual_access_server");
if ("FREE_CERT".equals(status) && hasPda)
throw new SQLException("Inconsistent free user: Solana PDA must be absent");
if (!"FREE_CERT".equals(status) && !hasPda)
throw new SQLException("Inconsistent paid user: Solana PDA is missing");
return new ResolvedIdentity(rs.getString("login"), rs.getString("root_key"),
rs.getString("blockchain_key"), rs.getString("client_key"),
rs.getString("registration_source"), status, rs.getString("namespace"), server, hasPda);
}
}
}
public boolean isFreeCertificate(String login) throws SQLException {
ResolvedIdentity identity = get(login);
return identity != null && identity.isFree();
}
}
@@ -111,7 +111,7 @@ public final class SubscriptionsDAO {
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.login = ? AND cs.rel_type = ?
WHERE LOWER(cs.login) = LOWER(?) AND cs.rel_type = ?
UNION
@@ -46,26 +46,28 @@ public final class UserAccessServersCurrentDAO {
public UserAccessServerRouteEntry findPrimaryByUserLogin(String userLogin) throws SQLException {
String sql = """
SELECT
u.login AS user_login,
i.login AS user_login,
s.login AS server_login,
s.server_address AS server_url,
s.client_key AS server_client_key
FROM solana_user_pda_current u
FROM user_identity_current i
LEFT JOIN solana_user_pda_current u ON u.login = i.login
LEFT JOIN shine_namespace_current ns ON ns.namespace = i.namespace
CROSS JOIN LATERAL (
SELECT BTRIM(a.login_value) AS server_login
FROM jsonb_array_elements_text(
CASE
WHEN BTRIM(COALESCE(u.access_servers_json, '')) = '' THEN '[]'::jsonb
ELSE u.access_servers_json::jsonb
END
) WITH ORDINALITY AS a(login_value, ord)
WHERE a.ord = 1
SELECT CASE WHEN i.registration_status = 'FREE_CERT'
THEN ns.default_server_login
ELSE (SELECT BTRIM(a.login_value)
FROM jsonb_array_elements_text(
COALESCE(NULLIF(u.access_servers_json, ''), '[]')::jsonb)
WITH ORDINALITY AS a(login_value, ord)
WHERE a.ord = 1)
END AS server_login
) primary_access
JOIN solana_user_pda_current s
ON s.normalized_login = LOWER(primary_access.server_login)
AND s.is_server = TRUE
AND BTRIM(COALESCE(s.server_address, '')) <> ''
WHERE u.normalized_login = LOWER(BTRIM(?))
WHERE i.normalized_login = LOWER(BTRIM(?))
LIMIT 1
""";
try (Connection c = db.getConnection();
@@ -18,7 +18,7 @@ public final class CurrentUsersSql {
current_users.blockchain_key AS blockchain_key,
current_users.client_key AS client_key,
current_users.is_server AS is_server
FROM solana_user_pda_current current_users
FROM user_identity_current current_users
) %s
""".formatted(alias);
}
@@ -0,0 +1,213 @@
-- SHiNE DB v33: общий индекс идентичностей, namespace и сертификаты.
-- ТОЛЬКО dev/test до проверки всей серверной авторизации.
BEGIN;
CREATE TABLE user_identity_current (
login TEXT PRIMARY KEY,
normalized_login TEXT NOT NULL UNIQUE,
namespace TEXT,
registration_source TEXT NOT NULL CHECK (registration_source IN ('SOLANA', 'ARWEAVE')),
registration_status TEXT NOT NULL CHECK (registration_status IN ('PAID_DIRECT', 'FREE_CERT', 'PAID_UPGRADED')),
solana_pda_address TEXT UNIQUE,
free_data_item_id TEXT UNIQUE,
root_key TEXT NOT NULL,
client_key TEXT NOT NULL,
blockchain_key TEXT NOT NULL,
blockchain_name TEXT NOT NULL,
is_server BOOLEAN NOT NULL DEFAULT FALSE,
registered_at_ms BIGINT NOT NULL,
updated_at_ms BIGINT NOT NULL,
CHECK ((registration_status = 'FREE_CERT' AND solana_pda_address IS NULL AND free_data_item_id IS NOT NULL)
OR (registration_status <> 'FREE_CERT' AND solana_pda_address IS NOT NULL))
);
CREATE INDEX idx_user_identity_namespace ON user_identity_current(namespace);
INSERT INTO user_identity_current (
login, normalized_login, namespace, registration_source, registration_status,
solana_pda_address, root_key, client_key, blockchain_key, blockchain_name,
is_server, registered_at_ms, updated_at_ms
)
SELECT login, normalized_login,
CASE WHEN position('@' in login) > 0 THEN split_part(login, '@', 2) ELSE NULL END,
'SOLANA', 'PAID_DIRECT', pda_address, root_key, client_key, blockchain_key,
blockchain_name, is_server, created_at_ms, updated_at_ms
FROM solana_user_pda_current
ON CONFLICT (login) DO NOTHING;
CREATE TABLE shine_namespace_current (
namespace TEXT PRIMARY KEY,
pda_address TEXT NOT NULL UNIQUE,
namespace_type SMALLINT NOT NULL CHECK(namespace_type IN (1,2)),
min_localpart_len SMALLINT NOT NULL CHECK (min_localpart_len BETWEEN 1 AND 30),
registration_fee_lamports NUMERIC(20,0) NOT NULL CHECK (registration_fee_lamports >= 0),
registrar_pubkey TEXT,
default_server_login TEXT,
slot BIGINT NOT NULL,
last_tx_signature TEXT NOT NULL DEFAULT '',
raw_data_base64 TEXT NOT NULL,
CHECK ((namespace_type = 1 AND registrar_pubkey IS NULL AND default_server_login IS NULL)
OR (namespace_type = 2 AND registrar_pubkey IS NOT NULL AND default_server_login IS NOT NULL))
);
CREATE TABLE free_registration_certificate (
data_item_id TEXT PRIMARY KEY,
login TEXT NOT NULL UNIQUE REFERENCES user_identity_current(login),
namespace TEXT NOT NULL REFERENCES shine_namespace_current(namespace),
email_sha256 BYTEA NOT NULL UNIQUE CHECK (octet_length(email_sha256) = 32),
inner_signature BYTEA NOT NULL CHECK (octet_length(inner_signature) = 64),
raw_signed_data_item BYTEA NOT NULL,
publication_status TEXT NOT NULL CHECK (publication_status IN ('TURBO_ACCEPTED','ARWEAVE_SEEN','ARWEAVE_CONFIRMED')),
registered_at_ms BIGINT NOT NULL,
last_seen_at_ms BIGINT NOT NULL
);
CREATE INDEX idx_free_registration_namespace ON free_registration_certificate(namespace);
-- Существующие объекты (в том числе десятки FK) должны ссылаться на логическую
-- идентичность, иначе бесплатный пользователь не сможет иметь профиль/связи/каналы.
-- Воссоздаём существующие FK с теми же ON DELETE/UPDATE и deferrable-настройками.
DO $$
DECLARE
item RECORD;
definition TEXT;
BEGIN
FOR item IN SELECT c.conname, c.conrelid::regclass AS child_table,
pg_get_constraintdef(c.oid) AS definition
FROM pg_constraint c
WHERE c.contype = 'f' AND c.confrelid = 'solana_user_pda_current'::regclass
LOOP
definition := replace(item.definition,
'REFERENCES solana_user_pda_current(', 'REFERENCES user_identity_current(');
IF definition = item.definition THEN
RAISE EXCEPTION 'Unexpected FK expression: %', item.definition;
END IF;
EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I', item.child_table, item.conname);
EXECUTE format('ALTER TABLE %s ADD CONSTRAINT %I %s', item.child_table, item.conname, definition);
END LOOP;
END $$;
-- Любое поступившее из Solana состояние дополняет существующую идентичность.
-- Бесплатный → платный допускается ТОЛЬКО при совпадении всех публичных ключей;
-- старые on-chain key rotations разрешены, если статус уже платный.
CREATE OR REPLACE FUNCTION shine_sync_identity_from_solana()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
DECLARE old_user user_identity_current%ROWTYPE;
BEGIN
-- Если PostgreSQL получил старую запись из replay, она не должна затереть
-- уже принятую более новую логическую идентичность в BEFORE INSERT.
IF TG_OP = 'INSERT' AND EXISTS (
SELECT 1 FROM solana_user_pda_current prior
WHERE prior.pda_address = NEW.pda_address AND prior.record_number > NEW.record_number
) THEN
RETURN NEW;
END IF;
SELECT * INTO old_user FROM user_identity_current
WHERE normalized_login = NEW.normalized_login FOR UPDATE;
IF FOUND AND old_user.registration_status = 'FREE_CERT' AND
(old_user.root_key <> NEW.root_key OR old_user.client_key <> NEW.client_key OR old_user.blockchain_key <> NEW.blockchain_key) THEN
RAISE EXCEPTION 'Free certificate keys differ from Solana upgrade for %', NEW.login;
END IF;
IF FOUND AND old_user.solana_pda_address IS NOT NULL AND old_user.solana_pda_address <> NEW.pda_address THEN
RAISE EXCEPTION 'Duplicate on-chain identity for %', NEW.login;
END IF;
INSERT INTO user_identity_current (
login, normalized_login, namespace, registration_source, registration_status,
solana_pda_address, free_data_item_id, root_key, client_key, blockchain_key,
blockchain_name, is_server, registered_at_ms, updated_at_ms)
VALUES (NEW.login, NEW.normalized_login,
CASE WHEN position('@' in NEW.login) > 0 THEN split_part(NEW.login,'@',2) ELSE NULL END,
'SOLANA', CASE WHEN old_user.free_data_item_id IS NOT NULL THEN 'PAID_UPGRADED' ELSE 'PAID_DIRECT' END,
NEW.pda_address, old_user.free_data_item_id, NEW.root_key, NEW.client_key,
NEW.blockchain_key, NEW.blockchain_name, NEW.is_server,
COALESCE(old_user.registered_at_ms, NEW.created_at_ms), NEW.updated_at_ms)
ON CONFLICT (login) DO UPDATE SET
registration_source='SOLANA',
registration_status=EXCLUDED.registration_status,
solana_pda_address=EXCLUDED.solana_pda_address,
root_key=EXCLUDED.root_key, client_key=EXCLUDED.client_key,
blockchain_key=EXCLUDED.blockchain_key, blockchain_name=EXCLUDED.blockchain_name,
is_server=EXCLUDED.is_server, updated_at_ms=EXCLUDED.updated_at_ms;
RETURN NEW;
END $$;
CREATE TRIGGER trg_sync_identity_from_solana
BEFORE INSERT OR UPDATE ON solana_user_pda_current
FOR EACH ROW EXECUTE FUNCTION shine_sync_identity_from_solana();
-- Free namespace: сервер доступа задаётся namespace, а не клиентским полем.
-- Реальный сервер должен иметь on-chain PDA и открытый адрес.
CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_for_user(p_user_login TEXT)
RETURNS VOID LANGUAGE plpgsql AS $$
BEGIN
IF p_user_login IS NULL OR btrim(p_user_login) = '' THEN RETURN; END IF;
DELETE FROM user_access_servers_current WHERE lower(user_login) = lower(p_user_login);
INSERT INTO user_access_servers_current (
user_login, server_login, server_url, server_client_key, user_record_number,
user_updated_at_ms, server_record_number, server_updated_at_ms, refreshed_at_ms)
SELECT i.login, srv.login, srv.server_address, srv.client_key,
COALESCE(u.record_number, 0), i.updated_at_ms,
srv.record_number, srv.updated_at_ms,
CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
FROM user_identity_current i
LEFT JOIN solana_user_pda_current u ON u.login = i.login
LEFT JOIN shine_namespace_current ns ON ns.namespace = i.namespace
CROSS JOIN LATERAL (
SELECT CASE WHEN i.registration_status = 'FREE_CERT' THEN ns.default_server_login
ELSE (SELECT value FROM jsonb_array_elements_text(
COALESCE(NULLIF(u.access_servers_json, ''), '[]')::jsonb)
WITH ORDINALITY AS a(value, position) WHERE position=1) END AS login
) effective
JOIN solana_user_pda_current srv
ON lower(srv.login) = lower(effective.login) AND srv.is_server = true
AND btrim(coalesce(srv.server_address, '')) <> ''
WHERE lower(i.login) = lower(p_user_login)
ON CONFLICT (user_login, server_login) DO UPDATE SET
server_url=EXCLUDED.server_url, server_client_key=EXCLUDED.server_client_key,
user_record_number=EXCLUDED.user_record_number,
user_updated_at_ms=EXCLUDED.user_updated_at_ms,
server_record_number=EXCLUDED.server_record_number,
server_updated_at_ms=EXCLUDED.server_updated_at_ms,
refreshed_at_ms=EXCLUDED.refreshed_at_ms;
END $$;
CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_for_server(p_server_login TEXT)
RETURNS VOID LANGUAGE plpgsql AS $$
DECLARE u RECORD;
BEGIN
IF p_server_login IS NULL OR btrim(p_server_login) = '' THEN RETURN; END IF;
DELETE FROM user_access_servers_current WHERE lower(server_login) = lower(p_server_login);
FOR u IN
SELECT i.login FROM user_identity_current i
LEFT JOIN solana_user_pda_current p ON p.login=i.login
LEFT JOIN shine_namespace_current ns ON ns.namespace=i.namespace
WHERE lower(p_server_login) = lower(
CASE WHEN i.registration_status='FREE_CERT' THEN ns.default_server_login
ELSE (SELECT value FROM jsonb_array_elements_text(
COALESCE(NULLIF(p.access_servers_json,''),'[]')::jsonb)
WITH ORDINALITY AS a(value, position) WHERE position=1) END)
LOOP PERFORM shine_refresh_user_access_servers_for_user(u.login); END LOOP;
END $$;
CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_all()
RETURNS VOID LANGUAGE plpgsql AS $$
DECLARE u RECORD;
BEGIN
TRUNCATE TABLE user_access_servers_current;
FOR u IN SELECT login FROM user_identity_current LOOP
PERFORM shine_refresh_user_access_servers_for_user(u.login);
END LOOP;
END $$;
CREATE OR REPLACE FUNCTION shine_refresh_free_routing_from_identity()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
IF NEW.registration_status = 'FREE_CERT' THEN
PERFORM shine_refresh_user_access_servers_for_user(NEW.login);
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER trg_refresh_free_routing_from_identity
AFTER INSERT OR UPDATE ON user_identity_current
FOR EACH ROW EXECUTE FUNCTION shine_refresh_free_routing_from_identity();
UPDATE db_schema_version SET schema_version=33,
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) WHERE id=1;
COMMIT;
@@ -0,0 +1,12 @@
-- SHiNE v34. Отдельный checkpoint Arweave сертификатов, не смешивать с блоками.
BEGIN;
CREATE TABLE IF NOT EXISTS free_registration_arweave_sync_state (
id SMALLINT PRIMARY KEY CHECK (id=1),
last_block_height BIGINT NOT NULL DEFAULT 0 CHECK (last_block_height>=0),
updated_at_ms BIGINT NOT NULL DEFAULT 0
);
INSERT INTO free_registration_arweave_sync_state (id,last_block_height,updated_at_ms)
VALUES (1,0,0) ON CONFLICT (id) DO NOTHING;
UPDATE db_schema_version SET schema_version=34,
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT) WHERE id=1;
COMMIT;
@@ -0,0 +1,62 @@
-- v35: один полноценный статус для всех зарегистрированных в Solana.
-- Старые регистрационные сертификаты Arweave и дата исходной регистрации сохраняются.
BEGIN;
-- Сначала снимаем старое ограничение, затем переводим существующие строки.
ALTER TABLE user_identity_current
DROP CONSTRAINT user_identity_current_registration_status_check;
UPDATE user_identity_current
SET registration_status = 'PAID'
WHERE registration_status IN ('PAID_DIRECT', 'PAID_UPGRADED');
ALTER TABLE user_identity_current
ADD CONSTRAINT user_identity_current_registration_status_check
CHECK (registration_status IN ('FREE_CERT', 'PAID'));
-- Важнее миграции существующих строк: при следующих Solana sync/upsert
-- и обычный платный, и ранее бесплатный пользователь получают тот же PAID.
CREATE OR REPLACE FUNCTION shine_sync_identity_from_solana()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
DECLARE old_user user_identity_current%ROWTYPE;
BEGIN
-- Если PostgreSQL получил старую запись из replay, она не должна затереть
-- уже принятую более новую логическую идентичность в BEFORE INSERT.
IF TG_OP = 'INSERT' AND EXISTS (
SELECT 1 FROM solana_user_pda_current prior
WHERE prior.pda_address = NEW.pda_address AND prior.record_number > NEW.record_number
) THEN
RETURN NEW;
END IF;
SELECT * INTO old_user FROM user_identity_current
WHERE normalized_login = NEW.normalized_login FOR UPDATE;
IF FOUND AND old_user.registration_status = 'FREE_CERT' AND
(old_user.root_key <> NEW.root_key OR old_user.client_key <> NEW.client_key OR old_user.blockchain_key <> NEW.blockchain_key) THEN
RAISE EXCEPTION 'Free certificate keys differ from Solana upgrade for %', NEW.login;
END IF;
IF FOUND AND old_user.solana_pda_address IS NOT NULL AND old_user.solana_pda_address <> NEW.pda_address THEN
RAISE EXCEPTION 'Duplicate on-chain identity for %', NEW.login;
END IF;
INSERT INTO user_identity_current (
login, normalized_login, namespace, registration_source, registration_status,
solana_pda_address, free_data_item_id, root_key, client_key, blockchain_key,
blockchain_name, is_server, registered_at_ms, updated_at_ms)
VALUES (NEW.login, NEW.normalized_login,
CASE WHEN position('@' in NEW.login) > 0 THEN split_part(NEW.login,'@',2) ELSE NULL END,
'SOLANA', 'PAID',
NEW.pda_address, old_user.free_data_item_id, NEW.root_key, NEW.client_key,
NEW.blockchain_key, NEW.blockchain_name, NEW.is_server,
COALESCE(old_user.registered_at_ms, NEW.created_at_ms), NEW.updated_at_ms)
ON CONFLICT (login) DO UPDATE SET
registration_source='SOLANA',
registration_status=EXCLUDED.registration_status,
solana_pda_address=EXCLUDED.solana_pda_address,
root_key=EXCLUDED.root_key, client_key=EXCLUDED.client_key,
blockchain_key=EXCLUDED.blockchain_key, blockchain_name=EXCLUDED.blockchain_name,
is_server=EXCLUDED.is_server, updated_at_ms=EXCLUDED.updated_at_ms;
RETURN NEW;
END $$;
UPDATE db_schema_version
SET schema_version=35,
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT)
WHERE id=1;
COMMIT;
@@ -0,0 +1,66 @@
-- v36: регистрационная запись хранит исходный регистр; все ссылки FK
-- приводятся к её точному login. Исторические строки не мигрируются.
-- На новой базе исходные имена PDA/сертификатов и FK согласованы.
BEGIN;
CREATE OR REPLACE FUNCTION shine_canonicalize_identity_fk_login()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
DECLARE
field_name TEXT := TG_ARGV[0];
requested_login TEXT;
canonical_login TEXT;
BEGIN
requested_login := to_jsonb(NEW)->>field_name;
IF requested_login IS NULL OR btrim(requested_login) = '' THEN
RETURN NEW;
END IF;
SELECT i.login INTO canonical_login
FROM user_identity_current i
WHERE i.normalized_login = lower(btrim(requested_login))
LIMIT 1;
IF canonical_login IS NOT NULL THEN
-- Меняем только проекцию/связь в SQL, никогда не байты подписанного блока.
NEW := jsonb_populate_record(NEW, jsonb_build_object(field_name, canonical_login));
END IF;
RETURN NEW;
END $$;
DO $$
DECLARE
tab_name TEXT;
col_name TEXT;
spec TEXT;
trigger_name TEXT;
BEGIN
FOREACH spec IN ARRAY ARRAY[
'user_access_servers_current:user_login',
'user_access_servers_current:server_login',
'active_sessions:login',
'esp_pairing_settings:login',
'esp_pairing_requests:login',
'users_params:login',
'user_settings:login',
'channel_read_state:viewer_login',
'test_free_avatar_uploads:login',
-- blockchain_state — compatibility view; trigger может существовать
-- только на физической таблице хранения.
'blockchain_state_store:login',
'user_stats_state:login',
'user_push_tokens:login',
'key_rotation_sessions:login'
] LOOP
tab_name := split_part(spec, ':', 1);
col_name := split_part(spec, ':', 2);
trigger_name := 'trg_canonical_identity_' || tab_name || '_' || col_name;
EXECUTE format('DROP TRIGGER IF EXISTS %I ON %I', trigger_name, tab_name);
EXECUTE format(
'CREATE TRIGGER %I BEFORE INSERT OR UPDATE OF %I ON %I FOR EACH ROW EXECUTE FUNCTION shine_canonicalize_identity_fk_login(%L)',
trigger_name, col_name, tab_name, col_name
);
END LOOP;
END $$;
UPDATE db_schema_version SET schema_version = 36,
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
WHERE id = 1;
COMMIT;
@@ -0,0 +1,70 @@
-- v37: оригинальный регистр имени фиксируется при первой регистрации.
-- Нормализованное имя остаётся единственным ключом уникальности.
BEGIN;
CREATE OR REPLACE FUNCTION shine_identity_login_immutable()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'UPDATE' AND (NEW.login IS DISTINCT FROM OLD.login
OR NEW.normalized_login IS DISTINCT FROM OLD.normalized_login) THEN
RAISE EXCEPTION 'Registered login spelling is immutable: %', OLD.login;
END IF;
IF NEW.normalized_login IS DISTINCT FROM lower(btrim(NEW.login)) THEN
RAISE EXCEPTION 'normalized_login must match registered login: %', NEW.login;
END IF;
RETURN NEW;
END $$;
DROP TRIGGER IF EXISTS trg_identity_login_immutable ON user_identity_current;
CREATE TRIGGER trg_identity_login_immutable
BEFORE INSERT OR UPDATE ON user_identity_current
FOR EACH ROW EXECUTE FUNCTION shine_identity_login_immutable();
-- FREE_CERT -> Solana: имя должно совпадать побайтно, включая регистр.
-- Источником имени остаётся первая регистрация, а не очередная синхронизация.
CREATE OR REPLACE FUNCTION shine_sync_identity_from_solana()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
DECLARE old_user user_identity_current%ROWTYPE;
BEGIN
IF TG_OP = 'INSERT' AND EXISTS (
SELECT 1 FROM solana_user_pda_current prior
WHERE prior.pda_address = NEW.pda_address AND prior.record_number > NEW.record_number
) THEN
RETURN NEW;
END IF;
SELECT * INTO old_user FROM user_identity_current
WHERE normalized_login = NEW.normalized_login FOR UPDATE;
IF FOUND AND old_user.login <> NEW.login THEN
RAISE EXCEPTION 'Registered login case mismatch: % vs %', old_user.login, NEW.login;
END IF;
IF FOUND AND old_user.registration_status = 'FREE_CERT' AND
(old_user.root_key <> NEW.root_key OR old_user.client_key <> NEW.client_key OR old_user.blockchain_key <> NEW.blockchain_key) THEN
RAISE EXCEPTION 'Free certificate keys differ from Solana upgrade for %', NEW.login;
END IF;
IF FOUND AND old_user.solana_pda_address IS NOT NULL AND old_user.solana_pda_address <> NEW.pda_address THEN
RAISE EXCEPTION 'Duplicate on-chain identity for %', NEW.login;
END IF;
INSERT INTO user_identity_current (
login, normalized_login, namespace, registration_source, registration_status,
solana_pda_address, free_data_item_id, root_key, client_key, blockchain_key,
blockchain_name, is_server, registered_at_ms, updated_at_ms)
VALUES (NEW.login, NEW.normalized_login,
CASE WHEN position('@' in NEW.login) > 0 THEN split_part(NEW.login,'@',2) ELSE NULL END,
'SOLANA', 'PAID',
NEW.pda_address, old_user.free_data_item_id, NEW.root_key, NEW.client_key,
NEW.blockchain_key, NEW.blockchain_name, NEW.is_server,
COALESCE(old_user.registered_at_ms, NEW.created_at_ms), NEW.updated_at_ms)
ON CONFLICT (login) DO UPDATE SET
registration_source='SOLANA',
registration_status=EXCLUDED.registration_status,
solana_pda_address=EXCLUDED.solana_pda_address,
root_key=EXCLUDED.root_key, client_key=EXCLUDED.client_key,
blockchain_key=EXCLUDED.blockchain_key, blockchain_name=EXCLUDED.blockchain_name,
is_server=EXCLUDED.is_server, updated_at_ms=EXCLUDED.updated_at_ms;
RETURN NEW;
END $$;
UPDATE db_schema_version SET schema_version = 37,
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
WHERE id = 1;
COMMIT;
@@ -0,0 +1,11 @@
-- v38: blockchain_state_store.blockchain_key — runtime Base64(32).
-- Исторические Base58-значения нормализуются Java bootstrapper-ом,
-- поскольку PostgreSQL не содержит встроенного корректного Base58 decoder.
BEGIN;
UPDATE db_schema_version
SET schema_version = 38,
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
WHERE id = 1;
COMMIT;
@@ -0,0 +1,11 @@
-- SHiNE DB v39: допускает временный opt-in на повторное использование email
-- для free-регистрации. По умолчанию это всё равно запрещено проверками runtime.
BEGIN;
ALTER TABLE free_registration_certificate
DROP CONSTRAINT IF EXISTS free_registration_certificate_email_sha256_key;
CREATE INDEX IF NOT EXISTS idx_free_registration_email_sha256
ON free_registration_certificate(email_sha256);
UPDATE db_schema_version SET schema_version = 39 WHERE id = 1;
COMMIT;
@@ -2334,11 +2334,15 @@ CREATE INDEX idx_message_views_target_v29 ON message_views_state(to_login,to_blo
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);
v_canonical_login TEXT;
BEGIN
IF p_login IS NULL OR btrim(p_login)='' THEN RETURN; END IF;
-- В FK остаётся исходный регистр владельца, но поиск/сопоставления регистронезависимы.
SELECT login INTO v_canonical_login FROM user_identity_current WHERE normalized_login=lower(btrim(p_login)) LIMIT 1;
IF v_canonical_login IS NULL 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 v_canonical_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),
@@ -2485,15 +2489,15 @@ DECLARE positive_rel_type INTEGER; channel_bch TEXT;
BEGIN
IF NEW.msg_type<>3 OR NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
IF NEW.msg_sub_type IN (10,14,20,30,40,50,52,54,60,70,74,80) THEN
DELETE FROM connections_state WHERE login=NEW.login AND rel_type=NEW.msg_sub_type AND to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
DELETE FROM connections_state WHERE login=lower(NEW.login) AND rel_type=NEW.msg_sub_type AND to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
INSERT INTO connections_state(login,rel_type,to_login,to_block_number,to_block_hash)
VALUES(NEW.login,NEW.msg_sub_type,NEW.to_login,NEW.to_block_number,NEW.to_block_hash);
VALUES(lower(NEW.login),NEW.msg_sub_type,lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash);
ELSE
positive_rel_type := CASE NEW.msg_sub_type WHEN 11 THEN 10 WHEN 15 THEN 14 WHEN 21 THEN 20 WHEN 31 THEN 30 WHEN 41 THEN 40 WHEN 51 THEN 50 WHEN 53 THEN 52 WHEN 55 THEN 54 WHEN 61 THEN 60 WHEN 71 THEN 70 WHEN 75 THEN 74 WHEN 81 THEN 80 ELSE NULL END;
IF positive_rel_type IS NOT NULL THEN DELETE FROM connections_state WHERE login=NEW.login AND rel_type=positive_rel_type AND to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash; END IF;
IF positive_rel_type IS NOT NULL THEN DELETE FROM connections_state WHERE login=lower(NEW.login) AND rel_type=positive_rel_type AND to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash; END IF;
END IF;
PERFORM shine_refresh_user_stats(NEW.login);
PERFORM shine_refresh_user_stats(NEW.to_login);
PERFORM shine_refresh_user_stats(lower(NEW.login));
PERFORM shine_refresh_user_stats(lower(NEW.to_login));
IF NEW.msg_sub_type IN (30,31) AND NEW.to_block_number>0 THEN
SELECT owner_bch_name INTO channel_bch FROM channel_names_state WHERE LOWER(owner_login)=LOWER(NEW.to_login) AND channel_root_block_number=NEW.to_block_number AND channel_root_block_hash=NEW.to_block_hash LIMIT 1;
IF channel_bch IS NOT NULL THEN PERFORM shine_refresh_channel_follow_stats(channel_bch,NEW.to_block_number,NEW.to_block_hash); END IF;
@@ -2506,22 +2510,22 @@ DECLARE previous_sub_type INTEGER;
BEGIN
IF NEW.msg_type<>2 OR NEW.msg_sub_type NOT IN (1,2) THEN RETURN NEW; END IF;
IF NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
INSERT INTO message_stats(to_login,to_block_number,to_block_hash) VALUES(NEW.to_login,NEW.to_block_number,NEW.to_block_hash)
INSERT INTO message_stats(to_login,to_block_number,to_block_hash) VALUES(lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash)
ON CONFLICT(to_login,to_block_number,to_block_hash) DO NOTHING;
SELECT last_sub_type INTO previous_sub_type FROM reactions_state WHERE from_login=NEW.login AND reaction_type=1 AND to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash LIMIT 1;
SELECT last_sub_type INTO previous_sub_type FROM reactions_state WHERE from_login=lower(NEW.login) AND reaction_type=1 AND to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash LIMIT 1;
IF NEW.msg_sub_type=1 AND previous_sub_type IS DISTINCT FROM 1 THEN
UPDATE message_stats SET likes_count=likes_count+1,
primary_likes_count=primary_likes_count+CASE WHEN shine_is_primary(NEW.login) THEN 1 ELSE 0 END,
shining_likes_count=shining_likes_count+CASE WHEN shine_is_primary(NEW.login) AND shine_is_shining(NEW.login) THEN 1 ELSE 0 END
WHERE to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
WHERE to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
ELSIF NEW.msg_sub_type=2 AND previous_sub_type=1 THEN
UPDATE message_stats SET likes_count=GREATEST(0,likes_count-1),
primary_likes_count=GREATEST(0,primary_likes_count-CASE WHEN shine_is_primary(NEW.login) THEN 1 ELSE 0 END),
shining_likes_count=GREATEST(0,shining_likes_count-CASE WHEN shine_is_primary(NEW.login) AND shine_is_shining(NEW.login) THEN 1 ELSE 0 END)
WHERE to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
WHERE to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
END IF;
INSERT INTO reactions_state(from_login,reaction_type,to_login,to_block_number,to_block_hash,last_sub_type)
VALUES(NEW.login,1,NEW.to_login,NEW.to_block_number,NEW.to_block_hash,NEW.msg_sub_type)
VALUES(lower(NEW.login),1,lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash,NEW.msg_sub_type)
ON CONFLICT(from_login,reaction_type,to_login,to_block_number,to_block_hash) DO UPDATE SET last_sub_type=EXCLUDED.last_sub_type;
RETURN NEW;
END $$;
@@ -2532,7 +2536,7 @@ BEGIN
IF NEW.msg_type<>1 OR NEW.msg_sub_type<>20 THEN RETURN NEW; END IF;
IF NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
INSERT INTO message_stats(to_login,to_block_number,to_block_hash,replies_count)
VALUES(NEW.to_login,NEW.to_block_number,NEW.to_block_hash,1)
VALUES(lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash,1)
ON CONFLICT(to_login,to_block_number,to_block_hash) DO UPDATE SET replies_count=message_stats.replies_count+1;
RETURN NEW;
END $$;
@@ -30,6 +30,7 @@ dependencies {
implementation project(':shine-server-crypto') // модуль сервера для работы с криптографией
implementation project(':shine-server-blockchain') // модуль для работы с блокчейном
implementation project(':shine-server-solana-users-sync') // Нормализованный адрес PDA
implementation project(':shine-server-db') // модуль для работы с БД содержит и сущности из БД и саму работу с БД
implementation project(':shine-server-geo') // модуль для определения геолокации по IP
@@ -169,6 +169,8 @@ import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ListBlockchain
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_Ping_Request;
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ServerHello_Request;
import server.logic.ws_protocol.JSON.handlers.registration.Net_Registration_Handler;
import server.logic.ws_protocol.JSON.handlers.registration.Net_Registration_Request;
import java.util.Map;
/**
@@ -186,6 +188,14 @@ public final class JsonHandlerRegistry {
Map.entry("SearchUsers", new Net_SearchUsers_Handler()),
Map.entry("SearchChannels", new Net_SearchChannels_Handler()),
// --- Registration V2: 6 согласованных публичных операций ---
Map.entry("GetNamespaces", new Net_Registration_Handler("GetNamespaces")),
Map.entry("CheckRegistrationLogin", new Net_Registration_Handler("CheckRegistrationLogin")),
Map.entry("CheckRegistrationEmail", new Net_Registration_Handler("CheckRegistrationEmail")),
Map.entry("StartFreeRegistration", new Net_Registration_Handler("StartFreeRegistration")),
Map.entry("ConfirmFreeRegistration", new Net_Registration_Handler("ConfirmFreeRegistration")),
Map.entry("GetRegistrationStatus", new Net_Registration_Handler("GetRegistrationStatus")),
// --- auth ---
Map.entry("ResolveLoginForAuth", new Net_ResolveLoginForAuth_Handler()),
Map.entry("AuthChallenge", new Net_AuthChallenge_Handler()),
@@ -291,6 +301,14 @@ public final class JsonHandlerRegistry {
Map.entry("SearchUsers", Net_SearchUsers_Request.class),
Map.entry("SearchChannels", Net_SearchChannels_Request.class),
// --- Registration V2 ---
Map.entry("GetNamespaces", Net_Registration_Request.class),
Map.entry("CheckRegistrationLogin", Net_Registration_Request.class),
Map.entry("CheckRegistrationEmail", Net_Registration_Request.class),
Map.entry("StartFreeRegistration", Net_Registration_Request.class),
Map.entry("ConfirmFreeRegistration", Net_Registration_Request.class),
Map.entry("GetRegistrationStatus", Net_Registration_Request.class),
// --- auth ---
Map.entry("ResolveLoginForAuth", Net_ResolveLoginForAuth_Request.class),
Map.entry("AuthChallenge", Net_AuthChallenge_Request.class),
@@ -76,9 +76,12 @@ public final class JsonInboundProcessor {
return out;
}
// DEBUG: сырой вход (обрезаем, чтобы не убить лог)
// Не писать email, challenge и ключи в лог даже на DEBUG.
if (log.isDebugEnabled()) {
log.debug("JSON IN (login={}, sessionId={}): {}", ctxLogin, ctxSessionId, shorten(json, 1200));
log.debug("JSON IN (login={}, sessionId={}): {}", ctxLogin, ctxSessionId,
json.contains("FreeRegistration") || json.contains("RegistrationEmail")
|| json.contains("RegistrationLogin") || json.contains("GetNamespaces")
|| json.contains("GetRegistrationStatus") ? "<registration payload redacted>" : shorten(json, 1200));
}
// 1) Парсим общий пакет
@@ -178,7 +181,7 @@ public final class JsonInboundProcessor {
} catch (Exception mapErr) {
// Важно: вот это часто “теряется”, если не логировать отдельно
log.error("❌ JSON map error (op={}, requestId={}, login={}, sessionId={}): merged={}",
op, safe(requestId), ctxLogin, ctxSessionId, shorten(merged.toString(), 1200), mapErr);
op, safe(requestId), ctxLogin, ctxSessionId, "<redacted>", mapErr);
Net_Exception_Response err = NetExceptionResponseFactory.error(
op,
@@ -202,7 +205,7 @@ public final class JsonInboundProcessor {
// DEBUG: нормализованный запрос (уже распарсен)
if (log.isDebugEnabled()) {
log.debug("REQ OBJ (login={}, sessionId={}, op={}, requestId={}): {}",
ctxLogin, ctxSessionId, safe(op), safe(requestId), shorten(safeToString(request), 1200));
ctxLogin, ctxSessionId, safe(op), safe(requestId), isRegistrationOperation(op) ? "<registration payload redacted>" : shorten(safeToString(request), 1200));
}
// REMOTE-пользователь успешно авторизован, но этот сервер не является
@@ -372,6 +375,11 @@ public final class JsonInboundProcessor {
}
}
private static boolean isRegistrationOperation(String op) {
return op != null && (op.endsWith("Registration") || op.startsWith("CheckRegistration")
|| op.equals("GetNamespaces") || op.equals("GetRegistrationStatus"));
}
private static String safe(String s) {
return s != null ? s : "";
}
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import utils.config.SolanaProgramsConfig;
import shine.db.dao.RegistrationIdentityDAO;
import java.net.URI;
import java.net.http.HttpClient;
@@ -34,6 +35,10 @@ public final class SolanaUserPdaImportService {
public static SessionTypeCheckResult checkSessionTypeAgainstPda(String loginRaw, String sessionKeyApi, int requestedSessionType) throws Exception {
String login = normalizeLogin(loginRaw);
if (login == null) return SessionTypeCheckResult.noRecord();
// У FREE_CERT нет Solana PDA. Это НЕ означает отсутствие идентичности:
// AuthChallenge и подпись clientKey уже проверяются через общий индекс.
RegistrationIdentityDAO.ResolvedIdentity identity = RegistrationIdentityDAO.getInstance().get(login);
if (identity != null && identity.isFree()) return SessionTypeCheckResult.noRecord();
ParsedSolanaUser parsed = fetchFromSolana(login);
if (parsed == null) return SessionTypeCheckResult.noRecord();
@@ -103,54 +108,34 @@ public final class SolanaUserPdaImportService {
}
private static byte[] fetchRawUserPda(String login) throws Exception {
String loginB58 = toBase58(login.getBytes(StandardCharsets.UTF_8));
String lenB58 = toBase58(new byte[]{(byte) login.length()});
String reqJson = """
{
"jsonrpc":"2.0",
"id":1,
"method":"getProgramAccounts",
"params":[
"%s",
{
"encoding":"base64",
"filters":[
{"memcmp":{"offset":61,"bytes":"%s"}},
{"memcmp":{"offset":62,"bytes":"%s"}}
]
}
]
}
""".formatted(SolanaProgramsConfig.SHINE_USERS_PROGRAM_ID, lenB58, loginB58);
// Запись хранит исходный регистр, но адрес PDA зависит только от lowercase.
String address = sync.util.SolanaPdaUtil.findUserPdaV2(login, SolanaProgramsConfig.SHINE_USERS_PROGRAM_ID);
String reqJson = MAPPER.writeValueAsString(Map.of(
"jsonrpc", "2.0", "id", 1,
"method", "getAccountInfo",
"params", List.of(address, Map.of("encoding", "base64", "commitment", "confirmed"))));
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(SolanaProgramsConfig.SOLANA_RPC_URL))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(reqJson))
.build();
HttpResponse<String> resp = HTTP.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
if (resp.statusCode() < 200 || resp.statusCode() >= 300) {
throw new IllegalStateException("Solana RPC HTTP status=" + resp.statusCode());
}
JsonNode root = MAPPER.readTree(resp.body());
if (root.hasNonNull("error")) {
throw new IllegalStateException("Solana RPC error: " + root.get("error").toString());
throw new IllegalStateException("Solana RPC error: " + root.get("error"));
}
JsonNode result = root.path("result");
if (!result.isArray() || result.isEmpty()) return null;
for (JsonNode item : result) {
JsonNode dataNode = item.path("account").path("data");
if (!dataNode.isArray() || dataNode.size() < 1) continue;
String b64 = dataNode.get(0).asText("");
if (b64.isBlank()) continue;
return Base64.getDecoder().decode(b64);
JsonNode account = root.path("result").path("value");
if (account.isMissingNode() || account.isNull()) return null;
if (!SolanaProgramsConfig.SHINE_USERS_PROGRAM_ID.equals(account.path("owner").asText())) {
throw new IllegalStateException("PDA принадлежит другой программе");
}
return null;
JsonNode data = account.path("data");
if (!data.isArray() || data.isEmpty()) return null;
String b64 = data.get(0).asText("");
return b64.isBlank() ? null : Base64.getDecoder().decode(b64);
}
private static ParsedSolanaUser parseUserPda(byte[] raw) {
@@ -253,7 +238,7 @@ public final class SolanaUserPdaImportService {
}
if (blockchainKey32 == null || clientKey32 == null || forkCount <= 0 || forkCount > 999) return null;
String blockchainName = login + "-" + String.format(Locale.ROOT, "%03d", forkCount);
String blockchainName = normalizeLogin(login) + "-" + String.format(Locale.ROOT, "%03d", forkCount);
return new ParsedSolanaUser(
login,
blockchainName,
@@ -360,7 +345,7 @@ public final class SolanaUserPdaImportService {
return out;
}
// Нужен для memcmp.bytes в Solana RPC.
// Вспомогательная base58-конверсия для других совместимых полей.
private static String toBase58(byte[] input) {
final char[] alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
int zeros = 0;
@@ -37,11 +37,13 @@ import shine.db.dao.BlockchainStateDAO;
import shine.db.dao.BlocksDAO;
import shine.db.dao.CanonicalChainResolver;
import shine.db.dao.ChannelNameStateDAO;
import shine.db.dao.CurrentUsersDAO;
import shine.db.dao.UserNotificationsStateDAO;
import shine.db.dao.UserParamsDAO;
import shine.db.entities.BlockchainStateEntry;
import shine.db.entities.BlockEntry;
import shine.db.entities.ChannelNameStateEntry;
import shine.db.entities.CurrentUserEntry;
import shine.db.entities.UserNotificationEntry;
import shine.db.entities.UserParamEntry;
import utils.blockchain.BlockchainNameUtil;
@@ -68,6 +70,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
private final CanonicalChainResolver canonicalChain = CanonicalChainResolver.getInstance();
private final BlockchainStateDAO stateDAO = BlockchainStateDAO.getInstance();
private final CurrentUsersDAO currentUsersDAO = CurrentUsersDAO.getInstance();
private final UserParamsDAO userParamsDAO = UserParamsDAO.getInstance();
private final ChannelNameStateDAO channelNameStateDAO = ChannelNameStateDAO.getInstance();
@@ -202,6 +205,8 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
case "bad_type_tag" -> "Некорректный индексный t-тег ANS-104";
case "bad_channel_tag" -> "Некорректный тег канала ANS-104";
case "bad_block_body" -> "Некорректное тело блока";
case "header_login_mismatch" -> "HEADER должен содержать имя точно в регистре регистрации";
case "header_identity_lookup_failed" -> "Не удалось проверить регистрационное имя HEADER";
case "bad_channel_name" -> "Некорректное название канала";
case "bad_block_number" -> "Некорректный номер блока";
case "req_global_mismatch" -> "Номер блока в запросе не совпадает с номером в блоке";
@@ -255,7 +260,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
}
// 1) state обязателен
final BlockchainStateEntry st;
BlockchainStateEntry st;
try {
st = stateDAO.getByBlockchainName(blockchainName);
} catch (Exception e) {
@@ -264,6 +269,37 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "db_error", 0, "");
}
if (st == null) {
// Runtime-проекция могла отсутствовать у пользователей, зарегистрированных
// ранней версией free-регистрации. Восстанавливаем только для точно
// существующего владельца этой цепочки; сам блок всё равно проходит
// полную проверку ключа и подписи ниже.
try {
CurrentUserEntry user = currentUsersDAO.getByBlockchainName(blockchainName);
if (user != null) {
BlockchainStateEntry recovered = new BlockchainStateEntry();
recovered.setBlockchainName(user.getBlockchainName());
recovered.setLogin(user.getLogin());
recovered.setBlockchainKey(user.getBlockchainKey());
recovered.setSizeLimit(100_000L);
recovered.setFileSizeBytes(0L);
recovered.setLastBlockNumber(-1);
recovered.setLastBlockHash(new byte[32]);
recovered.setUpdatedAtMs(System.currentTimeMillis());
stateDAO.insertIfMissing(recovered);
st = stateDAO.getByBlockchainName(blockchainName);
if (st != null) {
log.warn("AddBlock: восстановлена отсутствующая blockchain_state для login={}, blockchainName={}",
user.getLogin(), blockchainName);
}
}
} catch (Exception e) {
log.error("AddBlock: не удалось восстановить blockchain_state (login={}, blockchainName={})",
login, blockchainName, e);
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "db_error", 0, "");
}
}
if (st == null) {
log.warn("AddBlock: blockchain_state_not_found (login={}, blockchainName={}, reqGlobalNumber={})",
login, blockchainName, globalNumberFromReq);
@@ -351,8 +387,17 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
if (!(block.body instanceof HeaderBody headerBody)) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_required_as_block_zero", serverLastNum, serverLastHashHex);
}
if (!login.equals(headerBody.login)) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_login_mismatch", serverLastNum, serverLastHashHex);
// HEADER фиксирует написание из регистрационной записи, а не lower-case имя цепочки.
// Проверка точная: другой регистр не может создать альтернативное "официальное" имя.
try {
CurrentUserEntry registeredOwner = currentUsersDAO.getByLogin(login);
if (registeredOwner == null || !headerBody.login.equals(registeredOwner.getLogin())
|| !login.equalsIgnoreCase(registeredOwner.getLogin())) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_login_mismatch", serverLastNum, serverLastHashHex);
}
} catch (Exception e) {
log.error("AddBlock: cannot verify registered HEADER login for {}", blockchainName, e);
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "header_identity_lookup_failed", serverLastNum, serverLastHashHex);
}
} else if (block.body instanceof HeaderBody) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_must_be_block_zero", serverLastNum, serverLastHashHex);
@@ -13,10 +13,10 @@ import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;
import shine.db.dao.BlockchainStateDAO;
import shine.db.dao.CanonicalChainResolver;
import shine.db.dao.SolanaUserPdaCurrentDAO;
import shine.db.dao.CurrentUsersDAO;
import shine.db.entities.BlockEntry;
import shine.db.entities.BlockchainStateEntry;
import shine.db.entities.SolanaUserPdaCurrentEntry;
import shine.db.entities.CurrentUserEntry;
import java.util.ArrayList;
import java.util.Collections;
@@ -26,7 +26,7 @@ import java.util.List;
public final class Net_GetMyBlockchain_Handler implements JsonMessageHandler {
private final CanonicalChainResolver canonical = CanonicalChainResolver.getInstance();
private final BlockchainStateDAO states = BlockchainStateDAO.getInstance();
private final SolanaUserPdaCurrentDAO users = SolanaUserPdaCurrentDAO.getInstance();
private final CurrentUsersDAO users = CurrentUsersDAO.getInstance();
@Override
public Net_Response handle(Net_Request baseReq, ConnectionContext ctx) {
@@ -36,7 +36,7 @@ public final class Net_GetMyBlockchain_Handler implements JsonMessageHandler {
}
try {
String login = ctx.getLogin().trim();
SolanaUserPdaCurrentEntry user = users.getByLogin(login);
CurrentUserEntry user = users.getByLogin(login);
if (user == null || user.getBlockchainName() == null || user.getBlockchainName().isBlank()) {
return NetExceptionResponseFactory.error(req, 404, "BLOCKCHAIN_NOT_FOUND", "Текущий блокчейн пользователя не найден");
}
@@ -16,6 +16,8 @@ import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Locale;
final class ChannelsReadSupport {
static final int MSG_TYPE_TEXT = 1;
@@ -39,6 +41,19 @@ final class ChannelsReadSupport {
}
}
// Пользовательское отображение — из реестра, не из normalized blocks.login.
// Кэш ограничен временем одного ответа и не требует дополнительных запросов на каждый пост.
static String officialLogin(Connection c, Map<String, String> cache, String raw) throws SQLException {
if (raw == null || raw.isBlank()) return raw;
String key = raw.trim().toLowerCase(Locale.ROOT);
String value = cache.get(key);
if (value != null) return value;
value = canonicalLogin(c, raw);
if (value == null || value.isBlank()) value = raw;
cache.put(key, value);
return value;
}
static ChannelMeta detectChannelMeta(Connection c, String ownerBch, int rootNumber) throws SQLException {
ChannelMeta meta = new ChannelMeta();
meta.channelTypeVersion = CreateChannelBody.CHANNEL_TYPE_VERSION_DEFAULT & 0xFFFF;
@@ -20,6 +20,8 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_GetChannelMessages_Handler.class);
@@ -44,6 +46,7 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
boolean asc = req.getSort() == null || !"desc".equalsIgnoreCase(req.getSort());
try (Connection c = DbController.getInstance().getConnection()) {
Map<String, String> officialLogins = new HashMap<>();
String viewerLogin = ctx != null ? ctx.getLogin() : null;
if (viewerLogin == null || viewerLogin.isBlank()) {
viewerLogin = ChannelsReadSupport.canonicalLogin(c, req.getLogin());
@@ -58,7 +61,7 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
Net_GetChannelMessages_Response.Channel channel = new Net_GetChannelMessages_Response.Channel();
channel.setOwnerBlockchainName(ownerBch);
channel.setOwnerLogin(BlockchainNameUtil.loginFromBlockchainName(ownerBch));
channel.setOwnerLogin(ChannelsReadSupport.officialLogin(c, officialLogins, BlockchainNameUtil.loginFromBlockchainName(ownerBch)));
ChannelsReadSupport.ChannelMeta meta = ChannelsReadSupport.detectChannelMeta(c, ownerBch, lineCode);
channel.setChannelName(meta.channelName);
channel.setDisplayName(meta.displayName == null || meta.displayName.isBlank() ? meta.channelName : meta.displayName);
@@ -88,7 +91,7 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
eventRef.setBlockNumber(event.blockNumber);
eventRef.setBlockHash(ChannelsReadSupport.toHex(event.blockHash));
outEvent.setMessageRef(eventRef);
outEvent.setAuthorLogin(event.login);
outEvent.setAuthorLogin(ChannelsReadSupport.officialLogin(c, officialLogins, event.login));
outEvent.setAuthorBlockchainName(event.bchName);
outEvent.setLineStep(event.lineStep);
outEvent.setCreatedAtMs(event.createdAtMs);
@@ -133,7 +136,7 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
msgRef.setBlockHash(ChannelsReadSupport.toHex(post.blockHash));
item.setMessageRef(msgRef);
item.setMsgSubType(post.msgSubType);
item.setAuthorLogin(post.login);
item.setAuthorLogin(ChannelsReadSupport.officialLogin(c, officialLogins, post.login));
item.setAuthorBlockchainName(post.bchName);
item.setLineStep(post.thisLineNumber);
item.setTargetBlockchainName(post.toBchName);
@@ -21,6 +21,8 @@ import java.util.Comparator;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
public class Net_GetMessageThread_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_GetMessageThread_Handler.class);
@@ -37,6 +39,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
int childLimit = req.getLimitChildrenPerNode() == null ? 50 : Math.max(1, req.getLimitChildrenPerNode());
try (Connection c = DbController.getInstance().getConnection()) {
Map<String, String> officialLogins = new HashMap<>();
String viewerLogin = ctx != null ? ctx.getLogin() : null;
if (viewerLogin == null || viewerLogin.isBlank()) {
viewerLogin = ChannelsReadSupport.canonicalLogin(c, req.getLogin());
@@ -51,7 +54,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
resp.setRequestId(req.getRequestId());
resp.setStatus(WireCodes.Status.OK);
resp.setFocus(toNode(c, focusRow, viewerLogin));
resp.setFocus(toNode(c, focusRow, viewerLogin, officialLogins));
List<Net_GetMessageThread_Response.MessageNode> ancestors = new ArrayList<>();
PostRow cur = focusRow;
@@ -68,12 +71,12 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
parent = findByNumber(c, cur.toBchName, cur.toBlockNumber);
}
if (parent == null) break;
ancestors.add(0, toNode(c, parent, viewerLogin));
ancestors.add(0, toNode(c, parent, viewerLogin, officialLogins));
cur = parent;
}
resp.setAncestors(ancestors);
resp.setDescendants(loadChildren(c, focusRow, depthDown, childLimit, viewerLogin));
resp.setDescendants(loadChildren(c, focusRow, depthDown, childLimit, viewerLogin, officialLogins));
return resp;
} catch (Exception e) {
log.error("GetMessageThread failed", e);
@@ -97,14 +100,14 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
return null;
}
private List<Net_GetMessageThread_Response.MessageNodeTree> loadChildren(Connection c, PostRow parent, int depthDown, int childLimit, String viewerLogin) throws Exception {
private List<Net_GetMessageThread_Response.MessageNodeTree> loadChildren(Connection c, PostRow parent, int depthDown, int childLimit, String viewerLogin, Map<String, String> officialLogins) throws Exception {
if (depthDown <= 0) return List.of();
List<PostRow> replies = findRepliesAndRatings(c, parent.bchName, parent.blockNumber, parent.blockHash, childLimit);
List<Net_GetMessageThread_Response.MessageNodeTree> out = new ArrayList<>();
for (PostRow row : replies) {
Net_GetMessageThread_Response.MessageNodeTree t = new Net_GetMessageThread_Response.MessageNodeTree();
t.setNode(toNode(c, row, viewerLogin));
t.setChildren(loadChildren(c, row, depthDown - 1, childLimit, viewerLogin));
t.setNode(toNode(c, row, viewerLogin, officialLogins));
t.setChildren(loadChildren(c, row, depthDown - 1, childLimit, viewerLogin, officialLogins));
out.add(t);
}
return out;
@@ -233,14 +236,14 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
return row;
}
private Net_GetMessageThread_Response.MessageNode toNode(Connection c, PostRow row, String viewerLogin) throws Exception {
private Net_GetMessageThread_Response.MessageNode toNode(Connection c, PostRow row, String viewerLogin, Map<String, String> officialLogins) throws Exception {
Net_GetMessageThread_Response.MessageNode node = new Net_GetMessageThread_Response.MessageNode();
Net_GetChannelMessages_Response.BlockRef ref = new Net_GetChannelMessages_Response.BlockRef();
ref.setBlockNumber(row.blockNumber);
ref.setBlockHash(ChannelsReadSupport.toHex(row.blockHash));
node.setMessageRef(ref);
node.setMsgSubType(row.msgSubType);
node.setAuthorLogin(row.login);
node.setAuthorLogin(ChannelsReadSupport.officialLogin(c, officialLogins, row.login));
node.setAuthorBlockchainName(row.bchName);
node.setLineStep(row.thisLineNumber);
node.setTargetBlockchainName(row.toBchName);
@@ -19,6 +19,8 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_ListSubscriptionsFeed_Handler.class);
@@ -59,11 +61,12 @@ public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
private List<Net_ListSubscriptionsFeed_Response.ChannelSummary> buildSummaries(Connection c, String viewerLogin, List<ChannelKey> keys) throws Exception {
List<Net_ListSubscriptionsFeed_Response.ChannelSummary> out = new ArrayList<>();
Map<String, String> officialLogins = new HashMap<>();
for (ChannelKey key : keys) {
Net_ListSubscriptionsFeed_Response.ChannelSummary row = new Net_ListSubscriptionsFeed_Response.ChannelSummary();
Net_ListSubscriptionsFeed_Response.ChannelRef channelRef = new Net_ListSubscriptionsFeed_Response.ChannelRef();
ChannelsReadSupport.ChannelMeta meta = ChannelsReadSupport.detectChannelMeta(c, key.ownerBch, key.rootNumber);
channelRef.setOwnerLogin(key.ownerLogin);
channelRef.setOwnerLogin(ChannelsReadSupport.officialLogin(c, officialLogins, key.ownerLogin));
channelRef.setOwnerBlockchainName(key.ownerBch);
channelRef.setChannelName(meta.channelName);
channelRef.setDisplayName(meta.displayName == null || meta.displayName.isBlank() ? meta.channelName : meta.displayName);
@@ -108,7 +111,7 @@ public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
lm.setMessageRef(msgRef);
lm.setText(textInfo.text);
lm.setCreatedAtMs(textInfo.createdAtMs);
lm.setAuthorLogin(actual.login);
lm.setAuthorLogin(ChannelsReadSupport.officialLogin(c, officialLogins, actual.login));
lm.setAuthorBlockchainName(actual.bchName);
row.setLastMessage(lm);
}
@@ -11,6 +11,23 @@ import java.util.Base64;
final class KeyRotationApiSupport {
private KeyRotationApiSupport() {}
/** Free identity не имеет Solana PDA и не вправе менять ключи/форки. */
static server.logic.ws_protocol.JSON.entyties.Net_Response denyFreeRotation(
server.logic.ws_protocol.JSON.entyties.Net_Request req, String login) {
try {
var identity = shine.db.dao.RegistrationIdentityDAO.getInstance().get(login);
if (identity == null) return server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory.error(
req, 404, "KEY_ROTATION_USER_NOT_FOUND", "Пользователь не найден");
if (identity.isFree()) return server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory.error(
req, 403, "KEY_ROTATION_PAID_ONLY", "Для смены ключей необходима регистрация в Solana");
return null;
} catch (java.sql.SQLException e) {
// fail closed при неготовой миграции / ошибке БД
return server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory.error(
req, 503, "KEY_ROTATION_IDENTITY_UNAVAILABLE", "Невозможно проверить полномочия пользователя");
}
}
static String normalizePublicKey32(String raw) {
String normalized = KeyEncodingUtil.normalizeKeyToBase64_32(raw);
if (normalized == null || normalized.isBlank()) {
@@ -20,6 +20,8 @@ public final class Net_KeyRotationAbort_Handler implements JsonMessageHandler {
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
}
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
if (freeCheck != null) return freeCheck;
try {
KeyRotationSessionEntry current = rotations.getActiveByLogin(ctx.getLogin().trim());
if (current == null) return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), null);
@@ -44,6 +44,8 @@ public final class Net_KeyRotationAddBlock_Handler implements JsonMessageHandler
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
}
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
if (freeCheck != null) return freeCheck;
if (req.getBlockNumber() < 0 || req.getBlockBytesB64() == null || req.getBlockBytesB64().isBlank()) {
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_BLOCK", "blockNumber и blockBytesB64 обязательны");
}
@@ -22,6 +22,8 @@ public final class Net_KeyRotationContinue_Handler implements JsonMessageHandler
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
}
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
if (freeCheck != null) return freeCheck;
try {
String login = ctx.getLogin().trim();
KeyRotationSessionEntry current = rotations.getActiveByLogin(login);
@@ -47,6 +47,8 @@ public final class Net_KeyRotationFinishChain_Handler implements JsonMessageHand
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
}
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
if (freeCheck != null) return freeCheck;
String login = ctx.getLogin().trim();
KeyRotationSessionEntry initial;
@@ -24,6 +24,8 @@ public final class Net_KeyRotationRotatePda_Handler implements JsonMessageHandle
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
}
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
if (freeCheck != null) return freeCheck;
String login = ctx.getLogin().trim();
final String signature;
@@ -39,7 +41,18 @@ public final class Net_KeyRotationRotatePda_Handler implements JsonMessageHandle
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_NOT_ACTIVE", "Активная ротация отсутствует");
}
if (current.getStatus() == KeyRotationStatus.PDA_ROTATED) {
// Solana sync и rebuild работают независимо от уведомления клиента.
// При повторе после подтверждённой PDA возвращаем реальный этап, а не 409.
if (current.getStatus() == KeyRotationStatus.PDA_ROTATED
|| current.getStatus() == KeyRotationStatus.REBUILDING_SERVER
|| current.getStatus() == KeyRotationStatus.WALLET_MIGRATION
|| current.getStatus() == KeyRotationStatus.MESSAGE_MIGRATION
|| current.getStatus() == KeyRotationStatus.FINALIZING) {
String stored = current.getPdaRotationSignature();
if (stored != null && !stored.isBlank() && !stored.equals(signature)) {
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_PDA_SIGNATURE_CONFLICT",
"Для этой ротации уже сохранена другая Solana transaction signature");
}
var fresh = CurrentUsersDAO.getInstance().getByLogin(login);
if (fresh != null) ctx.setCurrentUser(fresh);
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current);
@@ -39,6 +39,8 @@ public final class Net_KeyRotationStart_Handler implements JsonMessageHandler {
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
}
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
if (freeCheck != null) return freeCheck;
String login = ctx.getLogin().trim();
String currentSessionId = ctx.getSessionId() == null ? "" : ctx.getSessionId().trim();
if (currentSessionId.isEmpty()) {
@@ -20,6 +20,8 @@ public final class Net_KeyRotationStatus_Handler implements JsonMessageHandler {
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
}
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
if (freeCheck != null) return freeCheck;
try {
String login = ctx.getLogin().trim();
KeyRotationSessionEntry current = rotations.getActiveByLogin(login);
@@ -0,0 +1,47 @@
package server.logic.ws_protocol.JSON.handlers.registration;
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.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;
/** API доступно анонимному клиенту, но без разрешения приватных операций. */
public final class Net_Registration_Handler implements JsonMessageHandler {
private final String operation;
private static final java.util.Map<ConnectionContext, long[]> LIMITS =
java.util.Collections.synchronizedMap(new java.util.WeakHashMap<>());
private static long globalMinute=-1;
private static int globalHits=0;
private static boolean throttled(ConnectionContext ctx) {
long minute=System.currentTimeMillis()/60000L;
synchronized (LIMITS) {
if(globalMinute!=minute){globalMinute=minute;globalHits=0;}
if(++globalHits>1200) return true;
if(ctx==null) return false;
long[] bucket=LIMITS.computeIfAbsent(ctx, c->new long[]{minute,0});
if(bucket[0]!=minute){bucket[0]=minute;bucket[1]=0;}
return ++bucket[1]>30;
}
}
public Net_Registration_Handler(String operation) { this.operation=operation; }
@Override public Net_Response handle(Net_Request base, ConnectionContext ctx) throws Exception {
Net_Registration_Request request=(Net_Registration_Request)base;
if (throttled(ctx)) return NetExceptionResponseFactory.error(request,429,"RATE_LIMITED","Слишком много запросов регистрации");
RegistrationApiBridge.Service service=RegistrationApiBridge.get();
if (service==null) return NetExceptionResponseFactory.error(request,503,"REGISTRATION_UNAVAILABLE","Регистрация на сервере пока не настроена");
try {
java.util.Map<String,Object> values=service.execute(operation,request);
Net_Registration_Response out=new Net_Registration_Response();
out.setOp(request.getOp()); out.setRequestId(request.getRequestId());
out.setStatus(WireCodes.Status.OK); out.setValues(values);
return out;
} catch (IllegalArgumentException e) {
// Без echo исходного email, чтобы не публиковать PII в ответе/логе.
return NetExceptionResponseFactory.error(request,400,"INVALID_REGISTRATION_INPUT","Данные регистрации не прошли проверку");
} catch (IllegalStateException e) {
return NetExceptionResponseFactory.error(request,409,"REGISTRATION_CONFLICT","Регистрация недоступна или данные уже заняты");
}
}
}
@@ -0,0 +1,28 @@
package server.logic.ws_protocol.JSON.handlers.registration;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
/** JSON payload; публичные данные пользователя, пароли/приватные ключи не принимаются. */
public final class Net_Registration_Request extends Net_Request {
private String fullLogin;
private String email;
private String rootPublicKeyB64;
private String blockchainPublicKeyB64;
private String clientPublicKeyB64;
private String challengeId;
private String code;
public String getFullLogin() { return fullLogin; }
public void setFullLogin(String v) { fullLogin = v; }
public String getEmail() { return email; }
public void setEmail(String v) { email = v; }
public String getRootPublicKeyB64() { return rootPublicKeyB64; }
public void setRootPublicKeyB64(String v) { rootPublicKeyB64 = v; }
public String getBlockchainPublicKeyB64() { return blockchainPublicKeyB64; }
public void setBlockchainPublicKeyB64(String v) { blockchainPublicKeyB64 = v; }
public String getClientPublicKeyB64() { return clientPublicKeyB64; }
public void setClientPublicKeyB64(String v) { clientPublicKeyB64 = v; }
public String getChallengeId() { return challengeId; }
public void setChallengeId(String v) { challengeId = v; }
public String getCode() { return code; }
public void setCode(String v) { code = v; }
}
@@ -0,0 +1,12 @@
package server.logic.ws_protocol.JSON.handlers.registration;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
/** Значения результата помещаются на верхний уровень объекта перед стандартной WS-обёрткой. */
public final class Net_Registration_Response extends Net_Response {
private Map<String, Object> values = Map.of();
public void setValues(Map<String,Object> values) { this.values = Map.copyOf(values); }
@JsonAnyGetter public Map<String,Object> getValues() { return values; }
}
@@ -0,0 +1,15 @@
package server.logic.ws_protocol.JSON.handlers.registration;
import java.util.Map;
/** SPI: HTTP/WS модуль не зависит от archive-модуля, устраняя циклический Gradle dependency. */
public final class RegistrationApiBridge {
@FunctionalInterface public interface Service {
Map<String, Object> execute(String operation, Net_Registration_Request request) throws Exception;
}
private static volatile Service service;
private RegistrationApiBridge() {}
public static void install(Service implementation) { service = java.util.Objects.requireNonNull(implementation); }
public static void uninstall() { service = null; }
public static Service get() { return service; }
}
@@ -32,6 +32,7 @@ public class Net_GetServerInfo_Handler implements JsonMessageHandler {
resp.setDescription(CONFIG.getStringOrEmpty("server.info.description"));
resp.setOrigin(CONFIG.getStringOrEmpty("server.info.origin"));
resp.setExtraInfo(CONFIG.getStringOrEmpty("server.info.extraInfo"));
resp.setSolanaCluster(CONFIG.getStringOrEmpty("solana.cluster"));
return resp;
}
@@ -26,6 +26,10 @@ public class Net_GetServerInfo_Response extends Net_Response {
private String description;
private String origin;
private String extraInfo;
private String solanaCluster;
public String getSolanaCluster() { return solanaCluster; }
public void setSolanaCluster(String cluster) { this.solanaCluster = cluster; }
public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; }
@@ -9,6 +9,7 @@ import server.logic.ws_protocol.JSON.ConnectionContext;
import server.logic.ws_protocol.JSON.push.WebPushSender;
import server.logic.ws_protocol.JSON.push.WsEventSender;
import shine.db.dao.ActiveSessionsDAO;
import shine.db.dao.DmDialogStateDAO;
import shine.db.dao.SignedMessagesDAO;
import shine.db.entities.ActiveSessionEntry;
import shine.db.entities.SignedMessageEntry;
@@ -49,6 +50,9 @@ public final class SignedMessagesRealtime {
DeliveryCounters counters = new DeliveryCounters();
long now = System.currentTimeMillis();
for (String targetLogin : targetLoginsForMessage(message)) {
boolean incomingNotification = shouldPushNewIncomingMessage(targetLogin, message, block);
DmDialogStateDAO.NotificationState notificationState = incomingNotification
? loadNotificationState(targetLogin, message.getFromLogin()) : null;
List<ActiveSessionEntry> sessions = ActiveSessionsDAO.getInstance().getByLogin(targetLogin);
List<String> sessionIdsToTrack = new ArrayList<>();
for (ActiveSessionEntry s : sessions) {
@@ -64,13 +68,13 @@ public final class SignedMessagesRealtime {
if (excludeSessionId != null && excludeSessionId.equals(sessionId)) {
continue;
}
boolean deliveredOnline = sendEventToSessionIfOnline(sessionId, targetLogin, message, false);
boolean deliveredOnline = sendEventToSessionIfOnline(sessionId, targetLogin, message, false, notificationState);
if (deliveredOnline) {
counters.wsDelivered++;
continue;
}
if (shouldPushNewIncomingMessage(targetLogin, message, block)) {
boolean pushed = pushNewMessageNotification(s, message);
if (incomingNotification) {
boolean pushed = pushNewMessageNotification(s, message, notificationState);
if (pushed) counters.pushDelivered++;
}
}
@@ -100,7 +104,7 @@ public final class SignedMessagesRealtime {
List<SignedMessageEntry> pending = SignedMessagesDAO.getInstance()
.listPendingForSession(login, sessionId);
for (SignedMessageEntry e : pending) {
sendEventToSessionIfOnline(sessionId, login, e, true);
sendEventToSessionIfOnline(sessionId, login, e, true, null);
}
} catch (Exception e) {
log.warn("Failed to dispatch pending messages for sessionId={}", sessionId, e);
@@ -111,7 +115,8 @@ public final class SignedMessagesRealtime {
String sessionId,
String actualTargetLogin,
SignedMessageEntry message,
boolean backlog
boolean backlog,
DmDialogStateDAO.NotificationState notificationState
) {
ConnectionContext targetCtx = ActiveConnectionsRegistry.getInstance().getBySessionId(sessionId);
if (targetCtx == null) return false;
@@ -128,6 +133,10 @@ public final class SignedMessagesRealtime {
payload.put("nonce", message.getNonce());
payload.put("blobB64", blobB64);
payload.put("backlog", backlog);
if (message.getMessageType() == SignedMessageBlock.TYPE_INCOMING_TEXT && notificationState != null) {
payload.put("unreadCount", notificationState.unreadCount());
payload.put("notificationVersionMs", notificationState.versionMs());
}
if (message.getReceiptRefBaseKey() != null) {
payload.put("receiptRefBaseKey", message.getReceiptRefBaseKey());
}
@@ -141,21 +150,41 @@ public final class SignedMessagesRealtime {
return block.revisionTimeMs == 0;
}
private static boolean pushNewMessageNotification(ActiveSessionEntry session, SignedMessageEntry message) {
private static DmDialogStateDAO.NotificationState loadNotificationState(String ownerLogin, String peerLogin) {
try {
return DmDialogStateDAO.getInstance().getNotificationState(ownerLogin, peerLogin);
} catch (Exception e) {
log.warn("Не удалось получить счётчик непрочитанных DM для {} / {}", ownerLogin, peerLogin, e);
return null;
}
}
private static boolean pushNewMessageNotification(
ActiveSessionEntry session, SignedMessageEntry message, DmDialogStateDAO.NotificationState notificationState
) {
try {
if (session == null) return false;
if (isBlank(session.getPushEndpoint()) || isBlank(session.getPushP256dhKey()) || isBlank(session.getPushAuthKey())) {
return false;
}
String text = "Новое сообщение от " + message.getFromLogin();
String payload = "{\"kind\":\"new_message\",\"fromLogin\":\"" + jsonEscape(message.getFromLogin()) + "\",\"text\":\"" + jsonEscape(text) + "\"}";
ObjectNode payload = MAPPER.createObjectNode();
payload.put("kind", "new_message");
payload.put("toLogin", session.getLogin());
payload.put("fromLogin", message.getFromLogin());
payload.put("messageKey", message.getMessageKey());
payload.put("text", "Новое сообщение от " + message.getFromLogin());
if (notificationState != null) {
payload.put("unreadCount", notificationState.unreadCount());
payload.put("notificationVersionMs", notificationState.versionMs());
}
return WebPushSender.sendBase64Payload(
session.getPushEndpoint(),
session.getPushP256dhKey(),
session.getPushAuthKey(),
payload
payload.toString()
);
} catch (Exception e) {
log.warn("Не удалось подготовить Web Push для DM {}", message.getMessageKey(), e);
return false;
}
}
@@ -182,21 +211,6 @@ public final class SignedMessagesRealtime {
return s == null ? "" : s.trim().toLowerCase();
}
private static String jsonEscape(String s) {
if (s == null) return "";
StringBuilder out = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\\') out.append("\\\\");
else if (c == '"') out.append("\\\"");
else if (c == '\n') out.append("\\n");
else if (c == '\r') out.append("\\r");
else if (c == '\t') out.append("\\t");
else out.append(c);
}
return out.toString();
}
private static boolean isBlank(String s) {
return s == null || s.isBlank();
}
@@ -2,6 +2,7 @@ package sync.codec;
import com.fasterxml.jackson.databind.JsonNode;
import sync.util.Base58Util;
import sync.util.SolanaPdaUtil;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
@@ -29,6 +30,8 @@ public final class ShineUsersCodec {
public static final int IX_CLOSE_LEGACY_USER_PDA =
6;
public static final int IX_CREATE_NAMESPACE = 7;
public static final long START_REGISTRATION_FEE_LAMPORTS =
10_000_000L;
@@ -151,6 +154,16 @@ public final class ShineUsersCodec {
null
);
case IX_CREATE_NAMESPACE ->
new ParsedInstruction(
TxKind.CREATE_NAMESPACE,
true,
accountAt(accounts, 1),
null,
null,
null
);
case IX_CREATE_USER_PDA ->
parseV12PdaMutationInstruction(
TxKind.CREATE_USER_PDA, reader, accounts
@@ -731,10 +744,55 @@ public final class ShineUsersCodec {
}
}
/** Строгий декодер бинарного namespace 1.0 с on-chain PDA address check. */
public static NamespaceSnapshot parseNamespaceAccount(
String pdaAddress, long slot, String rawDataBase64,
String lastTxSignature, String programId
) {
byte[] bytes = Base64.getDecoder().decode(rawDataBase64);
if (bytes.length < 13 || bytes[0] != 1 || bytes[1] != 0) {
throw new IllegalArgumentException("Not a namespace PDA 1.0");
}
Reader r = new Reader(bytes);
r.readU8(); r.readU8();
int type = r.readU8();
if (type != 1 && type != 2) throw new IllegalArgumentException("Invalid namespace type");
int minLen = r.readU8();
String namespace = r.readStringU8();
if (!namespace.matches("[a-z0-9_]+") || minLen < 1 || namespace.length() + minLen + 1 > 30) {
throw new IllegalArgumentException("Invalid namespace");
}
byte[] feeLittleEndian = r.readFixed(8);
byte[] feeBigEndian = new byte[9];
for (int n = 0; n < 8; n++) feeBigEndian[8 - n] = feeLittleEndian[n];
java.math.BigInteger fee = new java.math.BigInteger(feeBigEndian);
String registrarKey = null, serverLogin = null;
if (type == 2) {
registrarKey = Base58Util.encode(r.readFixed(32));
serverLogin = r.readStringU8();
if (!serverLogin.matches("[A-Za-z0-9_]+@[a-z0-9_]+") || serverLogin.length() > 30) {
throw new IllegalArgumentException("Invalid access server login");
}
}
if (r.remaining() != 0 || !pdaAddress.equals(SolanaPdaUtil.findNamespacePda(namespace, programId))) {
throw new IllegalArgumentException("Invalid namespace bytes or PDA address");
}
return new NamespaceSnapshot(namespace, pdaAddress, type, minLen,
fee, registrarKey, serverLogin, slot, lastTxSignature, rawDataBase64);
}
public record NamespaceSnapshot(
String namespace, String pdaAddress, int type, int minLocalpartLength,
java.math.BigInteger registrationFeeLamports, String registrarPublicKey,
String defaultServerLogin, long slot, String lastTxSignature,
String rawDataBase64
) {}
public enum TxKind {
INIT_USERS_ECONOMY_CONFIG,
UPDATE_USERS_ECONOMY_CONFIG,
CREATE_USER_PDA,
CREATE_NAMESPACE,
UPDATE_USER_PDA,
CLOSE_LEGACY_USER_PDA,
OTHER
@@ -386,6 +386,7 @@ public final class SolanaUsersSyncService
);
storage.applyHistoryBatch(
List.of(),
List.of(),
List.of(),
newState
@@ -452,6 +453,7 @@ public final class SolanaUsersSyncService
List<ShineUsersCodec.UserPdaSnapshot> snapshotsToPersist =
new ArrayList<>();
List<ShineUsersCodec.NamespaceSnapshot> namespacesToPersist = new ArrayList<>();
ShineUsersCodec.EconomyConfigState economyState =
state.economyConfigState();
@@ -528,15 +530,19 @@ public final class SolanaUsersSyncService
SolanaRpcClient.AccountBatchResult exactAccounts =
rpcClient.getCurrentAccounts(exactFetchPdaAddresses, newestSeen.slot());
for (ProgramAccountUpdate account : exactAccounts.updates()) {
ShineUsersCodec.UserPdaSnapshot snapshot =
ShineUsersCodec.parseUserPdaAccount(
account.address(),
account.slot(),
account.dataBase64(),
latestRelevantSignatureByPda.getOrDefault(account.address(), "")
);
snapshotsToPersist.removeIf(existing -> existing.pdaAddress().equals(snapshot.pdaAddress()));
snapshotsToPersist.add(snapshot);
String lastSignature = latestRelevantSignatureByPda.getOrDefault(account.address(), "");
byte[] firstBytes = Base64.getDecoder().decode(account.dataBase64());
if (firstBytes.length > 2 && firstBytes[0] == 1 && firstBytes[1] == 0) {
var ns = ShineUsersCodec.parseNamespaceAccount(account.address(),
account.slot(), account.dataBase64(), lastSignature, config.programId());
namespacesToPersist.removeIf(existing -> existing.pdaAddress().equals(ns.pdaAddress()));
namespacesToPersist.add(ns);
} else {
var snapshot = ShineUsersCodec.parseUserPdaAccount(account.address(),
account.slot(), account.dataBase64(), lastSignature);
snapshotsToPersist.removeIf(existing -> existing.pdaAddress().equals(snapshot.pdaAddress()));
snapshotsToPersist.add(snapshot);
}
}
}
@@ -558,6 +564,7 @@ public final class SolanaUsersSyncService
storage.applyHistoryBatch(
txEntries,
snapshotsToPersist,
namespacesToPersist,
newState
);
@@ -595,6 +602,7 @@ public final class SolanaUsersSyncService
List<ShineUsersCodec.UserPdaSnapshot> currentSnapshots =
new ArrayList<>();
List<ShineUsersCodec.NamespaceSnapshot> currentNamespaces = new ArrayList<>();
int processedAccounts =
0;
@@ -604,14 +612,14 @@ public final class SolanaUsersSyncService
processedAccounts++;
try {
currentSnapshots.add(
ShineUsersCodec.parseUserPdaAccount(
account.address(),
account.slot(),
account.dataBase64(),
""
)
);
byte[] firstBytes = Base64.getDecoder().decode(account.dataBase64());
if (firstBytes.length > 2 && firstBytes[0] == 1 && firstBytes[1] == 0) {
currentNamespaces.add(ShineUsersCodec.parseNamespaceAccount(
account.address(), account.slot(), account.dataBase64(), "", config.programId()));
} else {
currentSnapshots.add(ShineUsersCodec.parseUserPdaAccount(
account.address(), account.slot(), account.dataBase64(), ""));
}
} catch (Exception ignored) {
}
@@ -654,6 +662,7 @@ public final class SolanaUsersSyncService
storage.replaceCurrentFromFullSnapshot(
currentSnapshots,
currentNamespaces,
newState
);
@@ -248,6 +248,7 @@ public final class PostgresStorageRepository
public synchronized void applyHistoryBatch(
List<TxHistoryEntry> txEntries,
List<ShineUsersCodec.UserPdaSnapshot> snapshots,
List<ShineUsersCodec.NamespaceSnapshot> namespaces,
SyncStateSnapshot newState
) throws Exception {
@@ -268,6 +269,7 @@ public final class PostgresStorageRepository
snapshots
);
upsertNamespaceSnapshots(connection, namespaces);
upsertCurrentSnapshots(
connection,
snapshots
@@ -297,6 +299,7 @@ public final class PostgresStorageRepository
public synchronized void replaceCurrentFromFullSnapshot(
List<ShineUsersCodec.UserPdaSnapshot> snapshots,
List<ShineUsersCodec.NamespaceSnapshot> namespaces,
SyncStateSnapshot newState
) throws Exception {
@@ -306,6 +309,7 @@ public final class PostgresStorageRepository
connection.setAutoCommit(false);
try {
upsertNamespaceSnapshots(connection, namespaces);
upsertCurrentSnapshots(
connection,
snapshots
@@ -459,6 +463,39 @@ public final class PostgresStorageRepository
}
}
private void upsertNamespaceSnapshots(Connection connection,
List<ShineUsersCodec.NamespaceSnapshot> namespaces) throws Exception {
if (namespaces == null || namespaces.isEmpty()) return;
String sql = """
INSERT INTO shine_namespace_current (
namespace, pda_address, namespace_type, min_localpart_len,
registration_fee_lamports, registrar_pubkey, default_server_login,
slot, last_tx_signature, raw_data_base64
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (namespace) DO UPDATE SET
slot=EXCLUDED.slot, last_tx_signature=EXCLUDED.last_tx_signature,
raw_data_base64=EXCLUDED.raw_data_base64
WHERE shine_namespace_current.pda_address=EXCLUDED.pda_address
AND shine_namespace_current.raw_data_base64=EXCLUDED.raw_data_base64
""";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
for (ShineUsersCodec.NamespaceSnapshot ns : namespaces) {
ps.setString(1, ns.namespace()); ps.setString(2, ns.pdaAddress());
ps.setInt(3, ns.type()); ps.setInt(4, ns.minLocalpartLength());
ps.setBigDecimal(5, new java.math.BigDecimal(ns.registrationFeeLamports()));
ps.setString(6, ns.registrarPublicKey());
ps.setString(7, ns.defaultServerLogin()); ps.setLong(8, ns.slot());
ps.setString(9, ns.lastTxSignature()); ps.setString(10, ns.rawDataBase64());
ps.addBatch();
}
ps.executeBatch();
}
// Namespace появляется после сервера, пересчитываем маршруты free пользователей.
try (Statement st = connection.createStatement()) {
st.execute("SELECT shine_refresh_user_access_servers_all()");
}
}
private void upsertCurrentSnapshots(
Connection connection,
List<ShineUsersCodec.UserPdaSnapshot> snapshots
@@ -1076,6 +1113,16 @@ public final class PostgresStorageRepository
"ON user_access_servers_current(server_login)"
);
// После PostgreSQL migration_v33 функции маршрутизации принадлежат
// общему реестру логических identity, их нельзя перезаписывать
// legacy Solana-only вариантом при старте sync.
boolean hasIdentityTable;
try (ResultSet check = statement.executeQuery(
"SELECT to_regclass('user_identity_current') IS NOT NULL")) {
check.next();
hasIdentityTable = check.getBoolean(1);
}
if (!hasIdentityTable) {
statement.execute(
"""
CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_for_user(p_user_login TEXT)
@@ -1260,6 +1307,8 @@ public final class PostgresStorageRepository
"EXECUTE FUNCTION trg_refresh_user_access_servers_from_user_pda_truncate()"
);
}
statement.execute("SELECT shine_refresh_user_access_servers_all()");
}
}
@@ -61,6 +61,27 @@ public final class SolanaPdaUtil {
);
}
/** Новый v2 PDA. Старый двух-seed вариант оставлен только для legacy accounts. */
public static String findUserPdaV2(String fullLogin, String programId) {
if (fullLogin == null || !fullLogin.matches("[A-Za-z0-9_]+@[a-z0-9_]+") || fullLogin.length() > 30) {
throw new IllegalArgumentException("Invalid full login");
}
return findHashedPda("user_login=" + fullLogin.toLowerCase(java.util.Locale.ROOT), programId);
}
public static String findNamespacePda(String namespace, String programId) {
if (namespace == null || !namespace.matches("[a-z0-9_]+")) {
throw new IllegalArgumentException("Invalid namespace");
}
return findHashedPda("namespace=" + namespace, programId);
}
private static String findHashedPda(String preimage, String programId) {
SHA256.Digest digest = new SHA256.Digest();
byte[] seed = digest.digest(preimage.getBytes(StandardCharsets.UTF_8));
return findProgramAddress(List.of(seed), programId);
}
private static byte[] createProgramAddress(
List<byte[]> seeds,
byte[] programId
@@ -0,0 +1,35 @@
package sync.codec;
import sync.util.SolanaPdaUtil;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
import java.util.HexFormat;
import java.util.Properties;
/** Отдельная offline-проверка, без RPC/DB; запуск через main(). */
public final class NamespaceV2VectorCheck {
public static void main(String[] args) throws Exception {
Properties p = new Properties();
try (var stream = Files.newInputStream(Path.of(args[0]))) { p.load(stream); }
String program = p.getProperty("program_id");
if (!p.getProperty("namespace_free_pda").equals(SolanaPdaUtil.findNamespacePda("free", program)))
throw new AssertionError("Namespace seed/PDA mismatch");
if (!p.getProperty("user_bob_free_pda").equals(SolanaPdaUtil.findUserPdaV2("bob@free", program)))
throw new AssertionError("User v2 seed/PDA mismatch");
byte[] raw = HexFormat.of().parseHex(p.getProperty("namespace_free_bytes_hex"));
var ns = ShineUsersCodec.parseNamespaceAccount(p.getProperty("namespace_free_pda"),
42, Base64.getEncoder().encodeToString(raw), "test-signature", program);
if (!"free".equals(ns.namespace()) || ns.type() != 2 ||
ns.registrationFeeLamports().longValueExact() != 5_000_000L ||
!"registrar@shine".equals(ns.defaultServerLogin()))
throw new AssertionError("Namespace value mismatch");
byte[] corrupt = raw.clone(); corrupt[6] ^= 1;
try {
ShineUsersCodec.parseNamespaceAccount(p.getProperty("namespace_free_pda"),
42, Base64.getEncoder().encodeToString(corrupt), "test-signature", program);
throw new AssertionError("Wrong PDA accepted");
} catch (IllegalArgumentException expected) { }
System.out.println("PASS: Java namespace decoder & SHA256 PDA test vectors");
}
}
@@ -24,4 +24,13 @@ class SolanaPdaUtilTest {
pda
);
}
@Test
void mixedCaseUsesSamePdaButNamespaceMustRemainLowercase() {
String program = "SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6";
String lower = SolanaPdaUtil.findUserPdaV2("superman@free", program);
assertEquals(lower, SolanaPdaUtil.findUserPdaV2("SuperMan@free", program));
assertEquals(lower, SolanaPdaUtil.findUserPdaV2("SUPERMAN@free", program));
org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class,
() -> SolanaPdaUtil.findUserPdaV2("SuperMan@FREE", program));
}
}
@@ -0,0 +1,105 @@
package server.ws;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import utils.config.AppConfig;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/** Single, provider-independent Solana HTTP JSON-RPC gateway. */
public final class SolanaRpcGateway extends HttpServlet {
private static final ObjectMapper JSON = new ObjectMapper();
private static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(8)).build();
private static final Set<String> METHODS = Set.of(
"getBalance", "getAccountInfo", "getMultipleAccounts", "getProgramAccounts",
"getLatestBlockhash", "getBlockHeight", "isBlockhashValid", "getFeeForMessage",
"getMinimumBalanceForRentExemption", "getSignatureStatuses", "getSignatureStatus",
"getTransaction", "getParsedTransaction", "getEpochInfo", "getSlot", "getVersion",
"getTokenAccountBalance", "getTokenAccountsByOwner", "getSignaturesForAddress",
"simulateTransaction", "getRecentPrioritizationFees", "sendTransaction"
);
private static final ConcurrentHashMap<String, Window> LIMITS = new ConcurrentHashMap<>();
private static final int MAX_BYTES = 256 * 1024;
private record Window(long minute, int count) {}
@Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) {
cors(req, resp);
resp.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
resp.setStatus(204);
}
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
cors(req, resp);
resp.setContentType("application/json; charset=utf-8");
if (req.getContentLengthLong() > MAX_BYTES) { fail(resp, 413, "Request too large"); return; }
byte[] bytes = req.getInputStream().readNBytes(MAX_BYTES + 1);
if (bytes.length > MAX_BYTES) { fail(resp, 413, "Request too large"); return; }
final JsonNode call;
try {
call = JSON.readTree(bytes);
if (call == null || !call.isObject() || !call.path("jsonrpc").asText().equals("2.0")
|| !call.has("id") || !call.path("params").isArray()
|| !METHODS.contains(call.path("method").asText())) {
fail(resp, 400, "Unsupported JSON-RPC request"); return;
}
} catch (Exception ex) { fail(resp, 400, "Invalid JSON"); return; }
boolean write = "sendTransaction".equals(call.path("method").asText());
String client = req.getRemoteAddr();
if ("127.0.0.1".equals(client) || "::1".equals(client)) {
String forwarded = req.getHeader("X-Forwarded-For");
if (forwarded != null && !forwarded.isBlank()) {
String first = forwarded.split(",", 2)[0].trim();
if (first.matches("[0-9a-fA-F:.]{3,48}")) client = first;
}
}
long minute = System.currentTimeMillis() / 60_000L;
String key = client + (write ? ":write" : ":read");
Window window = LIMITS.compute(key, (k, old) -> old == null || old.minute != minute
? new Window(minute, 1) : new Window(minute, old.count + 1));
if (window.count > (write ? 6 : 180)) { fail(resp, 429, "RPC request limit exceeded"); return; }
String rpc = AppConfig.getInstance().getStringOrEmpty("solana.rpcUrl");
if (!rpc.startsWith("https://") && !rpc.startsWith("http://")) {
fail(resp, 503, "Solana RPC is not configured"); return;
}
try {
HttpRequest upstream = HttpRequest.newBuilder(URI.create(rpc))
.timeout(Duration.ofSeconds(30)).header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofByteArray(bytes)).build();
HttpResponse<byte[]> answer = HTTP.send(upstream, HttpResponse.BodyHandlers.ofByteArray());
resp.setStatus(answer.statusCode());
resp.getOutputStream().write(answer.body());
} catch (InterruptedException ex) {
Thread.currentThread().interrupt(); fail(resp, 502, "RPC interrupted");
} catch (Exception ex) { fail(resp, 502, "RPC upstream unavailable"); }
}
private static void cors(HttpServletRequest req, HttpServletResponse resp) {
String origin = req.getHeader("Origin");
if (origin == null) return;
try {
URI uri = URI.create(origin);
String host = uri.getHost();
if (host != null && (host.equals("shineup.me") || host.endsWith(".shineup.me")
|| host.equals("localhost") || host.equals("127.0.0.1"))) {
resp.setHeader("Access-Control-Allow-Origin", origin);
resp.setHeader("Vary", "Origin");
}
} catch (IllegalArgumentException ignored) { }
}
private static void fail(HttpServletResponse response, int code, String message) throws IOException {
response.setStatus(code);
response.getWriter().write(JSON.createObjectNode().put("error", message).toString());
}
}
@@ -4,10 +4,12 @@ import server.keyrotation.KeyRotationRebuildScheduler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.archive.ArweaveBlockPublisherScheduler;
import server.archive.registration.FreeRegistrationApiBootstrap;
import server.archive.ArweaveBlockSyncScheduler;
import server.debug.DebugApiConfigurator;
import server.files.DmFileApiConfigurator;
@@ -17,6 +19,7 @@ import server.sync.PeriodicDmDeliveryService;
import server.sync.SolanaUsersSyncStartupService;
import server.sync.SyncServersBootstrapService;
import server.sync.ServerConnectionPool;
import shine.db.DbController;
import utils.config.AppConfig;
import java.time.Duration;
@@ -33,7 +36,14 @@ public final class WsServer {
public static void main(String[] args) throws Exception {
// ============================================================
// 1.0) Синхронизация пользовательских Solana PDA
// 1.0) Сначала создаём полную runtime-схему SHiNE.
// Solana sync использует ту же БД и создаёт собственные таблицы;
// без этого порядка чистая БД ошибочно выглядит для runtime как legacy.
// ============================================================
DbController.getInstance();
// ============================================================
// 1.1) Синхронизация пользовательских Solana PDA
// ============================================================
SolanaUsersSyncStartupService.startOrThrow();
@@ -64,6 +74,7 @@ public final class WsServer {
// PeriodicBlockchainSyncService is retained only as deprecated historical code.
// ANS-104: publish locally-created signed user blocks and discover blocks published by other servers.
FreeRegistrationApiBootstrap.startOrThrow();
ArweaveBlockPublisherScheduler.startOrLog();
ArweaveBlockSyncScheduler.startOrLog();
KeyRotationRebuildScheduler.startOrLog();
@@ -77,6 +88,9 @@ public final class WsServer {
context.setContextPath("/");
server.setHandler(context);
// Universal Solana HTTP JSON-RPC gateway
context.addServlet(new ServletHolder(new SolanaRpcGateway()), "/solana-rpc");
// HTTP debug API
DebugApiConfigurator.register(context);
@@ -100,7 +114,7 @@ public final class WsServer {
log.info("✅ WS сервер запущен на ws://localhost:{}/ws", port);
ServerConnectionPool.getInstance().startOrLog();
Runtime.getRuntime().addShutdownHook(new Thread(
() -> { ServerConnectionPool.getInstance().close(); ArweaveBlockPublisherScheduler.close(); ArweaveBlockSyncScheduler.close(); },
() -> { ServerConnectionPool.getInstance().close(); ArweaveBlockPublisherScheduler.close(); ArweaveBlockSyncScheduler.close(); FreeRegistrationApiBootstrap.close(); },
"server-connection-pool-shutdown"));
PeriodicDmDeliveryService.startOrLog();
server.join();
@@ -146,7 +146,7 @@ test.freeAvatar.walletJwkPath=
# ============================================================
# Arweave per-user-block transport (ANS-104)
# Test namespace: each user DataItem is signed with App=test5591.
# Test namespace: each user DataItem is signed with App=test5592.
# Channel DataItems additionally contain c=<canonical-channel-slug>.
# ============================================================
arweave.blocks.publish.enabled=false
+2 -2
View File
@@ -1,2 +1,2 @@
client.version=1.19.32
server.version=1.15.0
client.version=1.20.15
server.version=1.16.12
+177
View File
@@ -0,0 +1,177 @@
# SHiNE: разрешённые домены email для БЕСПЛАТНОЙ регистрации.
# Один домен на строку; без @. Строки с # — комментарии.
# Сопоставление строгое: поддомены не разрешаются автоматически.
# Список — политика допуска, НЕ гарантия доставки; некоторые адреса исторические.
# Изменения вступают в силу после перезапуска Java-сервера.
# Google
gmail.com
googlemail.com
# Microsoft
outlook.com
outlook.de
outlook.fr
outlook.es
outlook.it
outlook.jp
hotmail.com
hotmail.co.uk
hotmail.de
hotmail.fr
hotmail.es
hotmail.it
hotmail.com.br
hotmail.co.jp
hotmail.com.au
live.com
live.co.uk
live.de
live.fr
live.nl
live.com.au
msn.com
# Yandex
yandex.ru
yandex.com
ya.ru
yandex.by
yandex.kz
yandex.ua
# Mail.ru
mail.ru
bk.ru
list.ru
inbox.ru
internet.ru
# Apple
icloud.com
me.com
mac.com
# Proton
proton.me
protonmail.com
protonmail.ch
pm.me
# Yahoo
yahoo.com
yahoo.co.uk
yahoo.de
yahoo.fr
yahoo.es
yahoo.it
yahoo.ca
yahoo.com.br
yahoo.co.jp
yahoo.com.au
yahoo.co.in
yahoo.com.mx
yahoo.com.sg
yahoo.com.hk
yahoo.com.tw
ymail.com
rocketmail.com
# Rambler
rambler.ru
lenta.ru
autorambler.ru
myrambler.ru
ro.ru
# Germany / DACH
gmx.de
gmx.com
gmx.net
gmx.at
gmx.ch
web.de
mailbox.org
posteo.de
# Poland
wp.pl
onet.pl
interia.pl
o2.pl
gazeta.pl
poczta.fm
op.pl
# Privacy-oriented services
tuta.com
tutanota.com
tutanota.de
tutanota.org
tutamail.com
keemail.me
startmail.com
runbox.com
disroot.org
# France
orange.fr
wanadoo.fr
laposte.net
free.fr
sfr.fr
netcourrier.com
# Italy
libero.it
virgilio.it
alice.it
tin.it
# Czechia and Slovakia
seznam.cz
email.cz
post.cz
centrum.cz
atlas.cz
centrum.sk
azet.sk
# Ukraine
ukr.net
i.ua
# Other Europe
abv.bg
mail.bg
freemail.hu
citromail.hu
# Korea
naver.com
daum.net
hanmail.net
nate.com
# China
qq.com
163.com
126.com
yeah.net
sina.com
sohu.com
139.com
# Brazil
bol.com.br
uol.com.br
ig.com.br
# International
zohomail.com
zoho.com
fastmail.com
aol.com
mail.com
email.com
hey.com
+34
View File
@@ -0,0 +1,34 @@
# SHiNE configuration EXAMPLE. This file is never loaded automatically.
# Copy it to application.properties in the server working directory,
# or provide a private application.properties on the server classpath.
# Never commit application.properties with real credentials.
# Database: replace with your own test/server values.
db.url=jdbc:postgresql://localhost:5432/shine
db.user=
db.password=
server.SHiNE.login=
# Solana/Arweave: disabled until configured.
solana.cluster=devnet
solana.rpcUrl=
solana.users.sync.enabled=false
blockchain.sync.enabled=false
sync.importUserProfileFromPartner.enabled=false
arweave.blocks.publish.enabled=false
arweave.blocks.sync.enabled=false
# Temporary / testing endpoints: off by default.
debug.tempApi.enabled=false
test.freeAvatar.enabled=false
# Other services: fill in real values only in the private config.
dm.delivery.enabled=false
webpush.vapid.public=
webpush.vapid.private=
webpush.vapid.subject=
call.ice.turn.sharedSecret=
# Email verification for free registration: requires the separate allowlist file.
# The deployment script copies allowed-email-domains.txt alongside shine-server.jar.
freeRegistration.email.allowedDomainsFile=allowed-email-domains.txt
+3 -4
View File
@@ -185,9 +185,8 @@ tasks.register('integrationTest', JavaExec) {
dependsOn testClasses
}
tasks.named('build') {
finalizedBy tasks.named('integrationTest')
}
// integrationTest is intentionally NOT attached to build.
// It performs destructive clean-start actions and must be requested explicitly.
tasks.register('startLocal', Exec) {
group = "!!run"
@@ -236,7 +235,7 @@ tasks.register('startLocal', Exec) {
(
cd "${file('SHiNE-server').absolutePath}"
java -Dserver.port="\$WS_PORT" -jar "\$JAR_PATH"
java -Dserver.port="\$WS_PORT" -DfreeRegistration.email.allowedDomainsFile="${file('allowed-email-domains.txt').absolutePath}" -jar "\$JAR_PATH"
) &
SERVER_PID=\$!
trap 'kill \$SERVER_PID 2>/dev/null || true' EXIT INT TERM
+5 -1
View File
@@ -63,7 +63,11 @@ is_denied_path() {
*/scripts/*/runs/*|\
*/scripts/*/keypairs/*|\
*/keys/*|\
*/.git-local-backup/*)
*/.git-local-backup/*|\
/application.properties|\
*/SHiNE-server/src/main/resources/application.properties|\
*/deploy/backup/scheme/*|\
*/shine-solana/shine/create-SHiNE-DAO/dao.config.mainnet.env)
return 0
;;
esac
+2 -1
View File
@@ -41,7 +41,8 @@
Общие скрипты:
- `scripts/deploy_server.sh` — обновить существующий серверный jar и перезапустить systemd service.
- `scripts/deploy_server.sh` — обновить существующий серверный jar, скопировать `allowed-email-domains.txt`
в рабочую папку сервера и перезапустить systemd service (список доменов требуется при включённой бесплатной регистрации).
- `scripts/deploy_ui.sh` — обновить существующий UI, проверить Caddy root и подставить `deploy-config.js`.
## Временные статические сайты
@@ -0,0 +1,14 @@
# Caddy: проксирование SolanaRpcGateway
Добавьте перед общим `handle` с UI / SPA в **каждый** site block SHiNE:
```caddyfile
@solana_rpc path /solana-rpc
handle @solana_rpc {
reverse_proxy 127.0.0.1:7070
}
```
Порт `7070` приведён для основного сервера из резервной конфигурации. У t1/t2/t3/t4 используйте фактический локальный Java-порт (например, 7102). Не заменяйте существующие настройки сервера целиком этой вставкой.
Далее: `caddy validate --config /etc/caddy/Caddyfile`, перезагрузите Caddy и проверьте `POST https://<ваш-сервер>/solana-rpc` с JSON-RPC `getVersion`.
+42 -2
View File
@@ -5,7 +5,7 @@
## Что уже есть
- основной сервер запускает `SolanaUsersSyncStartupService` до продолжения startup;
- основной сервер сначала инициализирует полную PostgreSQL runtime-схему SHiNE, затем запускает `SolanaUsersSyncStartupService` до продолжения startup;
- модуль синхронизации держит актуальными таблицы:
- `solana_sync_state`
- `solana_sync_tx_history`
@@ -56,7 +56,7 @@ psql \
-f SHiNE-server/shine-server-db/src/main/resources/postgres/schema_v1.sql
```
Скрипт предназначен **только для полностью пустой PostgreSQL схемы**. На старой/непустой базе он завершится ошибкой и не выполняет in-place migration.
Скрипт предназначен **только для полностью пустой PostgreSQL схемы**. На старой/непустой базе он завершится ошибкой и не выполняет in-place migration. При обычном первом запуске вручную выполнять его не нужно: сервер сам первым создаёт полную runtime-схему, и только затем стартует Solana sync; это не даёт sync-таблицам ошибочно выглядеть как legacy-БД.
Скрипт:
@@ -125,3 +125,43 @@ Migration v26 добавляет server-local поля `rotation_status` / `rota
## Миграции key rotation
При обновлении сервера DatabaseInitializer последовательно применяет migration v26 (state machine смены ключей) и v27 (отдельные candidate-блоки будущего fork). Ручного создания таблиц не требуется. Candidate-блоки не входят в текущую таблицу `blocks` до финального переключения fork.
## Этапы регистрации V2 4–7: подготовка тестового окружения (23.10.2026)
Перед запуском новой синхронизации нужен тестовый `shine_users` (opcode 7, namespace accounts), применённая PostgreSQL v33, бэкап и отдельная БД. Только после этого разрешён импорт namespace в отдельный регистр `shine_namespace_current`. Не совмещать с существующим UI/production. `freeRegistration.enabled` по умолчанию false; `freeRegistration.registrarSeedFile` — локальный secret path (Base64 seed32) вне Git. При несоответствии регистратора публичному ключу on-chain namespace выдача сертификата прекращается. Нет Arweave importer до этапа 8, API/UI до этапов 9–10. Сначала прогоните чистый snapshot, историю, restart/replay, FK и ключевую ротацию на тестовом контуре.
## DB v35: единый платный статус (26.10.2026)
`DatabaseInitializer` при запуске сервера последовательно обновляет схему до v35. Старые
`PAID_DIRECT` и `PAID_UPGRADED` преобразуются в единый `PAID`; `FREE_CERT` не изменяется.
Любой новый пользователь с настоящей PDA Solana получает `PAID` независимо от способа регистрации.
Данные аккаунтов, Arweave-сертификаты, начальная дата регистрации и ключи не удаляются.
Порядок на тестовом контуре: резервная копия БД → обновление серверного кода с `migration_v35.sql`
→ перезапуск и проверка `db_schema_version=35` → обновление UI → пробная регистрация и upgrade.
До обновления сервера или при неудачной миграции оставьте существующий UI: новое значение `PAID`
должно приходить только от сервера с применённой v35. На production — отдельное согласование.
Для проверки статусов после миграции:
```sql
SELECT registration_status, count(*) FROM user_identity_current GROUP BY registration_status;
SELECT schema_version FROM db_schema_version WHERE id=1;
```
## Регистронезависимый логин (2026-10-28)
Для новых баз важно совместное обновление программы `shine_users`, Java Solana sync/архива и UI. После обновления `login` внутри PDA сохраняет регистр, а адрес и `normalized_login` используют lowercase. Перед проверкой смешанного регистра заново инициализируйте **тестовую** БД и разверните обновлённую Solana-программу в devnet; сам ZIP её не разворачивает.
## 2026-10-28 — Неизменяемый регистр логина (PostgreSQL v37)
- В `user_identity_current.login` хранится **написание первой регистрации**, включая заглавные буквы. В `normalized_login` — его lowercase-форма для поиска и уникальности.
- v37 добавляет BEFORE INSERT/UPDATE-проверку: `normalized_login = lower(btrim(login))`, а после создания идентичности оба поля неизменяемы.
- `shine_sync_identity_from_solana()` отклоняет PDA, если для того же нормализованного имени его `login` не совпадает **точно** с Arweave-сертификатом или предыдущей регистрацией. При FREE_CERT → PAID нельзя изменять только регистр.
- Сервер перед первым `AddBlock` сверяет HEADER с точным `user_identity_current.login`; нормализованное имя цепочки этому не противоречит.
- Никакого преобразования существующих signed-блоков нет; новая тестовая эпоха создаётся с чистой БД и без старых HEADER.
## PostgreSQL v38: ключ blockchain state
После обновления сервера `DatabaseInitializer` автоматически применит migration v38 и при старте нормализует `blockchain_state_store.blockchain_key` из исторического Base58 в Base64(32). Ручной SQL-апдейт для free-пользователей не нужен. После запуска проверьте, что первый `AddBlock` нового free-пользователя проходит без `BAD_BLOCKCHAIN_KEY_LEN`.
+6
View File
@@ -14,6 +14,7 @@ REMOTE_PUBLIC_FILES_DIR="${REMOTE_PUBLIC_FILES_DIR:-}"
REMOTE_SERVICE_NAME="${REMOTE_SERVICE_NAME:?REMOTE_SERVICE_NAME is required}"
SERVER_PORT="${SERVER_PORT:?SERVER_PORT is required}"
LOCAL_JAR="${LOCAL_JAR:-$ROOT_DIR/SHiNE-server/build/libs/shine-server.jar}"
LOCAL_EMAIL_DOMAINS="${LOCAL_EMAIL_DOMAINS:-$ROOT_DIR/allowed-email-domains.txt}"
BUILD_JAR="${BUILD_JAR:-1}"
REQUIRE_BACKUP="${REQUIRE_BACKUP:-0}"
BACKUP_DIR="${BACKUP_DIR:-$ROOT_DIR/deploy/backup/archive}"
@@ -34,6 +35,10 @@ if [[ ! -f "$LOCAL_JAR" ]]; then
echo "ERROR: локальный jar не найден: $LOCAL_JAR" >&2
exit 1
fi
if [[ ! -s "$LOCAL_EMAIL_DOMAINS" ]]; then
echo "ERROR: не найден или пуст список почтовых доменов: $LOCAL_EMAIL_DOMAINS" >&2
exit 1
fi
echo "==> Deploy server to $TARGET_DOMAIN ($REMOTE_HOST)"
ssh -o BatchMode=yes -o ConnectTimeout=20 "$REMOTE_HOST" "echo SSH OK" >/dev/null
@@ -69,6 +74,7 @@ REMOTE_EXTRA_DIRS=""
[[ -n "$REMOTE_PUBLIC_FILES_DIR" ]] && REMOTE_EXTRA_DIRS+=" '$REMOTE_PUBLIC_FILES_DIR'"
ssh "$REMOTE_HOST" "mkdir -p '$REMOTE_SERVER_DIR' '$REMOTE_DATA_DIR' '$REMOTE_LOGS_DIR'$REMOTE_EXTRA_DIRS"
rsync -az --timeout=120 "$LOCAL_JAR" "$REMOTE_HOST:$REMOTE_SERVER_DIR/shine-server.jar"
rsync -az --timeout=120 "$LOCAL_EMAIL_DOMAINS" "$REMOTE_HOST:$REMOTE_SERVER_DIR/allowed-email-domains.txt"
rsync -az "$TMP_DIR/$REMOTE_SERVICE_NAME.service" "$REMOTE_HOST:/tmp/$REMOTE_SERVICE_NAME.service"
ssh "$REMOTE_HOST" "set -euo pipefail; \
+2 -1
View File
@@ -65,7 +65,8 @@ rsync -a "$SRC_DIR"/ "$TMP_DIR"/
DEPLOY_CONFIG_FILE="$TMP_DIR/js/deploy-config.js"
if [[ -f "$DEPLOY_CONFIG_FILE" ]]; then
if [[ -n "$DEPLOY_SERVER_LOGIN" ]]; then
perl -0pi -e "s/export const defaultServerLogin = '.*?';/export const defaultServerLogin = '$DEPLOY_SERVER_LOGIN';/s" "$DEPLOY_CONFIG_FILE"
export DEPLOY_SERVER_LOGIN
perl -0pi -e 's/export const defaultServerLogin = '\''[^'\'']*'\'';/export const defaultServerLogin = '\''$ENV{DEPLOY_SERVER_LOGIN}'\'';/' "$DEPLOY_CONFIG_FILE"
fi
if [[ -n "$DEPLOY_SERVER_ADDRESS" ]]; then
perl -0pi -e "s/export const defaultServerAddress = '.*?';/export const defaultServerAddress = '$DEPLOY_SERVER_ADDRESS';/s" "$DEPLOY_CONFIG_FILE"
+1 -1
View File
@@ -5,7 +5,7 @@ REMOTE_HOST="player@t2.shineup.me" \
REMOTE_UI_DIR="/home/player/t2/UI" \
EXPECTED_CADDY_UI_ROOT="/home/player/t2/UI" \
EXPECTED_CADDY_SITE="t2.shineup.me" \
DEPLOY_SERVER_LOGIN="server_t2" \
DEPLOY_SERVER_LOGIN="server_t2@shine" \
DEPLOY_SERVER_ADDRESS="t2.shineup.me" \
DEPLOY_SOLANA_CLUSTER="devnet" \
DEPLOY_SOLANA_ENDPOINT="https://devnet.helius-rpc.com/?api-key=0614c894-52d8-4ddc-bbbc-0947ce5ec3a4" \
+1 -1
View File
@@ -5,7 +5,7 @@ REMOTE_HOST="player@t3.shineup.me" \
REMOTE_UI_DIR="/home/player/t3/UI" \
EXPECTED_CADDY_UI_ROOT="/home/player/t3/UI" \
EXPECTED_CADDY_SITE="t3.shineup.me" \
DEPLOY_SERVER_LOGIN="server_t3" \
DEPLOY_SERVER_LOGIN="server_t3@shine" \
DEPLOY_SERVER_ADDRESS="t3.shineup.me" \
DEPLOY_SOLANA_CLUSTER="devnet" \
DEPLOY_SOLANA_ENDPOINT="https://devnet.helius-rpc.com/?api-key=0614c894-52d8-4ddc-bbbc-0947ce5ec3a4" \
+8
View File
@@ -171,3 +171,11 @@
- `GetUser` — проверка существования пользователя на сервере.
- `SearchUsers` — временный поиск пользователей по префиксу.
- Регистрация выполняется только через Solana.
## Регистрация V2: полные логины и независимые проверки
Публичные WS-операции нового протокола перечислены в `docs/registration-v2/WS_REGISTRATION_V2_PROPOSED_NOT_ENABLED.md`.
Сначала `GetNamespaces` → `CheckRegistrationLogin` с полным `login@namespace`; затем **только для бесплатной регистрации** отдельное `CheckRegistrationEmail`. После проверки запускается `StartFreeRegistration`, затем `ConfirmFreeRegistration` с шестизначным одноразовым кодом из письма (1 час, 5 попыток). Состояние читается через `GetRegistrationStatus`.
Все бесплатные сертификаты подписаны ANS-104 и внутренней подписью Ed25519; успешный Turbo ACK не означает подтверждённую высоту Arweave. Клиент никогда не отправляет пароль или приватные ключи на сервер.
+2 -2
View File
@@ -32,14 +32,14 @@
- generic Ed25519 signature type `2`;
- Ed25519 signature 64 bytes;
- owner 32 bytes и равен текущему blockchain public key;
- обязательный тестовый tag `App=test5591`;
- обязательный тестовый tag `App=test5592`;
- для channel block — `c=<canonical_channel_slug>`;
- `TEXT_CHANNEL_DELETE (type=1/subType=92/version=1)` является обычным line-based channel block с пустым text и тем же обязательным `c=<slug>`; отдельной операции API для удаления канала нет;
- `data` содержит SHiNE Frame v1 (`frameCode=1`).
## Основные ошибки
- `bad_app_tag` — отсутствует/неверен `App=test5591`;
- `bad_app_tag` — отсутствует/неверен `App=test5592`;
- `bad_channel_tag` — `c` отсутствует, лишний или не совпадает с canonical slug;
- `bad_signature` / `signature_verify_failed` — DataItem не подписан текущим blockchain key;
- `bad_block_number` — нарушена последовательность;
+4
View File
@@ -642,3 +642,7 @@ Changing `account_role` or `shine` does not alter the raw reaction. The two qual
`ownerBlockchainName` и корневой блок позволяют клиенту открыть канонический канал через существующую маршрутизацию.
Неверные поля: HTTP-подобный статус `400`, код `BAD_FIELDS`; ошибки чтения БД: `SERVER_DATA_ERROR`, `DB_ERROR`.
Структура блокчейна не меняется. Индексы поиска добавлены миграцией БД v32 (`pg_trgm`).
## 2026-10-28 — Официальный регистр логинов при чтении
В ответах `GetChannelMessages`, `GetMessageThread`, `ListSubscriptionsFeed` поля `authorLogin` и `ownerLogin` показывают **регистрационное написание** из `user_identity_current`, например `AlexSmith@shine`. В БД блока и в `blockchainName` по-прежнему возможен lowercase, используемый как нормализованный идентификатор. Это не меняет имена JSON-полей или типы значений, а уточняет их семантику. Для поиска и переходов разные варианты регистра по-прежнему ссылаются на одну идентичность; байты уже подписанных блоков не переписываются.
+22
View File
@@ -95,3 +95,25 @@
- HTTP endpoints публичных content-addressed файлов (`PUT/GET/HEAD/OPTIONS /files/{sha256}`) также не являются WebSocket `op` и описаны отдельно в `21_Public_File_Storage_API.md`.
- Классы `Net_MarkChannelMessagesSeen_*` существуют в коде, но операция `MarkChannelMessagesSeen` не зарегистрирована в `JsonHandlerRegistry`, поэтому в публичный список API не входит.
- HTTP debug endpoints из `src/main/java/server/debug/` не входят в этот индекс WebSocket `op`; они описаны отдельно в `13_HTTP_Debug_API.md`.
## Registration V2 (добавлено 23.10.2026, test/dev only)
- `GetNamespaces` — список зарегистрированных namespace из Solana-синхронизации;
- `CheckRegistrationLogin` — отдельная проверка `login@namespace`;
- `CheckRegistrationEmail` — отдельная проверка email;
- `StartFreeRegistration` — запрос сертификата по трём публичным ключам;
- `ConfirmFreeRegistration` — подтверждение тестовым кодом и Turbo ACK;
- `GetRegistrationStatus` — статус и публичные поля сертификата для upgrade.
Точный JSON и ограничения: `docs/registration-v2/WS_REGISTRATION_V2_PROPOSED_NOT_ENABLED.md` (имя сохранено для обратных ссылок; внутри утверждённая версия).
### `GetRegistrationStatus` после DB v35
Для существующего пользователя `payload.registrationStatus` имеет одно из **двух** значений:
`FREE_CERT` (бесплатная регистрация Arweave) или `PAID` (подтверждённая PDA Solana).
`PAID` применяется и к первоначально платным, и к ранее бесплатным пользователям;
`NOT_FOUND` остаётся техническим ответом для отсутствующего логина.
Во время поэтапного развертывания старый сервер может ещё возвращать `PAID_DIRECT`
или `PAID_UPGRADED`; обновлённый UI понимает эти устаревшие ответы как платные.
Поля сертификата для `FREE_CERT` и остальные поля API не меняются.
@@ -324,10 +324,16 @@ signed-блока проверяется всегда. Официальный UI
"timeMs": 1774700000123,
"nonce": 123456789,
"blobB64": "BASE64_SIGNED_BLOCK",
"backlog": false
"backlog": false,
"unreadCount": 3,
"notificationVersionMs": 1774700000456
}
```
`unreadCount` и `notificationVersionMs` добавляются только для нового входящего type=1 при обычной realtime-доставке. Это серверный снимок `dm_dialog_state`; для backlog, read-receipts и других типов эти поля могут отсутствовать. `notificationVersionMs` монотонно увеличивается при обновлении состояния конкретной переписки; формат подписанного блока не меняется.
При отсутствии активного WebSocket сервер отправляет Web Push с полями `kind=new_message`, `toLogin`, `fromLogin`, `messageKey`, `unreadCount`, `notificationVersionMs`. Push не содержит расшифрованного текста. Service Worker показывает по одной карточке на пару (получатель, отправитель), обновляя счётчик с запросом нового звукового оповещения для каждого нового сообщения.
Если это новая ревизия того же письма, `messageKey` остаётся тем же, а `revisionTimeMs` меняется внутри бинарного блока.
Для типов `5/6/7/8` событие тоже приходит в таком же конверте, но логика применения определяется `messageType` и бинарным `blobB64`.

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