From 80c70ebcdc264328215fe56c6834b39b1633cea1a3983025fdf5701ff0f10ad4 Mon Sep 17 00:00:00 2001 From: AidarKC Date: Sat, 21 Nov 2026 01:09:37 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9E=D0=B3=D1=80=D0=B0=D0=BD=D0=B8=D1=87?= =?UTF-8?q?=D0=B8=D1=82=D1=8C=20=D0=B1=D0=B5=D1=81=D0=BF=D0=BB=D0=B0=D1=82?= =?UTF-8?q?=D0=BD=D1=83=D1=8E=20=D1=80=D0=B5=D0=B3=D0=B8=D1=81=D1=82=D1=80?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D1=8E=20namespace=20=D1=81=D0=B5=D1=80=D0=B2?= =?UTF-8?q?=D0=B5=D1=80=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FreeRegistrationApiBootstrap.java | 9 +++-- .../registration/FreeRegistrationIssuer.java | 24 +++++++++++++ .../FreeRegistrationWorkflow.java | 34 +++++++++++++++---- ...egistrationNamespaceConfigurationTest.java | 20 +++++++++++ VERSION.properties | 4 +-- .../REGISTRAR_CONFIGURATION.md | 3 +- .../registration-v2/WS_REGISTRATION_V2_API.md | 2 +- shine-UI/js/pages/registration-choice-view.js | 25 +++++++++----- 8 files changed, 101 insertions(+), 20 deletions(-) create mode 100644 SHiNE-server/shine-server-archive/src/test/java/server/archive/registration/FreeRegistrationNamespaceConfigurationTest.java diff --git a/SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/FreeRegistrationApiBootstrap.java b/SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/FreeRegistrationApiBootstrap.java index e5bdd0bb..c694678c 100644 --- a/SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/FreeRegistrationApiBootstrap.java +++ b/SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/FreeRegistrationApiBootstrap.java @@ -33,7 +33,9 @@ public final class FreeRegistrationApiBootstrap { FreeRegistrationPublisher publisher=null; RegistrationEmailSender emailSender=null; AllowedEmailDomains allowedEmailDomains=null; - if (cfg.getBoolean("freeRegistration.enabled",false)) { + String freeNamespace=cfg.getStringOrEmpty("freeRegistration.namespace").trim(); + boolean freeRegistrationEnabled=cfg.getBoolean("freeRegistration.enabled",false) && !freeNamespace.isEmpty(); + if (freeRegistrationEnabled) { String domainsFile = cfg.getStringOrEmpty("freeRegistration.email.allowedDomainsFile"); if (domainsFile.isBlank()) domainsFile = "allowed-email-domains.txt"; // Относительный путь — от WorkingDirectory процесса Java. @@ -44,6 +46,8 @@ public final class FreeRegistrationApiBootstrap { if(transport.publishMode()!=ArweaveBlocksConfig.PublishMode.TURBO) throw new IllegalStateException("Free registration requires Turbo transport"); newSigner=LocalRegistrarSigner.fromConfig(cfg); + FreeRegistrationIssuer.validateConfiguredNamespace(dbSource(), newSigner, freeNamespace, + cfg.getStringOrEmpty("server.SHiNE.login")); issuer=new FreeRegistrationIssuer(dbSource(),newSigner,allowEmailReuse); publisher=new FreeRegistrationPublisher(issuer,new TurboDataItemUploader(transport), new VerifiedFreeRegistrationImporter(allowEmailReuse)); @@ -58,7 +62,8 @@ public final class FreeRegistrationApiBootstrap { } FreeRegistrationWorkflow newWorkflow=new FreeRegistrationWorkflow(issuer,publisher,emailSender, cfg.getBoolean("freeRegistration.email.allowTestCode",false), - cfg.getBoolean("freeRegistration.email.allowReuse",false), allowedEmailDomains); + cfg.getBoolean("freeRegistration.email.allowReuse",false), allowedEmailDomains, + freeRegistrationEnabled ? freeNamespace : ""); RegistrationApiBridge.install((op,req)->dispatch(newWorkflow,op,req)); signer=newSigner; workflow=newWorkflow; } diff --git a/SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/FreeRegistrationIssuer.java b/SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/FreeRegistrationIssuer.java index 41fa4873..821bd2c9 100644 --- a/SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/FreeRegistrationIssuer.java +++ b/SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/FreeRegistrationIssuer.java @@ -24,6 +24,30 @@ public final class FreeRegistrationIssuer { this.allowEmailReuse = allowEmailReuse; } + /** Проверяет привязку локального ключа и сервера до открытия бесплатной регистрации. */ + static void validateConfiguredNamespace(DataSource db, RegistrarSigner signer, String namespace, + String localServerLogin) throws Exception { + if (localServerLogin == null || localServerLogin.isBlank()) + throw new IllegalStateException("server.SHiNE.login is required for free registration"); + try (Connection conn = db.getConnection(); + PreparedStatement statement = conn.prepareStatement(""" + SELECT namespace_type, registrar_pubkey, default_server_login + FROM shine_namespace_current WHERE namespace = ? + """)) { + statement.setString(1, namespace); + try (ResultSet rs = statement.executeQuery()) { + if (!rs.next() || rs.getInt("namespace_type") != 2) + throw new IllegalStateException("Configured free registration namespace is unavailable"); + byte[] namespaceKey = Base58Util.decode(rs.getString("registrar_pubkey")); + if (!Arrays.equals(namespaceKey, signer.publicKey32())) + throw new IllegalStateException("Registrar public key does not match configured namespace"); + String namespaceServer = rs.getString("default_server_login"); + if (namespaceServer == null || !namespaceServer.equalsIgnoreCase(localServerLogin.trim())) + throw new IllegalStateException("Configured free namespace belongs to another access server"); + } + } + } + /** Выдаётся только после успешной проверки challenge в FreeRegistrationWorkflow. */ synchronized byte[] issue(String fullLogin, byte[] root32, byte[] blockchain32, byte[] client32, String email) throws Exception { diff --git a/SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/FreeRegistrationWorkflow.java b/SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/FreeRegistrationWorkflow.java index 2c7bd2c1..0e0af93c 100644 --- a/SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/FreeRegistrationWorkflow.java +++ b/SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/FreeRegistrationWorkflow.java @@ -51,10 +51,12 @@ public final class FreeRegistrationWorkflow { private final boolean allowTestCode; private final boolean allowEmailReuse; private final AllowedEmailDomains allowedEmailDomains; + /** Единственный type-2 namespace, для которого этот сервер является регистратором. */ + private final String freeRegistrationNamespace; public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher, RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse, - AllowedEmailDomains allowedEmailDomains) { + AllowedEmailDomains allowedEmailDomains, String freeRegistrationNamespace) { if ((issuer == null) != (publisher == null)) throw new IllegalArgumentException("Signer/publisher mismatch"); if (issuer != null && emailSender == null) throw new IllegalArgumentException("Email sender is required"); if (emailSender != null && allowedEmailDomains == null) @@ -65,11 +67,24 @@ public final class FreeRegistrationWorkflow { this.emailSender = emailSender; this.allowTestCode = allowTestCode; this.allowEmailReuse = allowEmailReuse; + this.freeRegistrationNamespace = normalizeConfiguredNamespace(freeRegistrationNamespace); + } + public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher, + RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse, + AllowedEmailDomains allowedEmailDomains) { + this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse, allowedEmailDomains, ""); + } + private static String normalizeConfiguredNamespace(String value) { + String namespace = value == null ? "" : value.trim(); + if (namespace.isEmpty()) return ""; + if (!namespace.matches("[a-z0-9_]+")) + throw new IllegalArgumentException("Free registration namespace must use lowercase ASCII letters, digits or _"); + return namespace; } public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher, RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse) { this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse, - emailSender == null ? null : loadDefaultEmailDomains()); + emailSender == null ? null : loadDefaultEmailDomains(), ""); } private static AllowedEmailDomains loadDefaultEmailDomains() { try { @@ -94,10 +109,15 @@ public final class FreeRegistrationWorkflow { try (Connection c = DbController.getInstance().getConnection(); PreparedStatement ps = c.prepareStatement(""" SELECT namespace,namespace_type,min_localpart_len,registration_fee_lamports,currency_code,default_server_login - FROM shine_namespace_current ORDER BY namespace - """); ResultSet rs = ps.executeQuery()) { - while (rs.next()) result.add(new NamespaceInfo(rs.getString(1),rs.getInt(2),rs.getInt(3), - rs.getString(4),rs.getInt(5),rs.getString(6))); + FROM shine_namespace_current + WHERE namespace_type = 1 OR (namespace_type = 2 AND namespace = ?) + ORDER BY namespace + """)) { + ps.setString(1, freeRegistrationNamespace); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) result.add(new NamespaceInfo(rs.getString(1),rs.getInt(2),rs.getInt(3), + rs.getString(4),rs.getInt(5),rs.getString(6))); + } } return List.copyOf(result); } @@ -111,6 +131,8 @@ public final class FreeRegistrationWorkflow { try (ResultSet rs=p.executeQuery()) { if (!rs.next()) throw new IllegalArgumentException("Namespace is unavailable"); type=rs.getInt(1); minimum=rs.getInt(2); fee=rs.getString(3); currencyCode=rs.getInt(4); + if (type == 2 && !namespace.equals(freeRegistrationNamespace)) + throw new IllegalArgumentException("Free registration is unavailable for this namespace"); if (currencyCode != 1) throw new IllegalStateException("Unsupported namespace currency"); if (login.indexOf('@') < minimum) throw new IllegalArgumentException("Login shorter than namespace minimum"); } diff --git a/SHiNE-server/shine-server-archive/src/test/java/server/archive/registration/FreeRegistrationNamespaceConfigurationTest.java b/SHiNE-server/shine-server-archive/src/test/java/server/archive/registration/FreeRegistrationNamespaceConfigurationTest.java new file mode 100644 index 00000000..aba0aec8 --- /dev/null +++ b/SHiNE-server/shine-server-archive/src/test/java/server/archive/registration/FreeRegistrationNamespaceConfigurationTest.java @@ -0,0 +1,20 @@ +package server.archive.registration; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class FreeRegistrationNamespaceConfigurationTest { + @Test + void acceptsLowercaseNamespaceForLocalFreeRegistration() { + assertDoesNotThrow(() -> new FreeRegistrationWorkflow( + null, null, null, false, false, null, "testfree")); + } + + @Test + void rejectsMixedCaseNamespaceInsteadOfSilentlyServingAnotherNamespace() { + assertThrows(IllegalArgumentException.class, () -> new FreeRegistrationWorkflow( + null, null, null, false, false, null, "TestFree")); + } +} diff --git a/VERSION.properties b/VERSION.properties index 6f1a2d60..4947aca0 100644 --- a/VERSION.properties +++ b/VERSION.properties @@ -1,2 +1,2 @@ -client.version=1.20.64 -server.version=1.16.31 +client.version=1.20.65 +server.version=1.16.32 diff --git a/docs/registration-v2/REGISTRAR_CONFIGURATION.md b/docs/registration-v2/REGISTRAR_CONFIGURATION.md index 37599ede..5a5f4250 100644 --- a/docs/registration-v2/REGISTRAR_CONFIGURATION.md +++ b/docs/registration-v2/REGISTRAR_CONFIGURATION.md @@ -4,7 +4,8 @@ ## Конфигурация -- `freeRegistration.enabled=false` по умолчанию. Включается только на тестовом сервере после проверки соответствия namespace. +- `freeRegistration.enabled=false` по умолчанию. Для включения обязательно одновременно задать `freeRegistration.namespace=`: это единственный type-2 namespace, в котором данный сервер выдаёт бесплатные аккаунты. Если namespace не задан или `enabled=false`, сервер публикует только платные namespace и не показывает в UI вариант бесплатной регистрации. +- При включении сервер до начала работы сверяет, что указанный namespace имеет type 2, его `default_server_login` совпадает с `server.SHiNE.login`, а `registrar_pubkey` — с публичным ключом из seed. При несовпадении запуск прекращается; чужой namespace нельзя случайно обслужить. - `freeRegistration.registrarSeedFile` — абсолютный путь к файлу вне Git, внутри одна Base64-строка **32-byte Ed25519 seed**. Пример имени `/var/lib/shine/secrets/registrar-seed.b64`; не создавать файл с тестовым ключом внутри репозитория. - `LocalRegistrarSigner.fromConfig(AppConfig)` проверяет enabled и наличие пути, не печатает секрет или bytes в лог. - Публичный ключ signer должен совпадать с `shine_namespace_current.registrar_pubkey` (из on-chain namespace), иначе `FreeRegistrationIssuer.issue` отказывает. diff --git a/docs/registration-v2/WS_REGISTRATION_V2_API.md b/docs/registration-v2/WS_REGISTRATION_V2_API.md index c7524c60..be6621bb 100644 --- a/docs/registration-v2/WS_REGISTRATION_V2_API.md +++ b/docs/registration-v2/WS_REGISTRATION_V2_API.md @@ -13,7 +13,7 @@ | `ConfirmFreeRegistration` | `challengeId,code` (случайный шестизначный код из письма) | `fullLogin,dataItemId,publicationStatus,chainConfirmed:false` | выпуск+Turbo ACK+локальный импорт | | `GetRegistrationStatus` | `fullLogin` | `registrationStatus,dataItemId,publicationStatus`; для FREE_CERT дополнительно `innerSignature64B64,rootPublicKey,blockchainPublicKey,clientPublicKey,defaultServerLogin` | retry/upgrade | -`registrationFeeLamports` — строка десятичного целого u64. `currencyCode` — числовой код: `1` = SOL; `2` зарезервирован, сервер не принимает его до реализации USDT. Сервер отдаёт актуальный кэш namespace после sync Solana, UI перед платной транзакцией дополнительно читает значение напрямую из Solana. Публичные ключи запроса — Base64 от ровно 32 байт (не PKCS#8). `innerSignature64B64` — Base64 внутренней подписи Ed25519, публичная информация сертификата; PRIVATE-ключ регистратора никогда не отдаётся. +`registrationFeeLamports` — строка десятичного целого u64. `currencyCode` — числовой код: `1` = SOL; `2` зарезервирован, сервер не принимает его до реализации USDT. Сервер отдаёт актуальный кэш namespace после sync Solana, UI перед платной транзакцией дополнительно читает значение напрямую из Solana. `GetNamespaces` всегда содержит платные namespace и содержит type-2 namespace только когда на этом access-сервере явно включён и проверен `freeRegistration.namespace`; другие type-2 namespace не возвращаются и не принимаются в `CheckRegistrationLogin`. Публичные ключи запроса — Base64 от ровно 32 байт (не PKCS#8). `innerSignature64B64` — Base64 внутренней подписи Ed25519, публичная информация сертификата; PRIVATE-ключ регистратора никогда не отдаётся. **Ошибки:** `REGISTRATION_UNAVAILABLE` 503, `INVALID_REGISTRATION_INPUT` 400, `REGISTRATION_CONFLICT` 409, `RATE_LIMITED` 429, прочие 500 требуют анализа логов без раскрытия секретов. Проверка логина и email *не резервирует* их; перед подписью и перед импортом делается повторная проверка. diff --git a/shine-UI/js/pages/registration-choice-view.js b/shine-UI/js/pages/registration-choice-view.js index a4349ddc..d679801b 100644 --- a/shine-UI/js/pages/registration-choice-view.js +++ b/shine-UI/js/pages/registration-choice-view.js @@ -1,6 +1,7 @@ import { t } from '../i18n/index.js'; import { createTopBar } from '../components/topbar.js'; import { resetRegistrationFlow, state } from '../state.js'; +import { getRegistrationNamespaces } from '../services/registration-v2-api.js'; export const pageMeta = { id: 'registration-choice-view', get title() { return t('screens.registration_choice_view.text_001'); }, showAppChrome: false }; @@ -55,23 +56,31 @@ export function render({ navigate }) { box.append(top, description, list, action); return box; } - screen.append( - createTopBar({ title: t('screens.registration_choice_view.text_004'), back: { label: '←', onClick: () => navigate('registration-intro-view') } }), - title, intro, - card({ + const topBar = createTopBar({ title: t('screens.registration_choice_view.text_004'), back: { label: '←', onClick: () => navigate('registration-intro-view') } }); + const plans = document.createElement('div'); + plans.className = 'stack'; + const paidCard = card({ type: 'paid', icon: '◇', heading: t('screens.registration_choice_view.text_005'), price: t('screens.registration_choice_view.text_007'), lead: t('screens.registration_choice_view.text_008'), perks: [t('screens.registration_choice_view.text_009'), t('screens.registration_choice_view.text_010'), t('screens.registration_choice_view.text_011')], button: t('screens.registration_choice_view.text_012'), - }), - card({ + }); + plans.append(paidCard); + screen.append(topBar, title, intro, plans); + + // Бесплатная регистрация доступна только если текущий сервер сам объявил + // привязанный к нему type-2 namespace. При ошибке запроса безопасно оставляем + // только платный сценарий. + void getRegistrationNamespaces().then(({ namespaces }) => { + if (!screen.isConnected || !Array.isArray(namespaces) || !namespaces.some(n => Number(n.type) === 2)) return; + plans.append(card({ type: 'free', icon: '♧', heading: t('screens.registration_choice_view.text_006'), price: t('screens.registration_choice_view.text_013'), lead: t('screens.registration_choice_view.text_014'), perks: [t('screens.registration_choice_view.text_015'), t('screens.registration_choice_view.text_016'), t('screens.registration_choice_view.text_017')], button: t('screens.registration_choice_view.text_018'), - }), - ); + })); + }); return screen; }