Ограничить бесплатную регистрацию namespace сервера

This commit is contained in:
AidarKC
2026-11-21 01:09:37 +03:00
parent 792f368175
commit 80c70ebcdc
8 changed files with 101 additions and 20 deletions
@@ -33,7 +33,9 @@ public final class FreeRegistrationApiBootstrap {
FreeRegistrationPublisher publisher=null; FreeRegistrationPublisher publisher=null;
RegistrationEmailSender emailSender=null; RegistrationEmailSender emailSender=null;
AllowedEmailDomains allowedEmailDomains=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"); String domainsFile = cfg.getStringOrEmpty("freeRegistration.email.allowedDomainsFile");
if (domainsFile.isBlank()) domainsFile = "allowed-email-domains.txt"; if (domainsFile.isBlank()) domainsFile = "allowed-email-domains.txt";
// Относительный путь — от WorkingDirectory процесса Java. // Относительный путь — от WorkingDirectory процесса Java.
@@ -44,6 +46,8 @@ public final class FreeRegistrationApiBootstrap {
if(transport.publishMode()!=ArweaveBlocksConfig.PublishMode.TURBO) if(transport.publishMode()!=ArweaveBlocksConfig.PublishMode.TURBO)
throw new IllegalStateException("Free registration requires Turbo transport"); throw new IllegalStateException("Free registration requires Turbo transport");
newSigner=LocalRegistrarSigner.fromConfig(cfg); newSigner=LocalRegistrarSigner.fromConfig(cfg);
FreeRegistrationIssuer.validateConfiguredNamespace(dbSource(), newSigner, freeNamespace,
cfg.getStringOrEmpty("server.SHiNE.login"));
issuer=new FreeRegistrationIssuer(dbSource(),newSigner,allowEmailReuse); issuer=new FreeRegistrationIssuer(dbSource(),newSigner,allowEmailReuse);
publisher=new FreeRegistrationPublisher(issuer,new TurboDataItemUploader(transport), publisher=new FreeRegistrationPublisher(issuer,new TurboDataItemUploader(transport),
new VerifiedFreeRegistrationImporter(allowEmailReuse)); new VerifiedFreeRegistrationImporter(allowEmailReuse));
@@ -58,7 +62,8 @@ public final class FreeRegistrationApiBootstrap {
} }
FreeRegistrationWorkflow newWorkflow=new FreeRegistrationWorkflow(issuer,publisher,emailSender, FreeRegistrationWorkflow newWorkflow=new FreeRegistrationWorkflow(issuer,publisher,emailSender,
cfg.getBoolean("freeRegistration.email.allowTestCode",false), 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)); RegistrationApiBridge.install((op,req)->dispatch(newWorkflow,op,req));
signer=newSigner; workflow=newWorkflow; signer=newSigner; workflow=newWorkflow;
} }
@@ -24,6 +24,30 @@ public final class FreeRegistrationIssuer {
this.allowEmailReuse = allowEmailReuse; 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. */ /** Выдаётся только после успешной проверки challenge в FreeRegistrationWorkflow. */
synchronized byte[] issue(String fullLogin, byte[] root32, byte[] blockchain32, synchronized byte[] issue(String fullLogin, byte[] root32, byte[] blockchain32,
byte[] client32, String email) throws Exception { byte[] client32, String email) throws Exception {
@@ -51,10 +51,12 @@ public final class FreeRegistrationWorkflow {
private final boolean allowTestCode; private final boolean allowTestCode;
private final boolean allowEmailReuse; private final boolean allowEmailReuse;
private final AllowedEmailDomains allowedEmailDomains; private final AllowedEmailDomains allowedEmailDomains;
/** Единственный type-2 namespace, для которого этот сервер является регистратором. */
private final String freeRegistrationNamespace;
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher, public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse, 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) != (publisher == null)) throw new IllegalArgumentException("Signer/publisher mismatch");
if (issuer != null && emailSender == null) throw new IllegalArgumentException("Email sender is required"); if (issuer != null && emailSender == null) throw new IllegalArgumentException("Email sender is required");
if (emailSender != null && allowedEmailDomains == null) if (emailSender != null && allowedEmailDomains == null)
@@ -65,11 +67,24 @@ public final class FreeRegistrationWorkflow {
this.emailSender = emailSender; this.emailSender = emailSender;
this.allowTestCode = allowTestCode; this.allowTestCode = allowTestCode;
this.allowEmailReuse = allowEmailReuse; 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, public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse) { RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse) {
this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse, this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse,
emailSender == null ? null : loadDefaultEmailDomains()); emailSender == null ? null : loadDefaultEmailDomains(), "");
} }
private static AllowedEmailDomains loadDefaultEmailDomains() { private static AllowedEmailDomains loadDefaultEmailDomains() {
try { try {
@@ -94,11 +109,16 @@ public final class FreeRegistrationWorkflow {
try (Connection c = DbController.getInstance().getConnection(); try (Connection c = DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement(""" PreparedStatement ps = c.prepareStatement("""
SELECT namespace,namespace_type,min_localpart_len,registration_fee_lamports,currency_code,default_server_login SELECT namespace,namespace_type,min_localpart_len,registration_fee_lamports,currency_code,default_server_login
FROM shine_namespace_current ORDER BY namespace FROM shine_namespace_current
"""); ResultSet rs = ps.executeQuery()) { 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), 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))); rs.getString(4),rs.getInt(5),rs.getString(6)));
} }
}
return List.copyOf(result); return List.copyOf(result);
} }
public LoginCheck checkLogin(String login) throws Exception { public LoginCheck checkLogin(String login) throws Exception {
@@ -111,6 +131,8 @@ public final class FreeRegistrationWorkflow {
try (ResultSet rs=p.executeQuery()) { try (ResultSet rs=p.executeQuery()) {
if (!rs.next()) throw new IllegalArgumentException("Namespace is unavailable"); 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); 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 (currencyCode != 1) throw new IllegalStateException("Unsupported namespace currency");
if (login.indexOf('@') < minimum) throw new IllegalArgumentException("Login shorter than namespace minimum"); if (login.indexOf('@') < minimum) throw new IllegalArgumentException("Login shorter than namespace minimum");
} }
@@ -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"));
}
}
+2 -2
View File
@@ -1,2 +1,2 @@
client.version=1.20.64 client.version=1.20.65
server.version=1.16.31 server.version=1.16.32
@@ -4,7 +4,8 @@
## Конфигурация ## Конфигурация
- `freeRegistration.enabled=false` по умолчанию. Включается только на тестовом сервере после проверки соответствия namespace. - `freeRegistration.enabled=false` по умолчанию. Для включения обязательно одновременно задать `freeRegistration.namespace=<namespace>`: это единственный type-2 namespace, в котором данный сервер выдаёт бесплатные аккаунты. Если namespace не задан или `enabled=false`, сервер публикует только платные namespace и не показывает в UI вариант бесплатной регистрации.
- При включении сервер до начала работы сверяет, что указанный namespace имеет type 2, его `default_server_login` совпадает с `server.SHiNE.login`, а `registrar_pubkey` — с публичным ключом из seed. При несовпадении запуск прекращается; чужой namespace нельзя случайно обслужить.
- `freeRegistration.registrarSeedFile` — абсолютный путь к файлу вне Git, внутри одна Base64-строка **32-byte Ed25519 seed**. Пример имени `/var/lib/shine/secrets/registrar-seed.b64`; не создавать файл с тестовым ключом внутри репозитория. - `freeRegistration.registrarSeedFile` — абсолютный путь к файлу вне Git, внутри одна Base64-строка **32-byte Ed25519 seed**. Пример имени `/var/lib/shine/secrets/registrar-seed.b64`; не создавать файл с тестовым ключом внутри репозитория.
- `LocalRegistrarSigner.fromConfig(AppConfig)` проверяет enabled и наличие пути, не печатает секрет или bytes в лог. - `LocalRegistrarSigner.fromConfig(AppConfig)` проверяет enabled и наличие пути, не печатает секрет или bytes в лог.
- Публичный ключ signer должен совпадать с `shine_namespace_current.registrar_pubkey` (из on-chain namespace), иначе `FreeRegistrationIssuer.issue` отказывает. - Публичный ключ signer должен совпадать с `shine_namespace_current.registrar_pubkey` (из on-chain namespace), иначе `FreeRegistrationIssuer.issue` отказывает.
@@ -13,7 +13,7 @@
| `ConfirmFreeRegistration` | `challengeId,code` (случайный шестизначный код из письма) | `fullLogin,dataItemId,publicationStatus,chainConfirmed:false` | выпуск+Turbo ACK+локальный импорт | | `ConfirmFreeRegistration` | `challengeId,code` (случайный шестизначный код из письма) | `fullLogin,dataItemId,publicationStatus,chainConfirmed:false` | выпуск+Turbo ACK+локальный импорт |
| `GetRegistrationStatus` | `fullLogin` | `registrationStatus,dataItemId,publicationStatus`; для FREE_CERT дополнительно `innerSignature64B64,rootPublicKey,blockchainPublicKey,clientPublicKey,defaultServerLogin` | retry/upgrade | | `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 *не резервирует* их; перед подписью и перед импортом делается повторная проверка. **Ошибки:** `REGISTRATION_UNAVAILABLE` 503, `INVALID_REGISTRATION_INPUT` 400, `REGISTRATION_CONFLICT` 409, `RATE_LIMITED` 429, прочие 500 требуют анализа логов без раскрытия секретов. Проверка логина и email *не резервирует* их; перед подписью и перед импортом делается повторная проверка.
+17 -8
View File
@@ -1,6 +1,7 @@
import { t } from '../i18n/index.js'; import { t } from '../i18n/index.js';
import { createTopBar } from '../components/topbar.js'; import { createTopBar } from '../components/topbar.js';
import { resetRegistrationFlow, state } from '../state.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 }; 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); box.append(top, description, list, action);
return box; return box;
} }
screen.append( const topBar = createTopBar({ title: t('screens.registration_choice_view.text_004'), back: { label: '←', onClick: () => navigate('registration-intro-view') } });
createTopBar({ title: t('screens.registration_choice_view.text_004'), back: { label: '←', onClick: () => navigate('registration-intro-view') } }), const plans = document.createElement('div');
title, intro, plans.className = 'stack';
card({ const paidCard = card({
type: 'paid', icon: '◇', heading: t('screens.registration_choice_view.text_005'), type: 'paid', icon: '◇', heading: t('screens.registration_choice_view.text_005'),
price: t('screens.registration_choice_view.text_007'), price: t('screens.registration_choice_view.text_007'),
lead: t('screens.registration_choice_view.text_008'), 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')], 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'), 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'), type: 'free', icon: '♧', heading: t('screens.registration_choice_view.text_006'),
price: t('screens.registration_choice_view.text_013'), price: t('screens.registration_choice_view.text_013'),
lead: t('screens.registration_choice_view.text_014'), 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')], 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'), button: t('screens.registration_choice_view.text_018'),
}), }));
); });
return screen; return screen;
} }