Добавить email-подтверждение бесплатной регистрации

This commit is contained in:
AidarKC
2026-11-04 13:39:07 +03:00
parent e78402c860
commit c13734cbc9
21 changed files with 427 additions and 82 deletions
@@ -10,6 +10,7 @@ import org.slf4j.LoggerFactory;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler; import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
import server.sync.BlockchainResyncGuard; import server.sync.BlockchainResyncGuard;
import shine.db.DbController; import shine.db.DbController;
import utils.config.AppConfig;
import shine.db.dao.ArweaveBlockImportDAO; import shine.db.dao.ArweaveBlockImportDAO;
import shine.db.dao.BlockchainStateDAO; import shine.db.dao.BlockchainStateDAO;
import shine.db.dao.BlocksDAO; import shine.db.dao.BlocksDAO;
@@ -51,7 +52,8 @@ public final class ArweaveBlockSyncService {
.connectTimeout(Duration.ofSeconds(20)) .connectTimeout(Duration.ofSeconds(20))
.followRedirects(HttpClient.Redirect.NORMAL) .followRedirects(HttpClient.Redirect.NORMAL)
.build(); .build();
private final VerifiedFreeRegistrationImporter registrationImporter = new VerifiedFreeRegistrationImporter(); private final VerifiedFreeRegistrationImporter registrationImporter = new VerifiedFreeRegistrationImporter(
AppConfig.getInstance().getBoolean("freeRegistration.email.allowReuse", false));
private final ArweaveBlockImportDAO importDAO = ArweaveBlockImportDAO.getInstance(); private final ArweaveBlockImportDAO importDAO = ArweaveBlockImportDAO.getInstance();
private final BlocksDAO blocksDAO = BlocksDAO.getInstance(); private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
private final SolanaUserPdaCurrentDAO usersDAO = SolanaUserPdaCurrentDAO.getInstance(); private final SolanaUserPdaCurrentDAO usersDAO = SolanaUserPdaCurrentDAO.getInstance();
@@ -30,16 +30,29 @@ public final class FreeRegistrationApiBootstrap {
LocalRegistrarSigner newSigner=null; LocalRegistrarSigner newSigner=null;
FreeRegistrationIssuer issuer=null; FreeRegistrationIssuer issuer=null;
FreeRegistrationPublisher publisher=null; FreeRegistrationPublisher publisher=null;
RegistrationEmailSender emailSender=null;
if (cfg.getBoolean("freeRegistration.enabled",false)) { if (cfg.getBoolean("freeRegistration.enabled",false)) {
boolean allowEmailReuse=cfg.getBoolean("freeRegistration.email.allowReuse",false);
// Не выводить seed/path в журнал ни при успешном старте, ни при ошибке. // Не выводить seed/path в журнал ни при успешном старте, ни при ошибке.
ArweaveBlocksConfig transport=ArweaveBlocksConfig.load(); ArweaveBlocksConfig transport=ArweaveBlocksConfig.load();
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);
issuer=new FreeRegistrationIssuer(dbSource(),newSigner); issuer=new FreeRegistrationIssuer(dbSource(),newSigner,allowEmailReuse);
publisher=new FreeRegistrationPublisher(issuer,new TurboDataItemUploader(transport),new VerifiedFreeRegistrationImporter()); 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); FreeRegistrationWorkflow newWorkflow=new FreeRegistrationWorkflow(issuer,publisher,emailSender,
cfg.getBoolean("freeRegistration.email.allowTestCode",false),
cfg.getBoolean("freeRegistration.email.allowReuse",false));
RegistrationApiBridge.install((op,req)->dispatch(newWorkflow,op,req)); RegistrationApiBridge.install((op,req)->dispatch(newWorkflow,op,req));
signer=newSigner; workflow=newWorkflow; signer=newSigner; workflow=newWorkflow;
} }
@@ -12,17 +12,22 @@ import java.util.Arrays;
public final class FreeRegistrationIssuer { public final class FreeRegistrationIssuer {
private final DataSource db; private final DataSource db;
private final RegistrarSigner signer; private final RegistrarSigner signer;
private final boolean allowEmailReuse;
public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer) { public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer) {
this.db = java.util.Objects.requireNonNull(db); this(db, signer, false);
this.signer = java.util.Objects.requireNonNull(signer);
} }
/** Код 1111 учебный: не подтверждает владение email. */ public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer, boolean allowEmailReuse) {
public synchronized byte[] issue(String fullLogin, byte[] root32, byte[] blockchain32, this.db = java.util.Objects.requireNonNull(db);
byte[] client32, String email, String code) throws Exception { 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); FreeRegistrationCertificateV1.validateLogin(fullLogin);
if (!"1111".equals(code)) throw new IllegalArgumentException("Invalid demo email code");
String namespace = fullLogin.substring(fullLogin.indexOf('@') + 1); String namespace = fullLogin.substring(fullLogin.indexOf('@') + 1);
byte[] expectedEmail = FreeRegistrationCertificateV1.emailHash(email); byte[] expectedEmail = FreeRegistrationCertificateV1.emailHash(email);
try (Connection conn = db.getConnection()) { try (Connection conn = db.getConnection()) {
@@ -52,6 +57,7 @@ public final class FreeRegistrationIssuer {
if (rs.next()) throw new IllegalArgumentException("Login is already registered"); if (rs.next()) throw new IllegalArgumentException("Login is already registered");
} }
} }
if (!allowEmailReuse) {
try (PreparedStatement ps = conn.prepareStatement( try (PreparedStatement ps = conn.prepareStatement(
"SELECT 1 FROM free_registration_certificate WHERE email_sha256 = ?")) { "SELECT 1 FROM free_registration_certificate WHERE email_sha256 = ?")) {
ps.setBytes(1, expectedEmail); ps.setBytes(1, expectedEmail);
@@ -60,6 +66,7 @@ public final class FreeRegistrationIssuer {
} }
} }
} }
}
// Это только подписанный артефакт, не активная регистрация. Перед Turbo // Это только подписанный артефакт, не активная регистрация. Перед Turbo
// и локальным импортом обязательно повторять уникальность в транзакции БД. // и локальным импортом обязательно повторять уникальность в транзакции БД.
return FreeRegistrationCertificateV1.issue(fullLogin, root32, blockchain32, client32, email, signer); return FreeRegistrationCertificateV1.issue(fullLogin, root32, blockchain32, client32, email, signer);
@@ -27,9 +27,4 @@ public final class FreeRegistrationPublisher {
throw new IllegalStateException("Unexpected Turbo DataItem id"); throw new IllegalStateException("Unexpected Turbo DataItem id");
return importer.importSigned(signedBytes, VerifiedFreeRegistrationImporter.Provenance.TURBO_ACCEPTED); return importer.importSigned(signedBytes, VerifiedFreeRegistrationImporter.Provenance.TURBO_ACCEPTED);
} }
public VerifiedFreeRegistrationImporter.ImportResult register(String fullLogin, byte[] root, byte[] blockchain,
byte[] client, String email, String demoCode) throws Exception {
byte[] signed = issuer.issue(fullLogin, root, blockchain, client, email, demoCode);
return publishSigned(signed);
}
} }
@@ -7,7 +7,7 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.time.Duration; import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.HashMap;
import java.util.Base64; import java.util.Base64;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -26,18 +26,51 @@ public final class FreeRegistrationWorkflow {
String defaultServerLogin) {} String defaultServerLogin) {}
private record Draft(String login, byte[] root, byte[] blockchain, byte[] client, String email, private record Draft(String login, byte[] root, byte[] blockchain, byte[] client, String email,
long expiresAtMs, byte[] signedBytes) {} 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, Draft> pending = new ConcurrentHashMap<>();
private static final long TTL_MS = Duration.ofMinutes(15).toMillis(); // Не храним в БД почтовые адреса, пока регистрация не завершилась.
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 int MAX_PENDING = 512;
private static final SecureRandom RANDOM = new SecureRandom(); private static final SecureRandom RANDOM = new SecureRandom();
private final FreeRegistrationIssuer issuer; private final FreeRegistrationIssuer issuer;
private final FreeRegistrationPublisher publisher; private final FreeRegistrationPublisher publisher;
private final RegistrationEmailSender emailSender;
private final boolean allowTestCode;
private final boolean allowEmailReuse;
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher) { public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse) {
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");
this.issuer = issuer; this.issuer = issuer;
this.publisher = publisher; this.publisher = publisher;
this.emailSender = emailSender;
this.allowTestCode = allowTestCode;
this.allowEmailReuse = allowEmailReuse;
}
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 { public List<NamespaceInfo> listNamespaces() throws Exception {
List<NamespaceInfo> result = new ArrayList<>(); List<NamespaceInfo> result = new ArrayList<>();
@@ -72,6 +105,7 @@ public final class FreeRegistrationWorkflow {
} }
public EmailCheck checkEmail(String email) throws Exception { public EmailCheck checkEmail(String email) throws Exception {
byte[] hash=FreeRegistrationCertificateV1.emailHash(email); byte[] hash=FreeRegistrationCertificateV1.emailHash(email);
if (allowEmailReuse) return new EmailCheck(true);
try (Connection c=DbController.getInstance().getConnection(); try (Connection c=DbController.getInstance().getConnection();
PreparedStatement p=c.prepareStatement("SELECT 1 FROM free_registration_certificate WHERE email_sha256=?")) { PreparedStatement p=c.prepareStatement("SELECT 1 FROM free_registration_certificate WHERE email_sha256=?")) {
p.setBytes(1,hash); p.setBytes(1,hash);
@@ -83,36 +117,92 @@ public final class FreeRegistrationWorkflow {
return new Availability(checkLogin(login).loginAvailable(),checkEmail(email).emailAvailable()); return new Availability(checkLogin(login).loginAvailable(),checkEmail(email).emailAvailable());
} }
public Started start(String login, byte[] root, byte[] blockchain, byte[] client, String email) throws Exception { public Started start(String login, byte[] root, byte[] blockchain, byte[] client, String email) throws Exception {
if (issuer == null || publisher == null) throw new IllegalStateException("Free registration is disabled"); if (issuer == null || publisher == null || emailSender == null)
throw new IllegalStateException("Free registration is disabled");
FreeRegistrationCertificateV1.identityFields(login,root,blockchain,client); FreeRegistrationCertificateV1.identityFields(login,root,blockchain,client);
LoginCheck checked = checkLogin(login); LoginCheck checked = checkLogin(login);
if (checked.namespaceType()!=2 || !checked.loginAvailable()) throw new IllegalStateException("Login is unavailable"); if (checked.namespaceType()!=2 || !checked.loginAvailable())
throw new IllegalStateException("Login is unavailable");
if (!checkEmail(email).emailAvailable()) throw new IllegalStateException("Email is unavailable"); if (!checkEmail(email).emailAvailable()) throw new IllegalStateException("Email is unavailable");
String cleanEmail=FreeRegistrationCertificateV1.normalizeEmail(email); String cleanEmail=FreeRegistrationCertificateV1.normalizeEmail(email);
pending.entrySet().removeIf(e->e.getValue().expiresAtMs < System.currentTimeMillis()); String normalizedLogin=login.toLowerCase(java.util.Locale.ROOT);
if (pending.size() >= MAX_PENDING) throw new IllegalStateException("Too many pending registrations");
byte[] id=new byte[32]; RANDOM.nextBytes(id); byte[] id=new byte[32]; RANDOM.nextBytes(id);
String challenge=Base64.getUrlEncoder().withoutPadding().encodeToString(id); String challenge=Base64.getUrlEncoder().withoutPadding().encodeToString(id);
long expires=System.currentTimeMillis()+TTL_MS; String code=RegistrationEmailCode.generate();
pending.put(challenge,new Draft(login,root.clone(),blockchain.clone(),client.clone(),cleanEmail,expires,null)); 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); return new Started(challenge,expires);
} }
public synchronized Completed confirm(String challenge, String demoCode) throws Exception { 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 (publisher == null) throw new IllegalStateException("Free registration disabled");
if (challenge == null || challenge.isBlank())
throw new IllegalArgumentException("Registration challenge missing");
Draft d=pending.get(challenge); Draft d=pending.get(challenge);
if (d==null || d.expiresAtMs < System.currentTimeMillis()) { if (d==null || d.expiresAtMs < System.currentTimeMillis()) {
pending.remove(challenge); throw new IllegalArgumentException("Registration challenge missing or expired"); pending.remove(challenge); throw new IllegalArgumentException("Registration challenge missing or expired");
} }
if (!"1111".equals(demoCode)) throw new IllegalArgumentException("Invalid demo code"); if (!d.delivered) throw new IllegalStateException("Verification email is not delivered yet");
// При ошибке Turbo сохраняем единожды подписанные bytes и повторно отправляем ТОТ ЖЕ DataItem. 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; byte[] signed=d.signedBytes;
if(signed==null) { if(signed==null) {
signed=issuer.issue(d.login,d.root,d.blockchain,d.client,d.email,demoCode); signed=issuer.issue(d.login,d.root,d.blockchain,d.client,d.email);
pending.put(challenge,new Draft(d.login,d.root,d.blockchain,d.client,d.email,d.expiresAtMs,signed)); d=d.update(d.attempts,true,true,signed);
pending.put(challenge,d);
} }
VerifiedFreeRegistrationImporter.ImportResult result=publisher.publishSigned(signed); VerifiedFreeRegistrationImporter.ImportResult result=publisher.publishSigned(signed);
// Сохраняем draft до TTL, чтобы потерянный WS-ответ не вынуждал выпускать другой сертификат. // Повтор использует тот же подписанный DataItem, без смены ключей и адреса email.
pending.put(challenge,new Draft(d.login,d.root,d.blockchain,d.client,d.email,d.expiresAtMs,signed));
return new Completed(result.login(),result.dataItemId(),"TURBO_ACCEPTED",result.alreadyImported()); return new Completed(result.login(),result.dataItemId(),"TURBO_ACCEPTED",result.alreadyImported());
} }
public State getStatus(String login) throws Exception { public State getStatus(String login) throws Exception {
@@ -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() + ")");
}
}
@@ -14,6 +14,15 @@ import java.util.Base64;
public final class VerifiedFreeRegistrationImporter { public final class VerifiedFreeRegistrationImporter {
public enum Provenance { TURBO_ACCEPTED, ARWEAVE_CONFIRMED } public enum Provenance { TURBO_ACCEPTED, ARWEAVE_CONFIRMED }
public record ImportResult(String login, String dataItemId, boolean alreadyImported, Provenance provenance) {} 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: не расходовать кредиты на чужую/битую запись. */ /** Предварительная проверка ДО Turbo: не расходовать кредиты на чужую/битую запись. */
public FreeRegistrationCertificateV1.Verified validateForUpload(byte[] raw) throws Exception { public FreeRegistrationCertificateV1.Verified validateForUpload(byte[] raw) throws Exception {
@@ -32,6 +41,7 @@ public final class VerifiedFreeRegistrationImporter {
throw new IllegalArgumentException("Login is already registered"); throw new IllegalArgumentException("Login is already registered");
} }
} }
if (!allowEmailReuse) {
try (PreparedStatement ps = c.prepareStatement( try (PreparedStatement ps = c.prepareStatement(
"SELECT data_item_id FROM free_registration_certificate WHERE email_sha256=?")) { "SELECT data_item_id FROM free_registration_certificate WHERE email_sha256=?")) {
ps.setBytes(1, cert.emailSha256()); ps.setBytes(1, cert.emailSha256());
@@ -40,6 +50,7 @@ public final class VerifiedFreeRegistrationImporter {
throw new IllegalArgumentException("Email hash belongs to another account"); throw new IllegalArgumentException("Email hash belongs to another account");
} }
} }
}
return cert; return cert;
} }
} }
@@ -27,21 +27,13 @@ public final class FreeRegistrationWorkflowLocalCheck {
var issuer = new FreeRegistrationIssuer(noDb, signer); var issuer = new FreeRegistrationIssuer(noDb, signer);
var importer = new VerifiedFreeRegistrationImporter(); var importer = new VerifiedFreeRegistrationImporter();
var workflow = new FreeRegistrationWorkflow(issuer, var workflow = new FreeRegistrationWorkflow(issuer,
new FreeRegistrationPublisher(issuer, new TurboDataItemUploader(), importer)); new FreeRegistrationPublisher(issuer, new TurboDataItemUploader(ArweaveBlocksConfig.load()), importer),
byte[] k1 = new byte[32], k2 = new byte[32], k3 = new byte[32]; (email, code) -> { throw new AssertionError("No real email in an offline check"); });
k1[0] = 1; k2[0] = 2; k3[0] = 3; try { workflow.confirm("unknown", "123456"); throw new AssertionError("Missing challenge accepted"); }
var start = workflow.start("bob@free", k1, k2, k3, "hello@example.org");
if (start.challengeId().isBlank() || start.expiresAtMs() <= System.currentTimeMillis())
throw new AssertionError("Cannot start a bounded challenge");
try { workflow.confirm(start.challengeId(), "wrong"); throw new AssertionError("Bad demo code accepted"); }
catch (IllegalArgumentException expected) { }
try { workflow.confirm("unknown", "1111"); throw new AssertionError("Missing challenge accepted"); }
catch (IllegalArgumentException expected) { }
try { workflow.start("BOB@free", k1, k2, k3, "hello@example.org"); throw new AssertionError("Invalid login accepted"); }
catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) { }
try { importer.importSigned(new byte[]{1,2,3}, VerifiedFreeRegistrationImporter.Provenance.TURBO_ACCEPTED); try { importer.importSigned(new byte[]{1,2,3}, VerifiedFreeRegistrationImporter.Provenance.TURBO_ACCEPTED);
throw new AssertionError("Invalid bytes accepted"); } throw new AssertionError("Invalid bytes accepted"); }
catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) { }
System.out.println("PASS: workflow nonce/code checks + reject invalid signed bytes"); System.out.println("PASS: workflow missing challenge + reject invalid signed bytes");
} }
} }
@@ -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");
}
}
@@ -29,6 +29,7 @@ public final class DatabaseInitializer {
public static final int SCHEMA_VERSION_36 = 36; public static final int SCHEMA_VERSION_36 = 36;
public static final int SCHEMA_VERSION_37 = 37; public static final int SCHEMA_VERSION_37 = 37;
public static final int SCHEMA_VERSION_38 = 38; 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_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.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_V32_RESOURCE = "postgres/migration_v32.sql";
@@ -38,6 +39,7 @@ public final class DatabaseInitializer {
public static final String POSTGRES_MIGRATION_V36_RESOURCE = "postgres/migration_v36.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_V37_RESOURCE = "postgres/migration_v37.sql";
public static final String POSTGRES_MIGRATION_V38_RESOURCE = "postgres/migration_v38.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() {} private DatabaseInitializer() {}
@@ -161,9 +163,13 @@ public final class DatabaseInitializer {
runSqlScript(conn, POSTGRES_MIGRATION_V38_RESOURCE); runSqlScript(conn, POSTGRES_MIGRATION_V38_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn); currentVersion = readCurrentSchemaVersion(conn);
} }
if (currentVersion != SCHEMA_VERSION_38) { if (currentVersion == SCHEMA_VERSION_38) {
runSqlScript(conn, POSTGRES_MIGRATION_V39_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion != SCHEMA_VERSION_39) {
throw new SQLException( throw new SQLException(
"Unsupported SHiNE DB v2 schema version: expected 38, found " + currentVersion); "Unsupported SHiNE DB v2 schema version: expected 39, found " + currentVersion);
} }
normalizeBlockchainStateKeysToBase64(conn); normalizeBlockchainStateKeysToBase64(conn);
} }
@@ -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;
+2 -2
View File
@@ -1,2 +1,2 @@
client.version=1.20.11 client.version=1.20.12
server.version=1.16.10 server.version=1.16.11
+1 -1
View File
@@ -176,6 +176,6 @@
## Регистрация V2: полные логины и независимые проверки ## Регистрация V2: полные логины и независимые проверки
Публичные WS-операции нового протокола перечислены в `docs/registration-v2/WS_REGISTRATION_V2_PROPOSED_NOT_ENABLED.md`. Публичные WS-операции нового протокола перечислены в `docs/registration-v2/WS_REGISTRATION_V2_PROPOSED_NOT_ENABLED.md`.
Сначала `GetNamespaces` → `CheckRegistrationLogin` с полным `login@namespace`; затем **только для бесплатной регистрации** отдельное `CheckRegistrationEmail`. После проверки запускается `StartFreeRegistration`, затем `ConfirmFreeRegistration` с тестовым кодом `1111`. Состояние читается через `GetRegistrationStatus`. Сначала `GetNamespaces` → `CheckRegistrationLogin` с полным `login@namespace`; затем **только для бесплатной регистрации** отдельное `CheckRegistrationEmail`. После проверки запускается `StartFreeRegistration`, затем `ConfirmFreeRegistration` с шестизначным одноразовым кодом из письма (1 час, 5 попыток). Состояние читается через `GetRegistrationStatus`.
Все бесплатные сертификаты подписаны ANS-104 и внутренней подписью Ed25519; успешный Turbo ACK не означает подтверждённую высоту Arweave. Клиент никогда не отправляет пароль или приватные ключи на сервер. Все бесплатные сертификаты подписаны ANS-104 и внутренней подписью Ed25519; успешный Turbo ACK не означает подтверждённую высоту Arweave. Клиент никогда не отправляет пароль или приватные ключи на сервер.
@@ -8,7 +8,7 @@
- `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` отказывает.
- В режиме демонстрации код — `1111`. Владение почтой не подтверждается. Регистрация окончательно не активируется до Turbo ACK и проверенного импорта на этапе 8. - При включённой бесплатной регистрации обязательно задать `RESEND_API_KEY` в окружении процесса (или `freeRegistration.email.apiKey` в защищённом внешнем конфиге). Настройки: `freeRegistration.email.allowTestCode=false` — временный обход `777777`, `freeRegistration.email.allowReuse=false` — запрет повторного использования одного email, `freeRegistration.email.from=SHiNE <noreply@shineup.me>` — отправитель. `allowReuse=true` допустим только в закрытом тестовом окружении: при этом один email может завершить несколько регистраций. Тестовый обход включать исключительно в закрытом тестовом окружении. 6-значный код отправляется на email через Resend и проверяется до выдачи сертификата. Подробности: [RESEND_EMAIL_VERIFICATION.md](RESEND_EMAIL_VERIFICATION.md). Регистрация окончательно не активируется до Turbo ACK и проверенного импорта.
**Безопасность:** на реальном сервере ограничить права файла регистратором/пользователем Java-процесса (0600), не сохранять секрет в stdout, crash reports, Git, backup без шифрования. В будущем заменить реализацию `RegistrarSigner` на аппаратный модуль. **Безопасность:** на реальном сервере ограничить права файла регистратором/пользователем Java-процесса (0600), не сохранять секрет в stdout, crash reports, Git, backup без шифрования. В будущем заменить реализацию `RegistrarSigner` на аппаратный модуль.
@@ -0,0 +1,62 @@
# Подтверждение email при бесплатной регистрации SHiNE
Реализация: `SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/`.
## Подключение Resend
1. В Resend подтвердить `shineup.me` (DNS DKIM + отправляющие CNAME), статус **Verified**.
2. Получить в Resend API key с правом `Sending access`.
3. Указать API-ключ как `RESEND_API_KEY` в окружении Java-процесса (предпочтительно) или через `freeRegistration.email.apiKey` во **внешнем**, недоступном из Git `application.properties`. Никогда не коммитить реальный ключ, не печатать в журнале и не отдавать клиенту.
4. Настройка `freeRegistration.email.from`. По умолчанию отправитель: `SHiNE <noreply@shineup.me>`.
При необходимости изменить внешним параметром `freeRegistration.email.from`, но адрес обязан относиться к подтверждённому домену.
5. Настройка `freeRegistration.email.allowTestCode=false` по умолчанию. Только для тестирования `true` разрешает код `777777` на этапе подтверждения любой активной заявки. Это полностью обходит подтверждение владения email и НЕ ДОЛЖНО использоваться на публичном/production-сервере.
6. На сервере, где `freeRegistration.enabled=true`, без API-ключа Resend старт завершится ошибкой (fail-closed), даже если тестовый код включён. При создании заявки письмо всегда отправляется.
7. После локальных тестов перезапустить только нужный тестовый сервер по инструкциям deploy (production отдельно согласовывать).
## Процесс
- `CheckRegistrationEmail` проверяет известный занятый email, без отправки.
- `StartFreeRegistration` создаёт случайный 6-значный код и challenge, отправляет письмо через HTTP API Resend;
только после ответа 2xx возвращает `challengeId` и `expiresAtMs`.
- `ConfirmFreeRegistration` принимает код для конкретного challenge. После верного кода
подписывает сертификат и публикует прежним Turbo/Arweave путём. Формат WS/API и сертификата не меняется.
- Код действует 1 час, хранится в памяти как SHA-256(challengeId + `:` + code), максимум 5 ошибок на challenge.
Повторная отправка ограничена одной попыткой в минуту на email и логин. Общий лимит — 60 отправок в час
на процесс. Повторная публикация сертификата после сетевой ошибки допускается до конца TTL.
- Данные challenge в памяти: после перезапуска сервера ещё не подтверждённый код перестаёт действовать;
пользователь начинает новую заявку. Для нескольких Java-инстансов понадобится общее хранилище TTL (Redis/Postgres),
иначе challenge, созданный на одном узле, не подтвердится на другом.
- При HTTP-ошибке Resend заявка удаляется, код не считается отправленным.
## Проверка
1. Для тестового окружения задать `RESEND_API_KEY` в systemd EnvironmentFile (файл с ограниченными правами),
не добавляя ключ в репозиторий. При изменении секрета перезапустить сервис.
2. Зарегистрировать новый `login@free` и доступный адрес email.
3. Проверить письмо, неверный код, истечение срока, пять ошибок, повторную отправку через минуту,
успешное подтверждение, Turbo ACK и отсутствие email/кода в системных журналах.
4. Проверить ошибки/квоту Resend в панели провайдера и корректное поведение UI.
Сервис Resend может принять запрос на отправку, но не гарантирует доставку во входящие пользователя;
статусы доставки анализируются в панели Resend, особенно для bounce/spam.
## Три настройки сервера
```properties
# Реальный секрет предпочтительно задавать через RESEND_API_KEY или внешнюю конфигурацию.
freeRegistration.email.apiKey=
freeRegistration.email.allowTestCode=false
freeRegistration.email.allowReuse=false
freeRegistration.email.from=SHiNE <noreply@shineup.me>
```
Параметры читаются из `AppConfig`: системное свойство → переменная окружения
(`FREE_REGISTRATION_EMAIL_API_KEY`, `FREE_REGISTRATION_EMAIL_ALLOW_TEST_CODE`,
`FREE_REGISTRATION_EMAIL_FROM`) → внешний `application.properties` → встроенный файл.
`RESEND_API_KEY` имеет приоритет над `freeRegistration.email.apiKey`.
Ограничение: чит-код действует **только для уже созданного challenge**, когда
Resend успешно принял запрос на отправку. Он не создаёт пользователя без
`StartFreeRegistration` и не работает после истечения 1 часа или перезапуска Java.
Для применения изменений настроек нужен перезапуск Java-процесса.
+11 -5
View File
@@ -28,7 +28,10 @@ export function render({navigate}) {
const nsLabel=document.createElement('label');nsLabel.className='stack';nsLabel.textContent='Пространство имён'; nsLabel.append(namespace); const nsLabel=document.createElement('label');nsLabel.className='stack';nsLabel.textContent='Пространство имён'; nsLabel.append(namespace);
const methodLabel=document.createElement('label');methodLabel.className='stack'; methodLabel.textContent='Способ регистрации';methodLabel.append(method); const methodLabel=document.createElement('label');methodLabel.className='stack'; methodLabel.textContent='Способ регистрации';methodLabel.append(method);
const pwLabel=document.createElement('label');pwLabel.className='stack';pwLabel.textContent='Пароль (ключи остаются только у вас)';pwLabel.append(password); const pwLabel=document.createElement('label');pwLabel.className='stack';pwLabel.textContent='Пароль (ключи остаются только у вас)';pwLabel.append(password);
form.append(methodLabel,nsLabel,local,full,caseNotice,pwLabel,status,action); const passwordHelp=document.createElement('p');passwordHelp.className='meta-muted';
passwordHelp.hidden=true;
passwordHelp.textContent='После проверки логина мы сгенерируем ключи из вашего пароля на этом устройстве. Это занимает несколько секунд и делает массовый подбор паролей значительно сложнее.';
form.append(methodLabel,nsLabel,local,full,caseNotice,pwLabel,passwordHelp,status,action);
let namespaces=[]; let disposed=false; let inputRevision=0; let submission=0; let namespaces=[]; let disposed=false; let inputRevision=0; let submission=0;
const feeToSol = fee => (Number(fee || '0')/1e9).toFixed(6); const feeToSol = fee => (Number(fee || '0')/1e9).toFixed(6);
function selected() { return namespaces.find(n=>n.name===namespace.value); } function selected() { return namespaces.find(n=>n.name===namespace.value); }
@@ -52,6 +55,9 @@ export function render({navigate}) {
method.addEventListener('change',()=>{inputRevision++;display();}); method.addEventListener('change',()=>{inputRevision++;display();});
namespace.addEventListener('change',()=>{inputRevision++;showFull();}); namespace.addEventListener('change',()=>{inputRevision++;showFull();});
local.addEventListener('input',()=>{inputRevision++;showFull();}); local.addEventListener('input',()=>{inputRevision++;showFull();});
function showPasswordHelp() { passwordHelp.hidden=!password.value; }
password.addEventListener('input',()=>{inputRevision++;showPasswordHelp();});
showPasswordHelp();
void getRegistrationNamespaces().then(data=>{ void getRegistrationNamespaces().then(data=>{
if(disposed)return;namespaces=Array.isArray(data.namespaces)?data.namespaces:[];display(); if(disposed)return;namespaces=Array.isArray(data.namespaces)?data.namespaces:[];display();
if(!namespaces.length)status.textContent='Solana namespace ещё не синхронизированы с сервером'; if(!namespaces.length)status.textContent='Solana namespace ещё не синхронизированы с сервером';
@@ -79,14 +85,14 @@ export function render({navigate}) {
draft.namespaceFeeLamports=String(check.registrationFeeLamports||ns.registrationFeeLamports); draft.namespaceFeeLamports=String(check.registrationFeeLamports||ns.registrationFeeLamports);
draft.namespaceServerLogin=ns.defaultServerLogin||''; draft.namespaceServerLogin=ns.defaultServerLogin||'';
if(changed)draft.preGeneratedKeyBundle=null; if(changed)draft.preGeneratedKeyBundle=null;
status.textContent='Генерируем ключи из вашего пароля… Это нужно, чтобы сделать массовый подбор паролей значительно сложнее.';
const bundle=draft.preGeneratedKeyBundle || await authService.derivePasswordKeyBundle(login,password.value);
if(disposed || thisRun!==submission)return;
draft.preGeneratedKeyBundle=bundle;
if(draft.flowType==='free') { if(draft.flowType==='free') {
navigate('registration-email-view'); navigate('registration-email-view');
return; return;
} }
status.textContent='Создаём ключи локально (Argon2id)…';
const bundle=draft.preGeneratedKeyBundle || await authService.derivePasswordKeyBundle(login,password.value);
if(disposed || thisRun!==submission)return;
draft.preGeneratedKeyBundle=bundle;
navigate('registration-payment-view'); navigate('registration-payment-view');
}catch(error){if(!disposed && thisRun===submission)status.textContent=error.message || 'Не удалось продолжить регистрацию.';} }catch(error){if(!disposed && thisRun===submission)status.textContent=error.message || 'Не удалось продолжить регистрацию.';}
finally {if(thisRun===submission)action.disabled=false;} finally {if(thisRun===submission)action.disabled=false;}
+24 -14
View File
@@ -1,5 +1,5 @@
import { createTopBar } from '../components/topbar.js'; import { createTopBar } from '../components/topbar.js';
import { authService, state } from '../state.js'; import { state } from '../state.js';
import { checkRegistrationEmail, startFreeRegistration, confirmFreeRegistration } from '../services/registration-v2-api.js'; import { checkRegistrationEmail, startFreeRegistration, confirmFreeRegistration } from '../services/registration-v2-api.js';
import { completeRegistrationLogin } from './registration-payment-view.js'; import { completeRegistrationLogin } from './registration-payment-view.js';
@@ -14,15 +14,16 @@ export function render({navigate}) {
info.textContent='Email используется только для регистрации. В Arweave публикуется SHA-256 от email; его можно подобрать перебором.'; info.textContent='Email используется только для регистрации. В Arweave публикуется SHA-256 от email; его можно подобрать перебором.';
const status=document.createElement('p');status.className='status-line';status.setAttribute('aria-live','polite'); const status=document.createElement('p');status.className='status-line';status.setAttribute('aria-live','polite');
const next=document.createElement('button');next.className='primary-btn';next.textContent='Проверить email'; const next=document.createElement('button');next.className='primary-btn';next.textContent='Проверить email';
const code=document.createElement('input');code.className='input';code.inputMode='numeric';code.placeholder='Код 1111'; const code=document.createElement('input');code.className='input';code.inputMode='numeric';code.placeholder='6-значный код из письма';code.maxLength=6;code.autocomplete='one-time-code';
const codeLabel=document.createElement('p');codeLabel.className='meta-muted'; const codeLabel=document.createElement('p');codeLabel.className='meta-muted';
codeLabel.textContent='Тест: код 1111. Письмо не отправляется, владение email не подтверждается.'; codeLabel.textContent='Мы отправили код на вашу почту. Введите его в течение 1 часа (не более 5 попыток).';
const confirm=document.createElement('button');confirm.className='primary-btn';confirm.textContent='Подтвердить и зарегистрироваться'; const confirm=document.createElement('button');confirm.className='primary-btn';confirm.textContent='Подтвердить и зарегистрироваться';
const retry=document.createElement('button');retry.className='secondary-btn';retry.textContent='Проверить статус и повторить'; const retry=document.createElement('button');retry.className='secondary-btn';retry.textContent='Повторить публикацию при ошибке';
code.hidden=true;codeLabel.hidden=true;confirm.hidden=true;retry.hidden=true; const resend=document.createElement('button');resend.className='secondary-btn';resend.textContent='Отправить новый код';
form.append(info,input,status,next,codeLabel,code,confirm,retry); code.hidden=true;codeLabel.hidden=true;confirm.hidden=true;retry.hidden=true;resend.hidden=true;
form.append(info,input,status,next,codeLabel,code,confirm,retry,resend);
let disposed=false; let disposed=false;
function showConfirm(){ input.disabled=true;next.hidden=true;code.hidden=false;codeLabel.hidden=false;confirm.hidden=false;retry.hidden=false; } function showConfirm(){ input.disabled=true;next.hidden=true;code.hidden=false;codeLabel.hidden=false;confirm.hidden=false;retry.hidden=false;resend.hidden=false; }
next.addEventListener('click',async()=>{ next.addEventListener('click',async()=>{
if(draft.flowType!=='free'){status.textContent='Выберите бесплатную регистрацию на предыдущем экране';return;} if(draft.flowType!=='free'){status.textContent='Выберите бесплатную регистрацию на предыдущем экране';return;}
next.disabled=true;status.textContent='Проверяем email…'; next.disabled=true;status.textContent='Проверяем email…';
@@ -32,21 +33,30 @@ export function render({navigate}) {
if(!available.emailAvailable) throw new Error('Этот email уже использован для бесплатной регистрации'); if(!available.emailAvailable) throw new Error('Этот email уже использован для бесплатной регистрации');
draft.email=address; draft.email=address;
if(!draft.preGeneratedKeyBundle){ if(!draft.preGeneratedKeyBundle){
if(!draft.login || !draft.password) throw new Error('Логин или пароль не сохранены. Вернитесь на предыдущий экран.'); throw new Error('Ключи не созданы. Вернитесь на предыдущий экран и продолжите регистрацию.');
status.textContent='Создаём ключи локально (Argon2id)…';
draft.preGeneratedKeyBundle=await authService.derivePasswordKeyBundle(draft.login,draft.password);
} }
status.textContent='Создаём временную заявку…'; status.textContent='Отправляем код подтверждения на почту…';
const started=await startFreeRegistration({fullLogin:draft.login,keyBundle:draft.preGeneratedKeyBundle,email:address}); const started=await startFreeRegistration({fullLogin:draft.login,keyBundle:draft.preGeneratedKeyBundle,email:address});
if(disposed)return; if(disposed)return;
draft.challengeId=started.challengeId;draft.challengeExpiresAtMs=started.expiresAtMs; draft.challengeId=started.challengeId;draft.challengeExpiresAtMs=started.expiresAtMs;
status.textContent='Заявка создана. Введите тестовый код 1111.';showConfirm(); status.textContent='Письмо отправлено. Проверьте входящие и папку «Спам».';showConfirm();
}catch(error){if(!disposed)status.textContent=error.message;next.disabled=false;} }catch(error){if(!disposed)status.textContent=error.message;next.disabled=false;}
}); });
resend.addEventListener('click', async()=>{
resend.disabled=true;status.textContent='Отправляем новый код…';
try {
const started=await startFreeRegistration({fullLogin:draft.login,keyBundle:draft.preGeneratedKeyBundle,email:draft.email});
if(disposed)return;
draft.challengeId=started.challengeId;draft.challengeExpiresAtMs=started.expiresAtMs;
code.value='';status.textContent='Новый код отправлен. Старый код больше не используйте.';
}catch(error){if(!disposed)status.textContent=error.message || 'Не удалось отправить код. Подождите минуту и повторите.';}
finally{resend.disabled=false;}
});
async function submit(){ async function submit(){
if(!draft.challengeId){status.textContent='Нет активной заявки';return;} if(!draft.challengeId){status.textContent='Нет активной заявки';return;}
if(!/^[0-9]{6}$/.test(code.value.trim())){status.textContent='Введите шесть цифр из письма.';return;}
confirm.disabled=true;retry.disabled=true; confirm.disabled=true;retry.disabled=true;
status.textContent='Подписываем сертификат и отправляем его через Turbo…'; status.textContent='Проверяем код и публикуем сертификат через Turbo…';
try{ try{
const res=await confirmFreeRegistration(draft.challengeId,code.value.trim()); const res=await confirmFreeRegistration(draft.challengeId,code.value.trim());
if(disposed)return; if(disposed)return;
@@ -58,7 +68,7 @@ export function render({navigate}) {
} }
confirm.addEventListener('click',submit);retry.addEventListener('click',submit); confirm.addEventListener('click',submit);retry.addEventListener('click',submit);
if(draft.challengeId && draft.challengeExpiresAtMs>Date.now()){ if(draft.challengeId && draft.challengeExpiresAtMs>Date.now()){
status.textContent='Есть незавершённая заявка. Можно повторить подтверждение без новых ключей.';showConfirm(); status.textContent='Заявка активна. Введите шестизначный код из письма.';showConfirm();
} }
screen.append(createTopBar({title:'Подтверждение email',back:{label:'←',onClick:()=>navigate('register-view')}}),form); screen.append(createTopBar({title:'Подтверждение email',back:{label:'←',onClick:()=>navigate('register-view')}}),form);
return screen; return screen;
@@ -28,9 +28,10 @@ test('free-регистрация передаёт ровно три публи
assert.match(request[0],/clientPublicKeyB64/); assert.match(request[0],/clientPublicKeyB64/);
assert.doesNotMatch(request[0],/password|masterSecret|privatePkcs8|seed32/); assert.doesNotMatch(request[0],/password|masterSecret|privatePkcs8|seed32/);
}); });
test('free экран показывает учебный код и ждёт Turbo, платный upgrade требует сравнить ключи',()=>{ test('free экран вводит код из письма и ждёт Turbo, платный upgrade проверяет ключи',()=>{
const email=read('shine-UI/js/pages/registration-email-view.js'); const email=read('shine-UI/js/pages/registration-email-view.js');
assert.match(email,/код 1111/);assert.match(email,/confirmFreeRegistration/); assert.match(email,/6-значный код из письма/);assert.match(email,/confirmFreeRegistration/);
assert.doesNotMatch(email,/код 1111/);
assert.match(email,/completeRegistrationLogin/); assert.match(email,/completeRegistrationLogin/);
const upgrade=read('shine-UI/js/pages/registration-upgrade-view.js'); const upgrade=read('shine-UI/js/pages/registration-upgrade-view.js');
assert.match(upgrade,/keys\.rootPair/);assert.match(upgrade,/bytesToBase58/); assert.match(upgrade,/keys\.rootPair/);assert.match(upgrade,/bytesToBase58/);