Добавить 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.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();
@@ -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;
}
@@ -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");
}
}
}
}
@@ -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);
}
}
@@ -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 {
@@ -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 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;
@@ -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");
}
}
@@ -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_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;