SHA256
Ограничить домены email бесплатной регистрации
This commit is contained in:
+50
@@ -0,0 +1,50 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashSet;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** Список разрешённых доменов для бесплатной регистрации; читается при старте Java-сервера. */
|
||||
public final class AllowedEmailDomains {
|
||||
// Обычные ASCII-домены (в том числе punycode), без масок, пробелов и URL.
|
||||
private static final Pattern DOMAIN = Pattern.compile(
|
||||
"(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+");
|
||||
private final Set<String> domains;
|
||||
|
||||
private AllowedEmailDomains(Set<String> domains) {
|
||||
this.domains = Set.copyOf(domains);
|
||||
}
|
||||
|
||||
/** Ошибки чтения, пустой или неверный список — ошибка запуска регистрации (fail-closed). */
|
||||
public static AllowedEmailDomains load(Path file) throws IOException {
|
||||
if (!Files.isRegularFile(file))
|
||||
throw new IOException("Email domain allowlist is missing: " + file.toAbsolutePath());
|
||||
Set<String> result = new HashSet<>();
|
||||
int lineNumber = 0;
|
||||
for (String line : Files.readAllLines(file, StandardCharsets.UTF_8)) {
|
||||
lineNumber++;
|
||||
String domain = line.strip().toLowerCase(Locale.ROOT);
|
||||
if (domain.isEmpty() || domain.startsWith("#")) continue;
|
||||
if (!DOMAIN.matcher(domain).matches())
|
||||
throw new IOException("Invalid allowed email domain at " + file + ":" + lineNumber);
|
||||
result.add(domain);
|
||||
}
|
||||
if (result.isEmpty())
|
||||
throw new IOException("Email domain allowlist is empty: " + file.toAbsolutePath());
|
||||
return new AllowedEmailDomains(result);
|
||||
}
|
||||
|
||||
/** Сопоставление строго по части после одного символа @, без wildcard и суффиксов. */
|
||||
public boolean permits(String email) {
|
||||
if (email == null) return false;
|
||||
String value = email.strip().toLowerCase(Locale.ROOT);
|
||||
int at = value.indexOf('@');
|
||||
if (at <= 0 || at != value.lastIndexOf('@')) return false;
|
||||
return domains.contains(value.substring(at + 1));
|
||||
}
|
||||
}
|
||||
+12
-2
@@ -9,6 +9,7 @@ import utils.config.AppConfig;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.SQLFeatureNotSupportedException;
|
||||
@@ -31,7 +32,12 @@ public final class FreeRegistrationApiBootstrap {
|
||||
FreeRegistrationIssuer issuer=null;
|
||||
FreeRegistrationPublisher publisher=null;
|
||||
RegistrationEmailSender emailSender=null;
|
||||
AllowedEmailDomains allowedEmailDomains=null;
|
||||
if (cfg.getBoolean("freeRegistration.enabled",false)) {
|
||||
String domainsFile = cfg.getStringOrEmpty("freeRegistration.email.allowedDomainsFile");
|
||||
if (domainsFile.isBlank()) domainsFile = "allowed-email-domains.txt";
|
||||
// Относительный путь — от WorkingDirectory процесса Java.
|
||||
allowedEmailDomains = AllowedEmailDomains.load(Path.of(domainsFile));
|
||||
boolean allowEmailReuse=cfg.getBoolean("freeRegistration.email.allowReuse",false);
|
||||
// Не выводить seed/path в журнал ни при успешном старте, ни при ошибке.
|
||||
ArweaveBlocksConfig transport=ArweaveBlocksConfig.load();
|
||||
@@ -52,7 +58,7 @@ public final class FreeRegistrationApiBootstrap {
|
||||
}
|
||||
FreeRegistrationWorkflow newWorkflow=new FreeRegistrationWorkflow(issuer,publisher,emailSender,
|
||||
cfg.getBoolean("freeRegistration.email.allowTestCode",false),
|
||||
cfg.getBoolean("freeRegistration.email.allowReuse",false));
|
||||
cfg.getBoolean("freeRegistration.email.allowReuse",false), allowedEmailDomains);
|
||||
RegistrationApiBridge.install((op,req)->dispatch(newWorkflow,op,req));
|
||||
signer=newSigner; workflow=newWorkflow;
|
||||
}
|
||||
@@ -78,7 +84,11 @@ public final class FreeRegistrationApiBootstrap {
|
||||
out.put("minLocalLength",info.minLocalLength());
|
||||
out.put("registrationFeeLamports",info.registrationFeeLamports());
|
||||
}
|
||||
case "CheckRegistrationEmail" -> out.put("emailAvailable",w.checkEmail(req.getEmail()).emailAvailable());
|
||||
case "CheckRegistrationEmail" -> {
|
||||
var check=w.checkEmail(req.getEmail());
|
||||
out.put("emailAvailable",check.emailAvailable());
|
||||
out.put("emailStatus",check.emailStatus());
|
||||
}
|
||||
case "StartFreeRegistration" -> {
|
||||
var state=w.start(req.getFullLogin(),decodeKey(req.getRootPublicKeyB64()),
|
||||
decodeKey(req.getBlockchainPublicKeyB64()),decodeKey(req.getClientPublicKeyB64()),req.getEmail());
|
||||
|
||||
+27
-5
@@ -18,7 +18,7 @@ public final class FreeRegistrationWorkflow {
|
||||
public record NamespaceInfo(String namespace, int type, int minLoginLength, String priceLamports, String serverLogin) {}
|
||||
public record Availability(boolean nameFree, boolean emailHashFree) {}
|
||||
public record LoginCheck(boolean loginAvailable, int namespaceType, int minLocalLength, String registrationFeeLamports) {}
|
||||
public record EmailCheck(boolean emailAvailable) {}
|
||||
public record EmailCheck(boolean emailAvailable, String emailStatus) {}
|
||||
public record Started(String challengeId, long expiresAtMs) {}
|
||||
public record Completed(String fullLogin, String dataItemId, String state, boolean alreadyImported) {}
|
||||
public record State(String status, String dataItemId, String publicationStatus, String innerSignature64B64,
|
||||
@@ -50,17 +50,34 @@ public final class FreeRegistrationWorkflow {
|
||||
private final RegistrationEmailSender emailSender;
|
||||
private final boolean allowTestCode;
|
||||
private final boolean allowEmailReuse;
|
||||
private final AllowedEmailDomains allowedEmailDomains;
|
||||
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
|
||||
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse) {
|
||||
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse,
|
||||
AllowedEmailDomains allowedEmailDomains) {
|
||||
if ((issuer == null) != (publisher == null)) throw new IllegalArgumentException("Signer/publisher mismatch");
|
||||
if (issuer != null && emailSender == null) throw new IllegalArgumentException("Email sender is required");
|
||||
if (emailSender != null && allowedEmailDomains == null)
|
||||
throw new IllegalArgumentException("Allowed email domain list is required");
|
||||
this.allowedEmailDomains = allowedEmailDomains;
|
||||
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, boolean allowEmailReuse) {
|
||||
this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse,
|
||||
emailSender == null ? null : loadDefaultEmailDomains());
|
||||
}
|
||||
private static AllowedEmailDomains loadDefaultEmailDomains() {
|
||||
try {
|
||||
return AllowedEmailDomains.load(java.nio.file.Path.of("allowed-email-domains.txt"));
|
||||
} catch (java.io.IOException e) {
|
||||
throw new IllegalStateException("Cannot load allowed email domains", e);
|
||||
}
|
||||
}
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
|
||||
RegistrationEmailSender emailSender, boolean allowTestCode) {
|
||||
this(issuer, publisher, emailSender, allowTestCode, false);
|
||||
@@ -104,12 +121,17 @@ public final class FreeRegistrationWorkflow {
|
||||
}
|
||||
}
|
||||
public EmailCheck checkEmail(String email) throws Exception {
|
||||
byte[] hash=FreeRegistrationCertificateV1.emailHash(email);
|
||||
if (allowEmailReuse) return new EmailCheck(true);
|
||||
// До запроса к БД: отсутствие разрешения не должно раскрывать занятость email.
|
||||
String normalizedEmail = FreeRegistrationCertificateV1.normalizeEmail(email);
|
||||
if (allowedEmailDomains == null || !allowedEmailDomains.permits(normalizedEmail))
|
||||
return new EmailCheck(false, "DOMAIN_NOT_ALLOWED");
|
||||
byte[] hash=FreeRegistrationCertificateV1.emailHash(normalizedEmail);
|
||||
if (allowEmailReuse) return new EmailCheck(true, "AVAILABLE");
|
||||
try (Connection c=DbController.getInstance().getConnection();
|
||||
PreparedStatement p=c.prepareStatement("SELECT 1 FROM free_registration_certificate WHERE email_sha256=?")) {
|
||||
p.setBytes(1,hash);
|
||||
try(ResultSet rs=p.executeQuery()) { return new EmailCheck(!rs.next()); }
|
||||
try(ResultSet rs=p.executeQuery()) { return rs.next() ? new EmailCheck(false, "ALREADY_REGISTERED")
|
||||
: new EmailCheck(true, "AVAILABLE"); }
|
||||
}
|
||||
}
|
||||
/** Устаревший внутренний helper: внешний API использует две отдельные операции. */
|
||||
|
||||
+3
-1
@@ -28,7 +28,9 @@ public final class FreeRegistrationWorkflowLocalCheck {
|
||||
var importer = new VerifiedFreeRegistrationImporter();
|
||||
var workflow = new FreeRegistrationWorkflow(issuer,
|
||||
new FreeRegistrationPublisher(issuer, new TurboDataItemUploader(ArweaveBlocksConfig.load()), importer),
|
||||
(email, code) -> { throw new AssertionError("No real email in an offline check"); });
|
||||
(email, code) -> { throw new AssertionError("No real email in an offline check"); },
|
||||
false, false, AllowedEmailDomains.load(Files.isRegularFile(Path.of("allowed-email-domains.txt"))
|
||||
? Path.of("allowed-email-domains.txt") : Path.of("../allowed-email-domains.txt")));
|
||||
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);
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/** Самостоятельный офлайн-тест: javac AllowedEmailDomains.java AllowedEmailDomainsCheck.java + java. */
|
||||
public final class AllowedEmailDomainsCheck {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Path dir = Files.createTempDirectory("shine-email-domains-test-");
|
||||
try {
|
||||
Path file = dir.resolve("allowed-email-domains.txt");
|
||||
Files.writeString(file, "# Test\n Gmail.com \nproton.me\n\n", StandardCharsets.UTF_8);
|
||||
AllowedEmailDomains allowed = AllowedEmailDomains.load(file);
|
||||
expect(allowed.permits("User@GMAIL.COM"), "case insensitive match");
|
||||
expect(allowed.permits(" user@proton.me "), "trimmed match");
|
||||
expect(!allowed.permits("user@gmail.com.evil.org"), "suffix bypass");
|
||||
expect(!allowed.permits("user@sub.gmail.com"), "subdomain bypass");
|
||||
expect(!allowed.permits("user@other.com"), "unknown domain");
|
||||
expect(!allowed.permits("user@@gmail.com"), "invalid multiple @");
|
||||
expect(!allowed.permits("@gmail.com"), "missing local part");
|
||||
expect(!allowed.permits(null), "null address");
|
||||
Files.writeString(file, "# no domains\n \n", StandardCharsets.UTF_8);
|
||||
expectLoadFailure(file, "empty file");
|
||||
Files.writeString(file, "*.gmail.com\n", StandardCharsets.UTF_8);
|
||||
expectLoadFailure(file, "wildcard not allowed");
|
||||
Files.writeString(file, "gmail.com\ninvalid_domain\n", StandardCharsets.UTF_8);
|
||||
expectLoadFailure(file, "invalid line not ignored");
|
||||
Files.delete(file);
|
||||
expectLoadFailure(file, "missing file");
|
||||
System.out.println("PASS: allowed email domains, strict matching, fail-closed");
|
||||
} finally {
|
||||
try (var files = Files.list(dir)) { files.forEach(path -> {try {Files.deleteIfExists(path);}catch(Exception ex){throw new RuntimeException(ex);}}); }
|
||||
Files.deleteIfExists(dir);
|
||||
}
|
||||
}
|
||||
|
||||
private static void expect(boolean condition, String scenario) {
|
||||
if (!condition) throw new AssertionError(scenario);
|
||||
}
|
||||
private static void expectLoadFailure(Path file, String scenario) throws Exception {
|
||||
try {
|
||||
AllowedEmailDomains.load(file);
|
||||
throw new AssertionError("Invalid allowlist accepted: " + scenario);
|
||||
} catch (java.io.IOException expected) { }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user