Ограничить домены email бесплатной регистрации

This commit is contained in:
AidarKC
2026-11-05 03:27:52 +03:00
parent e84ab41fe6
commit bd52a23bec
15 changed files with 424 additions and 20 deletions
+10
View File
@@ -116,3 +116,13 @@ SHiNE-bundle-*.zip
# Рабочие бэкапы/превью-ассеты UI — не для репозитория
*.bak.png
shine-UI/assets/navbar_preview.png
# Private local configuration: keep on disk, never push to GitHub
/SHiNE-server/src/main/resources/application.properties
/application.properties
/deploy/backup/scheme/
/shine-solana/shine/create-SHiNE-DAO/dao.config.mainnet.env
**/.env
**/.env.*
!**/.env.example
!**/.env.sample
@@ -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));
}
}
@@ -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());
@@ -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 использует две отдельные операции. */
@@ -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);
@@ -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) { }
}
}
+2 -2
View File
@@ -1,2 +1,2 @@
client.version=1.20.14
server.version=1.16.11
client.version=1.20.15
server.version=1.16.12
+177
View File
@@ -0,0 +1,177 @@
# SHiNE: разрешённые домены email для БЕСПЛАТНОЙ регистрации.
# Один домен на строку; без @. Строки с # — комментарии.
# Сопоставление строгое: поддомены не разрешаются автоматически.
# Список — политика допуска, НЕ гарантия доставки; некоторые адреса исторические.
# Изменения вступают в силу после перезапуска Java-сервера.
# Google
gmail.com
googlemail.com
# Microsoft
outlook.com
outlook.de
outlook.fr
outlook.es
outlook.it
outlook.jp
hotmail.com
hotmail.co.uk
hotmail.de
hotmail.fr
hotmail.es
hotmail.it
hotmail.com.br
hotmail.co.jp
hotmail.com.au
live.com
live.co.uk
live.de
live.fr
live.nl
live.com.au
msn.com
# Yandex
yandex.ru
yandex.com
ya.ru
yandex.by
yandex.kz
yandex.ua
# Mail.ru
mail.ru
bk.ru
list.ru
inbox.ru
internet.ru
# Apple
icloud.com
me.com
mac.com
# Proton
proton.me
protonmail.com
protonmail.ch
pm.me
# Yahoo
yahoo.com
yahoo.co.uk
yahoo.de
yahoo.fr
yahoo.es
yahoo.it
yahoo.ca
yahoo.com.br
yahoo.co.jp
yahoo.com.au
yahoo.co.in
yahoo.com.mx
yahoo.com.sg
yahoo.com.hk
yahoo.com.tw
ymail.com
rocketmail.com
# Rambler
rambler.ru
lenta.ru
autorambler.ru
myrambler.ru
ro.ru
# Germany / DACH
gmx.de
gmx.com
gmx.net
gmx.at
gmx.ch
web.de
mailbox.org
posteo.de
# Poland
wp.pl
onet.pl
interia.pl
o2.pl
gazeta.pl
poczta.fm
op.pl
# Privacy-oriented services
tuta.com
tutanota.com
tutanota.de
tutanota.org
tutamail.com
keemail.me
startmail.com
runbox.com
disroot.org
# France
orange.fr
wanadoo.fr
laposte.net
free.fr
sfr.fr
netcourrier.com
# Italy
libero.it
virgilio.it
alice.it
tin.it
# Czechia and Slovakia
seznam.cz
email.cz
post.cz
centrum.cz
atlas.cz
centrum.sk
azet.sk
# Ukraine
ukr.net
i.ua
# Other Europe
abv.bg
mail.bg
freemail.hu
citromail.hu
# Korea
naver.com
daum.net
hanmail.net
nate.com
# China
qq.com
163.com
126.com
yeah.net
sina.com
sohu.com
139.com
# Brazil
bol.com.br
uol.com.br
ig.com.br
# International
zohomail.com
zoho.com
fastmail.com
aol.com
mail.com
email.com
hey.com
+34
View File
@@ -0,0 +1,34 @@
# SHiNE configuration EXAMPLE. This file is never loaded automatically.
# Copy it to application.properties in the server working directory,
# or provide a private application.properties on the server classpath.
# Never commit application.properties with real credentials.
# Database: replace with your own test/server values.
db.url=jdbc:postgresql://localhost:5432/shine
db.user=
db.password=
server.SHiNE.login=
# Solana/Arweave: disabled until configured.
solana.cluster=devnet
solana.rpcUrl=
solana.users.sync.enabled=false
blockchain.sync.enabled=false
sync.importUserProfileFromPartner.enabled=false
arweave.blocks.publish.enabled=false
arweave.blocks.sync.enabled=false
# Temporary / testing endpoints: off by default.
debug.tempApi.enabled=false
test.freeAvatar.enabled=false
# Other services: fill in real values only in the private config.
dm.delivery.enabled=false
webpush.vapid.public=
webpush.vapid.private=
webpush.vapid.subject=
call.ice.turn.sharedSecret=
# Email verification for free registration: requires the separate allowlist file.
# The deployment script copies allowed-email-domains.txt alongside shine-server.jar.
freeRegistration.email.allowedDomainsFile=allowed-email-domains.txt
+3 -4
View File
@@ -185,9 +185,8 @@ tasks.register('integrationTest', JavaExec) {
dependsOn testClasses
}
tasks.named('build') {
finalizedBy tasks.named('integrationTest')
}
// integrationTest is intentionally NOT attached to build.
// It performs destructive clean-start actions and must be requested explicitly.
tasks.register('startLocal', Exec) {
group = "!!run"
@@ -236,7 +235,7 @@ tasks.register('startLocal', Exec) {
(
cd "${file('SHiNE-server').absolutePath}"
java -Dserver.port="\$WS_PORT" -jar "\$JAR_PATH"
java -Dserver.port="\$WS_PORT" -DfreeRegistration.email.allowedDomainsFile="${file('allowed-email-domains.txt').absolutePath}" -jar "\$JAR_PATH"
) &
SERVER_PID=\$!
trap 'kill \$SERVER_PID 2>/dev/null || true' EXIT INT TERM
+5 -1
View File
@@ -63,7 +63,11 @@ is_denied_path() {
*/scripts/*/runs/*|\
*/scripts/*/keypairs/*|\
*/keys/*|\
*/.git-local-backup/*)
*/.git-local-backup/*|\
/application.properties|\
*/SHiNE-server/src/main/resources/application.properties|\
*/deploy/backup/scheme/*|\
*/shine-solana/shine/create-SHiNE-DAO/dao.config.mainnet.env)
return 0
;;
esac
+2 -1
View File
@@ -41,7 +41,8 @@
Общие скрипты:
- `scripts/deploy_server.sh` — обновить существующий серверный jar и перезапустить systemd service.
- `scripts/deploy_server.sh` — обновить существующий серверный jar, скопировать `allowed-email-domains.txt`
в рабочую папку сервера и перезапустить systemd service (список доменов требуется при включённой бесплатной регистрации).
- `scripts/deploy_ui.sh` — обновить существующий UI, проверить Caddy root и подставить `deploy-config.js`.
## Временные статические сайты
+6
View File
@@ -14,6 +14,7 @@ REMOTE_PUBLIC_FILES_DIR="${REMOTE_PUBLIC_FILES_DIR:-}"
REMOTE_SERVICE_NAME="${REMOTE_SERVICE_NAME:?REMOTE_SERVICE_NAME is required}"
SERVER_PORT="${SERVER_PORT:?SERVER_PORT is required}"
LOCAL_JAR="${LOCAL_JAR:-$ROOT_DIR/SHiNE-server/build/libs/shine-server.jar}"
LOCAL_EMAIL_DOMAINS="${LOCAL_EMAIL_DOMAINS:-$ROOT_DIR/allowed-email-domains.txt}"
BUILD_JAR="${BUILD_JAR:-1}"
REQUIRE_BACKUP="${REQUIRE_BACKUP:-0}"
BACKUP_DIR="${BACKUP_DIR:-$ROOT_DIR/deploy/backup/archive}"
@@ -34,6 +35,10 @@ if [[ ! -f "$LOCAL_JAR" ]]; then
echo "ERROR: локальный jar не найден: $LOCAL_JAR" >&2
exit 1
fi
if [[ ! -s "$LOCAL_EMAIL_DOMAINS" ]]; then
echo "ERROR: не найден или пуст список почтовых доменов: $LOCAL_EMAIL_DOMAINS" >&2
exit 1
fi
echo "==> Deploy server to $TARGET_DOMAIN ($REMOTE_HOST)"
ssh -o BatchMode=yes -o ConnectTimeout=20 "$REMOTE_HOST" "echo SSH OK" >/dev/null
@@ -69,6 +74,7 @@ REMOTE_EXTRA_DIRS=""
[[ -n "$REMOTE_PUBLIC_FILES_DIR" ]] && REMOTE_EXTRA_DIRS+=" '$REMOTE_PUBLIC_FILES_DIR'"
ssh "$REMOTE_HOST" "mkdir -p '$REMOTE_SERVER_DIR' '$REMOTE_DATA_DIR' '$REMOTE_LOGS_DIR'$REMOTE_EXTRA_DIRS"
rsync -az --timeout=120 "$LOCAL_JAR" "$REMOTE_HOST:$REMOTE_SERVER_DIR/shine-server.jar"
rsync -az --timeout=120 "$LOCAL_EMAIL_DOMAINS" "$REMOTE_HOST:$REMOTE_SERVER_DIR/allowed-email-domains.txt"
rsync -az "$TMP_DIR/$REMOTE_SERVICE_NAME.service" "$REMOTE_HOST:/tmp/$REMOTE_SERVICE_NAME.service"
ssh "$REMOTE_HOST" "set -euo pipefail; \
@@ -11,11 +11,25 @@
При необходимости изменить внешним параметром `freeRegistration.email.from`, но адрес обязан относиться к подтверждённому домену.
5. Настройка `freeRegistration.email.allowTestCode=false` по умолчанию. Только для тестирования `true` разрешает код `777777` на этапе подтверждения любой активной заявки. Это полностью обходит подтверждение владения email и НЕ ДОЛЖНО использоваться на публичном/production-сервере.
6. На сервере, где `freeRegistration.enabled=true`, без API-ключа Resend старт завершится ошибкой (fail-closed), даже если тестовый код включён. При создании заявки письмо всегда отправляется.
7. После локальных тестов перезапустить только нужный тестовый сервер по инструкциям deploy (production отдельно согласовывать).
7. В корне репозитория есть `allowed-email-domains.txt` — закрытый список допустимых почтовых доменов.
Файл копируется скриптом `deploy/scripts/deploy_server.sh` рядом с JAR в рабочую директорию сервера.
Не кладите его внутрь JAR и не задавайте путь из UI: проверка выполняется на сервере.
При необходимости путь можно изменить через `freeRegistration.email.allowedDomainsFile` (относительный путь — от
рабочей директории Java-процесса). `./gradlew startLocal` передаёт абсолютный путь к файлу
в корне репозитория, поскольку запускает JAR из `SHiNE-server/`.
После изменения списка или пути требуется перезапуск процесса.
Если `freeRegistration.enabled=true`, а файл отсутствует, пустой или содержит некорректные домены,
регистрация не запустится (fail-closed). На выключенную бесплатную регистрацию этот файл не влияет.
8. После локальных тестов перезапустить только нужный тестовый сервер по инструкциям deploy (production отдельно согласовывать).
## Процесс
- `CheckRegistrationEmail` проверяет известный занятый email, без отправки.
- `CheckRegistrationEmail` проверяет домен по `allowed-email-domains.txt` и затем занятость email, без отправки.
Если домен не разрешён, возвращается `emailAvailable=false` без запроса к БД.
Формат API не менялся: `false` означает «адрес занят **или** домен не разрешён».
То же ограничение повторно применяется в `StartFreeRegistration`, включая прямые запросы к API.
Список проверяется по точному совпадению после `@` (регистр не важен), поддомены и wildcard не допускаются.
Список ограничивает только бесплатную регистрацию с подтверждением email, не регистрацию через Solana.
- `StartFreeRegistration` создаёт случайный 6-значный код и challenge, отправляет письмо через HTTP API Resend;
только после ответа 2xx возвращает `challengeId` и `expiresAtMs`.
- `ConfirmFreeRegistration` принимает код для конкретного challenge. После верного кода
@@ -48,6 +62,7 @@ freeRegistration.email.apiKey=
freeRegistration.email.allowTestCode=false
freeRegistration.email.allowReuse=false
freeRegistration.email.from=SHiNE <noreply@shineup.me>
freeRegistration.email.allowedDomainsFile=allowed-email-domains.txt
```
Параметры читаются из `AppConfig`: системное свойство → переменная окружения
@@ -60,3 +75,22 @@ Resend успешно принял запрос на отправку. Он не
`StartFreeRegistration` и не работает после истечения 1 часа или перезапуска Java.
Для применения изменений настроек нужен перезапуск Java-процесса.
## Обновление разрешённых почтовых доменов
Редактируйте `allowed-email-domains.txt` в корне проекта: по одному домену на строку,
без символа `@`; строки с `#` — комментарии. Например `gmail.com`, но не `*.gmail.com`.
`user@gmail.com` и `user@GMAIL.COM` подходят, `user@sub.gmail.com` — нет, пока его
не добавили отдельной строкой. Новые домены не подхватываются до перезапуска.
Список ограничивает злоупотребления, но сам по себе не гарантирует доставку письма
и не заменяет rate limiting, проверку кода и защиту от ботов.
Быстрая локальная проверка парсера без внешних зависимостей:
```bash
mkdir -p /tmp/shine-allowlist-check
javac -d /tmp/shine-allowlist-check \
SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/AllowedEmailDomains.java \
SHiNE-server/shine-server-archive/src/test/java/server/archive/registration/AllowedEmailDomainsCheck.java
java -cp /tmp/shine-allowlist-check server.archive.registration.AllowedEmailDomainsCheck
```
+10 -2
View File
@@ -35,7 +35,7 @@ export function render({ navigate }) {
info.innerHTML = `
<strong>Почта не нужна для входа или восстановления пароля.</strong>
<p>Мы не используем email для рассылок и сохраняем только хеш от электронного адреса. Один адрес — одна бесплатная регистрация.</p>
<p>Подойдут публичные почтовые сервисы, например Gmail, Яндекс, Mail.ru, Rambler, Yahoo, Outlook, iCloud или Proton Mail. Окончательная проверка — на сервере.</p>
<p>Регистрация доступна с адресами разрешённых почтовых сервисов: например, Gmail, Яндекс, Mail.ru, Rambler, Yahoo, Outlook, iCloud или Proton Mail. Список проверяет сервер.</p>
`;
const status = document.createElement('p');
status.className = 'status-line';
@@ -118,7 +118,15 @@ export function render({ navigate }) {
status.textContent = 'Проверяем адрес…';
try {
const available = await checkRegistrationEmail(address);
if (!available.emailAvailable) throw new Error('Этот email уже использован для бесплатной регистрации.');
if (!available.emailAvailable) {
if (available.emailStatus === 'DOMAIN_NOT_ALLOWED') {
throw new Error('Извините, этот почтовый домен пока не поддерживается. Чтобы защитить SHiNE от массовых и недобросовестных регистраций, мы разрешаем регистрацию только с проверенных почтовых сервисов. Попробуйте другой email, например Gmail, Яндекс, Mail.ru, Outlook или Proton Mail.');
}
if (available.emailStatus === 'ALREADY_REGISTERED') {
throw new Error('На этот email уже зарегистрирован один бесплатный аккаунт SHiNE. Повторная бесплатная регистрация с того же адреса невозможна.');
}
throw new Error('Этот email недоступен для бесплатной регистрации. Попробуйте другой адрес.');
}
status.textContent = 'Отправляем письмо с кодом…';
const started = await startFreeRegistration({ fullLogin: draft.login, keyBundle: draft.preGeneratedKeyBundle, email: address });
if (!screen.isConnected || disposed || requestId !== emailRequestId) return;