SHA256
Добавить email-подтверждение бесплатной регистрации
This commit is contained in:
+3
-1
@@ -10,6 +10,7 @@ import org.slf4j.LoggerFactory;
|
||||
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
|
||||
import server.sync.BlockchainResyncGuard;
|
||||
import shine.db.DbController;
|
||||
import utils.config.AppConfig;
|
||||
import shine.db.dao.ArweaveBlockImportDAO;
|
||||
import shine.db.dao.BlockchainStateDAO;
|
||||
import shine.db.dao.BlocksDAO;
|
||||
@@ -51,7 +52,8 @@ public final class ArweaveBlockSyncService {
|
||||
.connectTimeout(Duration.ofSeconds(20))
|
||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||
.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 BlocksDAO blocksDAO = BlocksDAO.getInstance();
|
||||
private final SolanaUserPdaCurrentDAO usersDAO = SolanaUserPdaCurrentDAO.getInstance();
|
||||
|
||||
+16
-3
@@ -30,16 +30,29 @@ public final class FreeRegistrationApiBootstrap {
|
||||
LocalRegistrarSigner newSigner=null;
|
||||
FreeRegistrationIssuer issuer=null;
|
||||
FreeRegistrationPublisher publisher=null;
|
||||
RegistrationEmailSender emailSender=null;
|
||||
if (cfg.getBoolean("freeRegistration.enabled",false)) {
|
||||
boolean allowEmailReuse=cfg.getBoolean("freeRegistration.email.allowReuse",false);
|
||||
// Не выводить seed/path в журнал ни при успешном старте, ни при ошибке.
|
||||
ArweaveBlocksConfig transport=ArweaveBlocksConfig.load();
|
||||
if(transport.publishMode()!=ArweaveBlocksConfig.PublishMode.TURBO)
|
||||
throw new IllegalStateException("Free registration requires Turbo transport");
|
||||
newSigner=LocalRegistrarSigner.fromConfig(cfg);
|
||||
issuer=new FreeRegistrationIssuer(dbSource(),newSigner);
|
||||
publisher=new FreeRegistrationPublisher(issuer,new TurboDataItemUploader(transport),new VerifiedFreeRegistrationImporter());
|
||||
issuer=new FreeRegistrationIssuer(dbSource(),newSigner,allowEmailReuse);
|
||||
publisher=new FreeRegistrationPublisher(issuer,new TurboDataItemUploader(transport),
|
||||
new VerifiedFreeRegistrationImporter(allowEmailReuse));
|
||||
// Секрет берём ТОЛЬКО из окружения, не из файлов репозитория.
|
||||
String resendKey=System.getenv("RESEND_API_KEY");
|
||||
if(resendKey==null || resendKey.isBlank())
|
||||
resendKey=cfg.getStringOrEmpty("freeRegistration.email.apiKey");
|
||||
emailSender=new ResendRegistrationEmailSender(resendKey,
|
||||
cfg.getStringOrEmpty("freeRegistration.email.from").isBlank()
|
||||
? "SHiNE <noreply@shineup.me>"
|
||||
: cfg.getStringOrEmpty("freeRegistration.email.from"));
|
||||
}
|
||||
FreeRegistrationWorkflow newWorkflow=new FreeRegistrationWorkflow(issuer,publisher);
|
||||
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));
|
||||
signer=newSigner; workflow=newWorkflow;
|
||||
}
|
||||
|
||||
+18
-11
@@ -12,17 +12,22 @@ import java.util.Arrays;
|
||||
public final class FreeRegistrationIssuer {
|
||||
private final DataSource db;
|
||||
private final RegistrarSigner signer;
|
||||
private final boolean allowEmailReuse;
|
||||
|
||||
public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer) {
|
||||
this.db = java.util.Objects.requireNonNull(db);
|
||||
this.signer = java.util.Objects.requireNonNull(signer);
|
||||
this(db, signer, false);
|
||||
}
|
||||
|
||||
/** Код 1111 учебный: не подтверждает владение email. */
|
||||
public synchronized byte[] issue(String fullLogin, byte[] root32, byte[] blockchain32,
|
||||
byte[] client32, String email, String code) throws Exception {
|
||||
public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer, boolean allowEmailReuse) {
|
||||
this.db = java.util.Objects.requireNonNull(db);
|
||||
this.signer = java.util.Objects.requireNonNull(signer);
|
||||
this.allowEmailReuse = allowEmailReuse;
|
||||
}
|
||||
|
||||
/** Выдаётся только после успешной проверки challenge в FreeRegistrationWorkflow. */
|
||||
synchronized byte[] issue(String fullLogin, byte[] root32, byte[] blockchain32,
|
||||
byte[] client32, String email) throws Exception {
|
||||
FreeRegistrationCertificateV1.validateLogin(fullLogin);
|
||||
if (!"1111".equals(code)) throw new IllegalArgumentException("Invalid demo email code");
|
||||
String namespace = fullLogin.substring(fullLogin.indexOf('@') + 1);
|
||||
byte[] expectedEmail = FreeRegistrationCertificateV1.emailHash(email);
|
||||
try (Connection conn = db.getConnection()) {
|
||||
@@ -52,11 +57,13 @@ public final class FreeRegistrationIssuer {
|
||||
if (rs.next()) throw new IllegalArgumentException("Login is already registered");
|
||||
}
|
||||
}
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT 1 FROM free_registration_certificate WHERE email_sha256 = ?")) {
|
||||
ps.setBytes(1, expectedEmail);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (rs.next()) throw new IllegalArgumentException("Email hash already registered");
|
||||
if (!allowEmailReuse) {
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT 1 FROM free_registration_certificate WHERE email_sha256 = ?")) {
|
||||
ps.setBytes(1, expectedEmail);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (rs.next()) throw new IllegalArgumentException("Email hash already registered");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-5
@@ -27,9 +27,4 @@ public final class FreeRegistrationPublisher {
|
||||
throw new IllegalStateException("Unexpected Turbo DataItem id");
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
+107
-17
@@ -7,7 +7,7 @@ import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -26,18 +26,51 @@ public final class FreeRegistrationWorkflow {
|
||||
String defaultServerLogin) {}
|
||||
|
||||
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 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 SecureRandom RANDOM = new SecureRandom();
|
||||
private final FreeRegistrationIssuer issuer;
|
||||
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 && emailSender == null) throw new IllegalArgumentException("Email sender is required");
|
||||
this.issuer = issuer;
|
||||
this.publisher = publisher;
|
||||
this.emailSender = emailSender;
|
||||
this.allowTestCode = allowTestCode;
|
||||
this.allowEmailReuse = allowEmailReuse;
|
||||
}
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
|
||||
RegistrationEmailSender emailSender, boolean allowTestCode) {
|
||||
this(issuer, publisher, emailSender, allowTestCode, false);
|
||||
}
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
|
||||
RegistrationEmailSender emailSender) {
|
||||
this(issuer, publisher, emailSender, false);
|
||||
}
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher) {
|
||||
this(issuer, publisher, null);
|
||||
}
|
||||
public List<NamespaceInfo> listNamespaces() throws Exception {
|
||||
List<NamespaceInfo> result = new ArrayList<>();
|
||||
@@ -72,6 +105,7 @@ public final class FreeRegistrationWorkflow {
|
||||
}
|
||||
public EmailCheck checkEmail(String email) throws Exception {
|
||||
byte[] hash=FreeRegistrationCertificateV1.emailHash(email);
|
||||
if (allowEmailReuse) return new EmailCheck(true);
|
||||
try (Connection c=DbController.getInstance().getConnection();
|
||||
PreparedStatement p=c.prepareStatement("SELECT 1 FROM free_registration_certificate WHERE email_sha256=?")) {
|
||||
p.setBytes(1,hash);
|
||||
@@ -83,36 +117,92 @@ public final class FreeRegistrationWorkflow {
|
||||
return new Availability(checkLogin(login).loginAvailable(),checkEmail(email).emailAvailable());
|
||||
}
|
||||
public Started start(String login, byte[] root, byte[] blockchain, byte[] client, String email) throws Exception {
|
||||
if (issuer == null || publisher == null) 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);
|
||||
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");
|
||||
String cleanEmail=FreeRegistrationCertificateV1.normalizeEmail(email);
|
||||
pending.entrySet().removeIf(e->e.getValue().expiresAtMs < System.currentTimeMillis());
|
||||
if (pending.size() >= MAX_PENDING) throw new IllegalStateException("Too many pending registrations");
|
||||
String normalizedLogin=login.toLowerCase(java.util.Locale.ROOT);
|
||||
byte[] id=new byte[32]; RANDOM.nextBytes(id);
|
||||
String challenge=Base64.getUrlEncoder().withoutPadding().encodeToString(id);
|
||||
long expires=System.currentTimeMillis()+TTL_MS;
|
||||
pending.put(challenge,new Draft(login,root.clone(),blockchain.clone(),client.clone(),cleanEmail,expires,null));
|
||||
String code=RegistrationEmailCode.generate();
|
||||
long now=System.currentTimeMillis();
|
||||
long expires=now+TTL_MS;
|
||||
Draft draft=new Draft(login,root.clone(),blockchain.clone(),client.clone(),cleanEmail,
|
||||
expires,RegistrationEmailCode.hash(challenge,code),0,false,false,null);
|
||||
synchronized (this) {
|
||||
pending.entrySet().removeIf(e->e.getValue().expiresAtMs < now);
|
||||
recentEmails.entrySet().removeIf(e->e.getValue() < now-TTL_MS);
|
||||
recentLogins.entrySet().removeIf(e->e.getValue() < now-TTL_MS);
|
||||
while(!globalSendTimes.isEmpty() && globalSendTimes.peekFirst() < now-GLOBAL_WINDOW_MS)
|
||||
globalSendTimes.removeFirst();
|
||||
if (pending.size() >= MAX_PENDING) throw new IllegalStateException("Too many pending registrations");
|
||||
if (now-recentEmails.getOrDefault(cleanEmail,0L) < EMAIL_COOLDOWN_MS ||
|
||||
now-recentLogins.getOrDefault(normalizedLogin,0L) < EMAIL_COOLDOWN_MS)
|
||||
throw new IllegalStateException("Please wait before requesting another code");
|
||||
if (globalSendTimes.size() >= MAX_EMAILS_PER_HOUR)
|
||||
throw new IllegalStateException("Email verification temporarily limited");
|
||||
recentEmails.put(cleanEmail,now);
|
||||
recentLogins.put(normalizedLogin,now);
|
||||
globalSendTimes.addLast(now);
|
||||
pending.put(challenge,draft);
|
||||
}
|
||||
try {
|
||||
// Не блокируем monitor workflow на время HTTP-запроса к Resend.
|
||||
emailSender.sendVerificationCode(cleanEmail,code);
|
||||
} catch (Exception e) {
|
||||
synchronized (this) {
|
||||
pending.remove(challenge);
|
||||
recentEmails.remove(cleanEmail,now);
|
||||
recentLogins.remove(normalizedLogin,now);
|
||||
globalSendTimes.removeFirstOccurrence(now);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
synchronized (this) {
|
||||
// Новый успешно отправленный код заменяет старые заявки на тот же login/email.
|
||||
pending.entrySet().removeIf(e -> !e.getKey().equals(challenge) &&
|
||||
(e.getValue().email.equals(cleanEmail) ||
|
||||
e.getValue().login.equalsIgnoreCase(login)));
|
||||
pending.computeIfPresent(challenge,(key,d)->d.update(d.attempts,true,d.verified,d.signedBytes));
|
||||
}
|
||||
return new Started(challenge,expires);
|
||||
}
|
||||
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 (challenge == null || challenge.isBlank())
|
||||
throw new IllegalArgumentException("Registration challenge missing");
|
||||
Draft d=pending.get(challenge);
|
||||
if (d==null || d.expiresAtMs < System.currentTimeMillis()) {
|
||||
pending.remove(challenge); throw new IllegalArgumentException("Registration challenge missing or expired");
|
||||
}
|
||||
if (!"1111".equals(demoCode)) throw new IllegalArgumentException("Invalid demo code");
|
||||
// При ошибке Turbo сохраняем единожды подписанные bytes и повторно отправляем ТОТ ЖЕ DataItem.
|
||||
if (!d.delivered) throw new IllegalStateException("Verification email is not delivered yet");
|
||||
if (!d.verified) {
|
||||
if (!isValidVerificationCode(d.codeHash, challenge, code)) {
|
||||
if (d.attempts+1 >= MAX_ATTEMPTS) pending.remove(challenge);
|
||||
else pending.put(challenge,d.update(d.attempts+1,true,false,d.signedBytes));
|
||||
throw new IllegalArgumentException("Invalid email code");
|
||||
}
|
||||
// Если Turbo не ответит, подтверждённая заявка может быть повторена до TTL.
|
||||
d=d.update(d.attempts,true,true,d.signedBytes);
|
||||
pending.put(challenge,d);
|
||||
}
|
||||
byte[] signed=d.signedBytes;
|
||||
if(signed==null) {
|
||||
signed=issuer.issue(d.login,d.root,d.blockchain,d.client,d.email,demoCode);
|
||||
pending.put(challenge,new Draft(d.login,d.root,d.blockchain,d.client,d.email,d.expiresAtMs,signed));
|
||||
signed=issuer.issue(d.login,d.root,d.blockchain,d.client,d.email);
|
||||
d=d.update(d.attempts,true,true,signed);
|
||||
pending.put(challenge,d);
|
||||
}
|
||||
VerifiedFreeRegistrationImporter.ImportResult result=publisher.publishSigned(signed);
|
||||
// Сохраняем draft до TTL, чтобы потерянный WS-ответ не вынуждал выпускать другой сертификат.
|
||||
pending.put(challenge,new Draft(d.login,d.root,d.blockchain,d.client,d.email,d.expiresAtMs,signed));
|
||||
// Повтор использует тот же подписанный DataItem, без смены ключей и адреса email.
|
||||
return new Completed(result.login(),result.dataItemId(),"TURBO_ACCEPTED",result.alreadyImported());
|
||||
}
|
||||
public State getStatus(String login) throws Exception {
|
||||
|
||||
+31
@@ -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));
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package server.archive.registration;
|
||||
|
||||
/** Отправка кода. Детали внешнего почтового провайдера не влияют на протокол регистрации. */
|
||||
@FunctionalInterface
|
||||
public interface RegistrationEmailSender {
|
||||
void sendVerificationCode(String recipient, String code) throws Exception;
|
||||
}
|
||||
+63
@@ -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() + ")");
|
||||
}
|
||||
}
|
||||
+17
-6
@@ -14,6 +14,15 @@ import java.util.Base64;
|
||||
public final class VerifiedFreeRegistrationImporter {
|
||||
public enum Provenance { TURBO_ACCEPTED, ARWEAVE_CONFIRMED }
|
||||
public record ImportResult(String login, String dataItemId, boolean alreadyImported, Provenance provenance) {}
|
||||
private final boolean allowEmailReuse;
|
||||
|
||||
public VerifiedFreeRegistrationImporter() {
|
||||
this(false);
|
||||
}
|
||||
|
||||
public VerifiedFreeRegistrationImporter(boolean allowEmailReuse) {
|
||||
this.allowEmailReuse = allowEmailReuse;
|
||||
}
|
||||
|
||||
/** Предварительная проверка ДО Turbo: не расходовать кредиты на чужую/битую запись. */
|
||||
public FreeRegistrationCertificateV1.Verified validateForUpload(byte[] raw) throws Exception {
|
||||
@@ -32,12 +41,14 @@ public final class VerifiedFreeRegistrationImporter {
|
||||
throw new IllegalArgumentException("Login is already registered");
|
||||
}
|
||||
}
|
||||
try (PreparedStatement ps = c.prepareStatement(
|
||||
"SELECT data_item_id FROM free_registration_certificate WHERE email_sha256=?")) {
|
||||
ps.setBytes(1, cert.emailSha256());
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (rs.next() && !cert.idBase64Url().equals(rs.getString(1)))
|
||||
throw new IllegalArgumentException("Email hash belongs to another account");
|
||||
if (!allowEmailReuse) {
|
||||
try (PreparedStatement ps = c.prepareStatement(
|
||||
"SELECT data_item_id FROM free_registration_certificate WHERE email_sha256=?")) {
|
||||
ps.setBytes(1, cert.emailSha256());
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (rs.next() && !cert.idBase64Url().equals(rs.getString(1)))
|
||||
throw new IllegalArgumentException("Email hash belongs to another account");
|
||||
}
|
||||
}
|
||||
}
|
||||
return cert;
|
||||
|
||||
+4
-12
@@ -27,21 +27,13 @@ public final class FreeRegistrationWorkflowLocalCheck {
|
||||
var issuer = new FreeRegistrationIssuer(noDb, signer);
|
||||
var importer = new VerifiedFreeRegistrationImporter();
|
||||
var workflow = new FreeRegistrationWorkflow(issuer,
|
||||
new FreeRegistrationPublisher(issuer, new TurboDataItemUploader(), importer));
|
||||
byte[] k1 = new byte[32], k2 = new byte[32], k3 = new byte[32];
|
||||
k1[0] = 1; k2[0] = 2; k3[0] = 3;
|
||||
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"); }
|
||||
new FreeRegistrationPublisher(issuer, new TurboDataItemUploader(ArweaveBlocksConfig.load()), importer),
|
||||
(email, code) -> { throw new AssertionError("No real email in an offline check"); });
|
||||
try { workflow.confirm("unknown", "123456"); throw new AssertionError("Missing challenge accepted"); }
|
||||
catch (IllegalArgumentException expected) { }
|
||||
try { importer.importSigned(new byte[]{1,2,3}, VerifiedFreeRegistrationImporter.Provenance.TURBO_ACCEPTED);
|
||||
throw new AssertionError("Invalid bytes accepted"); }
|
||||
catch (IllegalArgumentException expected) { }
|
||||
System.out.println("PASS: workflow nonce/code checks + reject invalid signed bytes");
|
||||
System.out.println("PASS: workflow missing challenge + reject invalid signed bytes");
|
||||
}
|
||||
}
|
||||
|
||||
+17
@@ -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");
|
||||
}
|
||||
}
|
||||
+21
@@ -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_37 = 37;
|
||||
public static final int SCHEMA_VERSION_38 = 38;
|
||||
public static final int SCHEMA_VERSION_39 = 39;
|
||||
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
|
||||
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
|
||||
public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql";
|
||||
@@ -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_V37_RESOURCE = "postgres/migration_v37.sql";
|
||||
public static final String POSTGRES_MIGRATION_V38_RESOURCE = "postgres/migration_v38.sql";
|
||||
public static final String POSTGRES_MIGRATION_V39_RESOURCE = "postgres/migration_v39.sql";
|
||||
|
||||
private DatabaseInitializer() {}
|
||||
|
||||
@@ -161,9 +163,13 @@ public final class DatabaseInitializer {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V38_RESOURCE);
|
||||
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(
|
||||
"Unsupported SHiNE DB v2 schema version: expected 38, found " + currentVersion);
|
||||
"Unsupported SHiNE DB v2 schema version: expected 39, found " + currentVersion);
|
||||
}
|
||||
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
@@ -1,2 +1,2 @@
|
||||
client.version=1.20.11
|
||||
server.version=1.16.10
|
||||
client.version=1.20.12
|
||||
server.version=1.16.11
|
||||
|
||||
@@ -176,6 +176,6 @@
|
||||
## Регистрация V2: полные логины и независимые проверки
|
||||
|
||||
Публичные 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. Клиент никогда не отправляет пароль или приватные ключи на сервер.
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
- `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` отказывает.
|
||||
- В режиме демонстрации код — `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` на аппаратный модуль.
|
||||
|
||||
|
||||
@@ -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-процесса.
|
||||
@@ -28,7 +28,10 @@ export function render({navigate}) {
|
||||
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 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;
|
||||
const feeToSol = fee => (Number(fee || '0')/1e9).toFixed(6);
|
||||
function selected() { return namespaces.find(n=>n.name===namespace.value); }
|
||||
@@ -52,6 +55,9 @@ export function render({navigate}) {
|
||||
method.addEventListener('change',()=>{inputRevision++;display();});
|
||||
namespace.addEventListener('change',()=>{inputRevision++;showFull();});
|
||||
local.addEventListener('input',()=>{inputRevision++;showFull();});
|
||||
function showPasswordHelp() { passwordHelp.hidden=!password.value; }
|
||||
password.addEventListener('input',()=>{inputRevision++;showPasswordHelp();});
|
||||
showPasswordHelp();
|
||||
void getRegistrationNamespaces().then(data=>{
|
||||
if(disposed)return;namespaces=Array.isArray(data.namespaces)?data.namespaces:[];display();
|
||||
if(!namespaces.length)status.textContent='Solana namespace ещё не синхронизированы с сервером';
|
||||
@@ -79,14 +85,14 @@ export function render({navigate}) {
|
||||
draft.namespaceFeeLamports=String(check.registrationFeeLamports||ns.registrationFeeLamports);
|
||||
draft.namespaceServerLogin=ns.defaultServerLogin||'';
|
||||
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') {
|
||||
navigate('registration-email-view');
|
||||
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');
|
||||
}catch(error){if(!disposed && thisRun===submission)status.textContent=error.message || 'Не удалось продолжить регистрацию.';}
|
||||
finally {if(thisRun===submission)action.disabled=false;}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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 { completeRegistrationLogin } from './registration-payment-view.js';
|
||||
|
||||
@@ -14,15 +14,16 @@ export function render({navigate}) {
|
||||
info.textContent='Email используется только для регистрации. В Arweave публикуется SHA-256 от email; его можно подобрать перебором.';
|
||||
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 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';
|
||||
codeLabel.textContent='Тест: код 1111. Письмо не отправляется, владение email не подтверждается.';
|
||||
codeLabel.textContent='Мы отправили код на вашу почту. Введите его в течение 1 часа (не более 5 попыток).';
|
||||
const confirm=document.createElement('button');confirm.className='primary-btn';confirm.textContent='Подтвердить и зарегистрироваться';
|
||||
const retry=document.createElement('button');retry.className='secondary-btn';retry.textContent='Проверить статус и повторить';
|
||||
code.hidden=true;codeLabel.hidden=true;confirm.hidden=true;retry.hidden=true;
|
||||
form.append(info,input,status,next,codeLabel,code,confirm,retry);
|
||||
const retry=document.createElement('button');retry.className='secondary-btn';retry.textContent='Повторить публикацию при ошибке';
|
||||
const resend=document.createElement('button');resend.className='secondary-btn';resend.textContent='Отправить новый код';
|
||||
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;
|
||||
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()=>{
|
||||
if(draft.flowType!=='free'){status.textContent='Выберите бесплатную регистрацию на предыдущем экране';return;}
|
||||
next.disabled=true;status.textContent='Проверяем email…';
|
||||
@@ -32,21 +33,30 @@ export function render({navigate}) {
|
||||
if(!available.emailAvailable) throw new Error('Этот email уже использован для бесплатной регистрации');
|
||||
draft.email=address;
|
||||
if(!draft.preGeneratedKeyBundle){
|
||||
if(!draft.login || !draft.password) throw new Error('Логин или пароль не сохранены. Вернитесь на предыдущий экран.');
|
||||
status.textContent='Создаём ключи локально (Argon2id)…';
|
||||
draft.preGeneratedKeyBundle=await authService.derivePasswordKeyBundle(draft.login,draft.password);
|
||||
throw new Error('Ключи не созданы. Вернитесь на предыдущий экран и продолжите регистрацию.');
|
||||
}
|
||||
status.textContent='Создаём временную заявку…';
|
||||
status.textContent='Отправляем код подтверждения на почту…';
|
||||
const started=await startFreeRegistration({fullLogin:draft.login,keyBundle:draft.preGeneratedKeyBundle,email:address});
|
||||
if(disposed)return;
|
||||
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;}
|
||||
});
|
||||
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(){
|
||||
if(!draft.challengeId){status.textContent='Нет активной заявки';return;}
|
||||
if(!/^[0-9]{6}$/.test(code.value.trim())){status.textContent='Введите шесть цифр из письма.';return;}
|
||||
confirm.disabled=true;retry.disabled=true;
|
||||
status.textContent='Подписываем сертификат и отправляем его через Turbo…';
|
||||
status.textContent='Проверяем код и публикуем сертификат через Turbo…';
|
||||
try{
|
||||
const res=await confirmFreeRegistration(draft.challengeId,code.value.trim());
|
||||
if(disposed)return;
|
||||
@@ -58,7 +68,7 @@ export function render({navigate}) {
|
||||
}
|
||||
confirm.addEventListener('click',submit);retry.addEventListener('click',submit);
|
||||
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);
|
||||
return screen;
|
||||
|
||||
@@ -28,9 +28,10 @@ test('free-регистрация передаёт ровно три публи
|
||||
assert.match(request[0],/clientPublicKeyB64/);
|
||||
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');
|
||||
assert.match(email,/код 1111/);assert.match(email,/confirmFreeRegistration/);
|
||||
assert.match(email,/6-значный код из письма/);assert.match(email,/confirmFreeRegistration/);
|
||||
assert.doesNotMatch(email,/код 1111/);
|
||||
assert.match(email,/completeRegistrationLogin/);
|
||||
const upgrade=read('shine-UI/js/pages/registration-upgrade-view.js');
|
||||
assert.match(upgrade,/keys\.rootPair/);assert.match(upgrade,/bytesToBase58/);
|
||||
|
||||
Reference in New Issue
Block a user