SHA256
Немного поправил UI и сделал скетч ESP32 для регистрации
This commit is contained in:
+83
@@ -0,0 +1,83 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import server.logic.ws_protocol.JSON.handlers.registration.RegistrationServiceException;
|
||||
import utils.crypto.Ed25519Util;
|
||||
import javax.sql.DataSource;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
/** Один активный аппаратный регистратор; транспорт не имеет доступа к приватному ключу. */
|
||||
public final class ExternalRegistrar implements RegistrationCertificateSigner, AutoCloseable {
|
||||
public interface Peer {
|
||||
boolean open();
|
||||
void send(Map<String,Object> request) throws Exception;
|
||||
void disconnect();
|
||||
}
|
||||
public record Challenge(String nonce, long expiresAtMs, String serverLogin) {}
|
||||
private record Pending(Peer peer, CompletableFuture<byte[]> result) {}
|
||||
private final DataSource db;
|
||||
private final String namespace, serverLogin;
|
||||
private final byte[] initialKey;
|
||||
private final Map<String,Pending> pending = new ConcurrentHashMap<>();
|
||||
private Peer peer;
|
||||
private long lastPing;
|
||||
private final ScheduledExecutorService timer=Executors.newSingleThreadScheduledExecutor(r->{Thread t=new Thread(r,"registrar-watchdog");t.setDaemon(true);return t;});
|
||||
public ExternalRegistrar(DataSource db,String namespace,String serverLogin) throws Exception {
|
||||
this.db=db; this.namespace=namespace; this.serverLogin=serverLogin.trim();
|
||||
this.initialKey=FreeRegistrationIssuer.configuredNamespaceKey(db,namespace,this.serverLogin);
|
||||
timer.scheduleAtFixedRate(this::expire,5,5,TimeUnit.SECONDS);
|
||||
}
|
||||
public String namespace(){return namespace;}
|
||||
public byte[] publicKey32(){return initialKey.clone();}
|
||||
public Challenge challenge(String ns) {
|
||||
if(!namespace.equals(ns)) throw new IllegalArgumentException("Wrong namespace");
|
||||
byte[] nonce=new byte[32]; new SecureRandom().nextBytes(nonce);
|
||||
return new Challenge(Base64.getUrlEncoder().withoutPadding().encodeToString(nonce),System.currentTimeMillis()+30000,serverLogin);
|
||||
}
|
||||
public boolean authenticate(Challenge c,String ns,long timeMs,byte[] sig) throws Exception {
|
||||
long now=System.currentTimeMillis();
|
||||
if(c==null || !namespace.equals(ns) || now>c.expiresAtMs() || timeMs<now-60000 || timeMs>now+60000) return false;
|
||||
byte[] current=FreeRegistrationIssuer.configuredNamespaceKey(db,namespace,serverLogin);
|
||||
if(!Arrays.equals(current,initialKey)) return false; // ротация ключа требует перезапуска конфигурации
|
||||
String msg="SHINE_REGISTRAR_CONNECT_V1:"+serverLogin+":"+ns+":"+timeMs+":"+c.nonce();
|
||||
return Ed25519Util.verify(msg.getBytes(StandardCharsets.UTF_8),sig,current);
|
||||
}
|
||||
public synchronized boolean attach(Peer p) {
|
||||
if(!p.open() || (connected() && peer!=p)) return false;
|
||||
if(peer!=null && peer!=p)detach(peer);
|
||||
peer=p; lastPing=System.nanoTime(); return true;
|
||||
}
|
||||
public synchronized boolean connected(){return peer!=null && peer.open() && System.nanoTime()-lastPing<TimeUnit.SECONDS.toNanos(100);}
|
||||
public synchronized void ping(Peer p){if(peer==p)lastPing=System.nanoTime();}
|
||||
public synchronized boolean isPeer(Peer p){return peer==p && connected();}
|
||||
public synchronized void detach(Peer p){
|
||||
if(peer==p)peer=null;
|
||||
pending.forEach((id,job)->{if(job.peer()==p && pending.remove(id,job))job.result().completeExceptionally(new RegistrationServiceException(503));});
|
||||
}
|
||||
private void expire(){Peer stale; synchronized(this){stale=connected()?null:peer;if(stale!=null)detach(stale);} if(stale!=null)stale.disconnect();}
|
||||
public void result(Peer p,String id,int status,byte[] raw){
|
||||
Pending job=pending.get(id);
|
||||
if(job==null || job.peer()!=p || !isPeer(p) || !pending.remove(id,job))return;
|
||||
if(status==200 && raw!=null && raw.length<=4096)job.result().complete(raw);
|
||||
else job.result().completeExceptionally(new RegistrationServiceException(switch(status){case 400,403,409,429,500,503->status;default->500;}));
|
||||
}
|
||||
@Override public byte[] issue(String login,byte[] root,byte[] blockchain,byte[] client,byte[] emailHash) throws Exception {
|
||||
if(!login.endsWith("@"+namespace)) throw new IllegalArgumentException("Wrong namespace");
|
||||
if(!Arrays.equals(initialKey,FreeRegistrationIssuer.configuredNamespaceKey(db,namespace,serverLogin))) throw new RegistrationServiceException(503);
|
||||
String id=UUID.randomUUID().toString();
|
||||
Pending job;
|
||||
synchronized(this){if(!connected())throw new RegistrationServiceException(503);job=new Pending(peer,new CompletableFuture<>());pending.put(id,job);}
|
||||
try {
|
||||
job.peer().send(Map.of("op","RegistrarSignRegistration","requestId",id,"payload",Map.of(
|
||||
"login",login,"rootPublicKey",b64(root),"blockchainPublicKey",b64(blockchain),"clientPublicKey",b64(client),"emailSha256",b64(emailHash))));
|
||||
return job.result().get(25,TimeUnit.SECONDS);
|
||||
} catch(ExecutionException e){if(e.getCause() instanceof RegistrationServiceException x)throw x;throw new RegistrationServiceException(503);}
|
||||
catch(InterruptedException e){Thread.currentThread().interrupt();throw new RegistrationServiceException(503);}
|
||||
catch(Exception e){throw new RegistrationServiceException(503);}
|
||||
finally{pending.remove(id,job);}
|
||||
}
|
||||
private static String b64(byte[] b){return Base64.getEncoder().encodeToString(b);}
|
||||
@Override public void close(){timer.shutdownNow();Peer p; synchronized(this){p=peer;if(p!=null)detach(p);} if(p!=null)p.disconnect();}
|
||||
}
|
||||
+16
-5
@@ -23,12 +23,15 @@ import java.util.logging.Logger;
|
||||
public final class FreeRegistrationApiBootstrap {
|
||||
private static volatile FreeRegistrationWorkflow workflow;
|
||||
private static volatile LocalRegistrarSigner signer;
|
||||
private static volatile ExternalRegistrar external;
|
||||
public static ExternalRegistrar externalRegistrar() { return external; }
|
||||
private FreeRegistrationApiBootstrap() {}
|
||||
|
||||
public static synchronized void startOrThrow() throws Exception {
|
||||
if (workflow != null) return;
|
||||
AppConfig cfg=AppConfig.getInstance();
|
||||
LocalRegistrarSigner newSigner=null;
|
||||
ExternalRegistrar newExternal=null;
|
||||
FreeRegistrationIssuer issuer=null;
|
||||
FreeRegistrationPublisher publisher=null;
|
||||
RegistrationEmailSender emailSender=null;
|
||||
@@ -45,10 +48,16 @@ public final class FreeRegistrationApiBootstrap {
|
||||
ArweaveBlocksConfig transport=ArweaveBlocksConfig.load();
|
||||
if(transport.publishMode()!=ArweaveBlocksConfig.PublishMode.TURBO)
|
||||
throw new IllegalStateException("Free registration requires Turbo transport");
|
||||
newSigner=LocalRegistrarSigner.fromConfig(cfg);
|
||||
FreeRegistrationIssuer.validateConfiguredNamespace(dbSource(), newSigner, freeNamespace,
|
||||
cfg.getStringOrEmpty("server.SHiNE.login"));
|
||||
issuer=new FreeRegistrationIssuer(dbSource(),newSigner,allowEmailReuse);
|
||||
String mode=cfg.getStringOrEmpty("freeRegistration.signerMode").trim();
|
||||
if ("external".equals(mode)) {
|
||||
newExternal = new ExternalRegistrar(dbSource(), freeNamespace, cfg.getStringOrEmpty("server.SHiNE.login"));
|
||||
issuer = new FreeRegistrationIssuer(dbSource(), newExternal, allowEmailReuse);
|
||||
} else if (mode.isEmpty() || "local".equals(mode)) {
|
||||
newSigner=LocalRegistrarSigner.fromConfig(cfg);
|
||||
FreeRegistrationIssuer.validateConfiguredNamespace(dbSource(), newSigner, freeNamespace,
|
||||
cfg.getStringOrEmpty("server.SHiNE.login"));
|
||||
issuer=new FreeRegistrationIssuer(dbSource(),newSigner,allowEmailReuse);
|
||||
} else throw new IllegalStateException("Unknown freeRegistration.signerMode");
|
||||
publisher=new FreeRegistrationPublisher(issuer,new TurboDataItemUploader(transport),
|
||||
new VerifiedFreeRegistrationImporter(allowEmailReuse));
|
||||
// Секрет берём ТОЛЬКО из окружения, не из файлов репозитория.
|
||||
@@ -65,13 +74,15 @@ public final class FreeRegistrationApiBootstrap {
|
||||
cfg.getBoolean("freeRegistration.email.allowReuse",false), allowedEmailDomains,
|
||||
freeRegistrationEnabled ? freeNamespace : "");
|
||||
RegistrationApiBridge.install((op,req)->dispatch(newWorkflow,op,req));
|
||||
signer=newSigner; workflow=newWorkflow;
|
||||
signer=newSigner; external=newExternal; workflow=newWorkflow;
|
||||
}
|
||||
public static synchronized void close() {
|
||||
RegistrationApiBridge.uninstall();
|
||||
workflow=null;
|
||||
if(signer!=null) signer.close();
|
||||
signer=null;
|
||||
if(external!=null) external.close();
|
||||
external=null;
|
||||
}
|
||||
public static Map<String,Object> dispatch(FreeRegistrationWorkflow w, String op,Net_Registration_Request req) throws Exception {
|
||||
Map<String,Object> out=new LinkedHashMap<>();
|
||||
|
||||
+7
-1
@@ -59,13 +59,19 @@ public final class FreeRegistrationCertificateV1 {
|
||||
|
||||
public static byte[] issue(String login, byte[] root32, byte[] blockchain32,
|
||||
byte[] client32, String email, RegistrarSigner signer) {
|
||||
return issueWithEmailHash(login, root32, blockchain32, client32, emailHash(email), signer);
|
||||
}
|
||||
|
||||
public static byte[] issueWithEmailHash(String login, byte[] root32, byte[] blockchain32,
|
||||
byte[] client32, byte[] emailHash, RegistrarSigner signer) {
|
||||
require32(emailHash);
|
||||
byte[] fields = identityFields(login, root32, blockchain32, client32);
|
||||
byte[] inner = signer.sign(innerMessage(fields));
|
||||
if (inner.length != 64) throw new IllegalStateException("Invalid inner signature length");
|
||||
ByteArrayOutputStream payload = new ByteArrayOutputStream();
|
||||
payload.writeBytes(fields);
|
||||
payload.writeBytes(inner);
|
||||
payload.writeBytes(emailHash(email));
|
||||
payload.writeBytes(emailHash);
|
||||
byte[] data = payload.toByteArray();
|
||||
byte[] owner = signer.publicKey32();
|
||||
require32(owner);
|
||||
|
||||
+24
-4
@@ -11,7 +11,7 @@ import java.util.Arrays;
|
||||
/** Выдача (без публикации). Stage 8 публикует через Turbo и импортирует тот же raw DataItem. */
|
||||
public final class FreeRegistrationIssuer {
|
||||
private final DataSource db;
|
||||
private final RegistrarSigner signer;
|
||||
private final RegistrationCertificateSigner signer;
|
||||
private final boolean allowEmailReuse;
|
||||
|
||||
public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer) {
|
||||
@@ -19,6 +19,15 @@ public final class FreeRegistrationIssuer {
|
||||
}
|
||||
|
||||
public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer, boolean allowEmailReuse) {
|
||||
this(db, new RegistrationCertificateSigner() {
|
||||
public byte[] publicKey32() { return signer.publicKey32(); }
|
||||
public byte[] issue(String login, byte[] root, byte[] blockchain, byte[] client, byte[] emailHash) {
|
||||
return FreeRegistrationCertificateV1.issueWithEmailHash(login, root, blockchain, client, emailHash, signer);
|
||||
}
|
||||
}, allowEmailReuse);
|
||||
}
|
||||
|
||||
public FreeRegistrationIssuer(DataSource db, RegistrationCertificateSigner signer, boolean allowEmailReuse) {
|
||||
this.db = java.util.Objects.requireNonNull(db);
|
||||
this.signer = java.util.Objects.requireNonNull(signer);
|
||||
this.allowEmailReuse = allowEmailReuse;
|
||||
@@ -27,6 +36,11 @@ public final class FreeRegistrationIssuer {
|
||||
/** Проверяет привязку локального ключа и сервера до открытия бесплатной регистрации. */
|
||||
static void validateConfiguredNamespace(DataSource db, RegistrarSigner signer, String namespace,
|
||||
String localServerLogin) throws Exception {
|
||||
if (!Arrays.equals(configuredNamespaceKey(db, namespace, localServerLogin), signer.publicKey32()))
|
||||
throw new IllegalStateException("Registrar public key does not match configured namespace");
|
||||
}
|
||||
|
||||
static byte[] configuredNamespaceKey(DataSource db, String namespace, String localServerLogin) throws Exception {
|
||||
if (localServerLogin == null || localServerLogin.isBlank())
|
||||
throw new IllegalStateException("server.SHiNE.login is required for free registration");
|
||||
try (Connection conn = db.getConnection();
|
||||
@@ -39,11 +53,11 @@ public final class FreeRegistrationIssuer {
|
||||
if (!rs.next() || rs.getInt("namespace_type") != 2)
|
||||
throw new IllegalStateException("Configured free registration namespace is unavailable");
|
||||
byte[] namespaceKey = Base58Util.decode(rs.getString("registrar_pubkey"));
|
||||
if (!Arrays.equals(namespaceKey, signer.publicKey32()))
|
||||
throw new IllegalStateException("Registrar public key does not match configured namespace");
|
||||
if (namespaceKey.length != 32) throw new IllegalStateException("Invalid namespace key");
|
||||
String namespaceServer = rs.getString("default_server_login");
|
||||
if (namespaceServer == null || !namespaceServer.equalsIgnoreCase(localServerLogin.trim()))
|
||||
throw new IllegalStateException("Configured free namespace belongs to another access server");
|
||||
return namespaceKey;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,6 +107,12 @@ public final class FreeRegistrationIssuer {
|
||||
}
|
||||
// Это только подписанный артефакт, не активная регистрация. Перед Turbo
|
||||
// и локальным импортом обязательно повторять уникальность в транзакции БД.
|
||||
return FreeRegistrationCertificateV1.issue(fullLogin, root32, blockchain32, client32, email, signer);
|
||||
byte[] signed = signer.issue(fullLogin, root32, blockchain32, client32, expectedEmail);
|
||||
var verified = FreeRegistrationCertificateV1.verify(signed, signer.publicKey32());
|
||||
if (!fullLogin.equals(verified.login()) || !Arrays.equals(root32, verified.rootKey()) ||
|
||||
!Arrays.equals(blockchain32, verified.blockchainKey()) || !Arrays.equals(client32, verified.clientKey()) ||
|
||||
!Arrays.equals(expectedEmail, verified.emailSha256()))
|
||||
throw new IllegalStateException("Registrar returned mismatched certificate");
|
||||
return signed;
|
||||
}
|
||||
}
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package server.archive.registration;
|
||||
|
||||
/** Выдаёт только полный регистрационный сертификат, не произвольную подпись. */
|
||||
public interface RegistrationCertificateSigner {
|
||||
byte[] publicKey32();
|
||||
byte[] issue(String login, byte[] root, byte[] blockchain, byte[] client, byte[] emailHash) throws Exception;
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package server.archive;
|
||||
import server.archive.registration.*;
|
||||
import server.logic.ws_protocol.JSON.handlers.registration.RegistrationServiceException;
|
||||
import sync.util.Base58Util;
|
||||
import utils.crypto.Ed25519Util;
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.*;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.*;
|
||||
public class ExternalRegistrarCheck {
|
||||
static <T> T mock(Class<T> cls,java.lang.reflect.InvocationHandler h){return cls.cast(Proxy.newProxyInstance(cls.getClassLoader(),new Class[]{cls},h));}
|
||||
static DataSource db(byte[] owner){return mock(DataSource.class,(obj,m,a)->{
|
||||
if(!m.getName().equals("getConnection"))throw new UnsupportedOperationException(m.getName());
|
||||
return mock(Connection.class,(o,method,args)->switch(method.getName()){
|
||||
case "close","setReadOnly"->null;
|
||||
case "prepareStatement"->mock(PreparedStatement.class,(po,pm,pa)->switch(pm.getName()){
|
||||
case "close","setString"->null;
|
||||
case "executeQuery"->mock(ResultSet.class,(ro,rm,ra)->switch(rm.getName()){
|
||||
case "close"->null;case "next"->true;case "getInt"->2;case "getString"->ra[0].equals("registrar_pubkey")?Base58Util.encode(owner):"testserver";default->throw new UnsupportedOperationException(rm.getName());});
|
||||
default->throw new UnsupportedOperationException(pm.getName());});
|
||||
default->throw new UnsupportedOperationException(method.getName());});});}
|
||||
static void require(boolean x){if(!x)throw new AssertionError();}
|
||||
static void expect503(ExternalRegistrar reg) throws Exception {try{reg.issue("Example@free",new byte[32],new byte[32],new byte[32],new byte[32]);throw new AssertionError("Expected failure");}catch(RegistrationServiceException e){require(e.status()==503);}}
|
||||
public static void main(String[] args)throws Exception{
|
||||
byte[] seed=new byte[32],owner=Ed25519Util.derivePublicKey(seed);
|
||||
try(ExternalRegistrar reg=new ExternalRegistrar(db(owner),"free","testserver")){
|
||||
expect503(reg);var c=reg.challenge("free");long t=System.currentTimeMillis();byte[] msg=("SHINE_REGISTRAR_CONNECT_V1:testserver:free:"+t+":"+c.nonce()).getBytes(StandardCharsets.UTF_8);byte[] sig=Ed25519Util.sign(msg,seed);
|
||||
require(reg.authenticate(c,"free",t,sig));sig[0]^=1;require(!reg.authenticate(c,"free",t,sig));
|
||||
BlockingQueue<Map<String,Object>> queue=new LinkedBlockingQueue<>();
|
||||
ExternalRegistrar.Peer peer=new ExternalRegistrar.Peer(){public boolean open(){return true;}public void send(Map<String,Object> request){queue.add(request);}public void disconnect(){}};
|
||||
ExternalRegistrar.Peer stranger=new ExternalRegistrar.Peer(){public boolean open(){return true;}public void send(Map<String,Object> request){}public void disconnect(){}};
|
||||
require(reg.attach(peer));require(!reg.attach(stranger));
|
||||
var executor=Executors.newSingleThreadExecutor();try{
|
||||
var f=executor.submit(()->reg.issue("Example@free",new byte[32],new byte[32],new byte[32],new byte[32]));
|
||||
var request=queue.poll(2,TimeUnit.SECONDS);require(request!=null);String id=(String)request.get("requestId");
|
||||
reg.result(stranger,id,200,new byte[]{9});require(!f.isDone());reg.result(peer,"unknown",200,new byte[]{9});require(!f.isDone());reg.result(peer,id,200,new byte[]{1,2});require(Arrays.equals(f.get(2,TimeUnit.SECONDS),new byte[]{1,2}));
|
||||
var f2=executor.submit(()->reg.issue("Example@free",new byte[32],new byte[32],new byte[32],new byte[32]));require(queue.poll(2,TimeUnit.SECONDS)!=null);reg.detach(peer);try{f2.get(2,TimeUnit.SECONDS);throw new AssertionError("Expected disconnect");}catch(ExecutionException e){require(e.getCause() instanceof RegistrationServiceException x&&x.status()==503);}
|
||||
}finally{executor.shutdownNow();}
|
||||
}System.out.println("PASS: challenge signature, wrong key, disconnected, exclusive peer, request correlation, wrong peer, disconnect while pending");
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import utils.crypto.Ed25519Util;
|
||||
import java.util.HexFormat;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ExternalRegistrarVectorTest {
|
||||
@Test void firmwareReferenceVector() {
|
||||
byte[] seed=new byte[32],root=new byte[32],chain=new byte[32],client=new byte[32],email=new byte[32];
|
||||
for(int i=0;i<32;i++){seed[i]=(byte)i;root[i]=(byte)(i+32);chain[i]=(byte)(i+64);client[i]=(byte)(i+96);email[i]=(byte)(i+128);}
|
||||
try(var signer=new LocalRegistrarSigner(seed)) {
|
||||
byte[] item=FreeRegistrationCertificateV1.issueWithEmailHash("Example@free",root,chain,client,email,signer);
|
||||
assertEquals(EXPECTED,HexFormat.of().formatHex(item));
|
||||
assertArrayEquals(email,FreeRegistrationCertificateV1.verify(item,signer.publicKey32()).emailSha256());
|
||||
item[item.length-1]^=1;
|
||||
assertThrows(IllegalArgumentException.class,()->FreeRegistrationCertificateV1.verify(item,signer.publicKey32()));
|
||||
}
|
||||
}
|
||||
// Synthetic public test vector; never use its seed for a real namespace.
|
||||
private static final String EXPECTED = "02003830de5c252e8d4da7dab6de28fdc2f8693dc709f4688895c2e92e2092113f4172cd21a1c7e9842c4cac6fd0cb0537c958d8ad22a00f0297082275df4edf730e03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b800000300000000000000390000000000000006064170701074657374353539390274067265671050726f746f636f6c345348694e452d467265652d526567697374726174696f6e2d56310001000c4578616d706c654066726565202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f779d957dfe14d4d4097cfcb567944a1a3b4ee04024b71c189d95cfe15ed1bba8a5cf7b7a314e264437a0361f7422c287da24e70d785a0e7c2b1f8cc7073e6d05808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f";
|
||||
}
|
||||
+1
@@ -25,6 +25,7 @@ public class ConnectionContext {
|
||||
// Статусы аутентификации
|
||||
public static final int AUTH_STATUS_NONE = 0; // анонимный / не авторизован
|
||||
public static final int AUTH_STATUS_AUTH_IN_PROGRESS = 1; // выполнен challenge (AuthChallenge или SessionChallenge)
|
||||
public static final int AUTH_STATUS_REGISTRAR = 3;
|
||||
public static final int AUTH_STATUS_USER = 2; // авторизованный пользователь
|
||||
|
||||
// При успешной авторизации отдельно фиксируем отношение пользователя к этому серверу.
|
||||
|
||||
+2
@@ -37,6 +37,8 @@ public final class Net_Registration_Handler implements JsonMessageHandler {
|
||||
out.setOp(request.getOp()); out.setRequestId(request.getRequestId());
|
||||
out.setStatus(WireCodes.Status.OK); out.setValues(values);
|
||||
return out;
|
||||
} catch (RegistrationServiceException e) {
|
||||
return NetExceptionResponseFactory.error(request,e.status(),"REGISTRAR_ERROR","Регистратор не выдал сертификат");
|
||||
} catch (IllegalArgumentException e) {
|
||||
// Без echo исходного email, чтобы не публиковать PII в ответе/логе.
|
||||
return NetExceptionResponseFactory.error(request,400,"INVALID_REGISTRATION_INPUT","Данные регистрации не прошли проверку");
|
||||
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.registration;
|
||||
|
||||
/** Ошибка внешнего регистратора, безопасная для публичного API. */
|
||||
public final class RegistrationServiceException extends Exception {
|
||||
private final int status;
|
||||
public RegistrationServiceException(int status) { super("Registration signer unavailable: " + status); this.status=status; }
|
||||
public int status() { return status; }
|
||||
}
|
||||
@@ -37,7 +37,13 @@ public class BlockchainWsEndpoint {
|
||||
new ThreadPoolExecutor.AbortPolicy()
|
||||
);
|
||||
|
||||
private Session session;
|
||||
// Подтверждение регистрации может ожидать сеть; ответ регистратора никогда не ждёт этот пул.
|
||||
private static final ExecutorService REGISTRATION_EXECUTOR = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.SECONDS,
|
||||
new ArrayBlockingQueue<>(128), r -> {Thread t = new Thread(r, "registration-worker"); t.setDaemon(true); return t;}, new ThreadPoolExecutor.AbortPolicy());
|
||||
private static final ExecutorService REGISTRAR_EXECUTOR = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.SECONDS,
|
||||
new ArrayBlockingQueue<>(128), r -> {Thread t = new Thread(r, "registrar-worker"); t.setDaemon(true); return t;}, new ThreadPoolExecutor.AbortPolicy());
|
||||
private volatile Session session;
|
||||
private volatile RegistrarSocket registrar;
|
||||
|
||||
/** Контекст для текущего WebSocket-соединения. */
|
||||
private final ConnectionContext connectionContext = new ConnectionContext();
|
||||
@@ -55,6 +61,7 @@ public class BlockchainWsEndpoint {
|
||||
public void onConnect(Session session) {
|
||||
this.session = session;
|
||||
connectionContext.setWsSession(session);
|
||||
registrar = new RegistrarSocket(session, connectionContext);
|
||||
log.info("WS connected: {}", session.getRemoteAddress());
|
||||
}
|
||||
|
||||
@@ -65,10 +72,14 @@ public class BlockchainWsEndpoint {
|
||||
if (message == null || message.isBlank()) return;
|
||||
|
||||
// Добавляем обработку в очередь данного соединения (строго по порядку)
|
||||
enqueue(() -> processJsonAndReply(message));
|
||||
String op = RegistrarSocket.operation(message);
|
||||
Executor executor = (registrar != null && registrar.dedicated() || op.startsWith("Registrar"))
|
||||
? REGISTRAR_EXECUTOR : (op.equals("ConfirmFreeRegistration") || op.equals("StartFreeRegistration"))
|
||||
? REGISTRATION_EXECUTOR : WS_EXECUTOR;
|
||||
enqueue(() -> processJsonAndReply(message), executor);
|
||||
}
|
||||
|
||||
private void enqueue(Runnable task) {
|
||||
private void enqueue(Runnable task, Executor executor) {
|
||||
synchronized (queueLock) {
|
||||
queueTail = queueTail.thenRunAsync(() -> {
|
||||
try {
|
||||
@@ -78,14 +89,26 @@ public class BlockchainWsEndpoint {
|
||||
log.error("❌ Unhandled error in ws task", t);
|
||||
trySendJsonError();
|
||||
}
|
||||
}, WS_EXECUTOR);
|
||||
}, executor).exceptionally(ex -> {
|
||||
Session current = session; if (current != null) current.close(1013,"Server busy");
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void processJsonAndReply(String message) {
|
||||
if (session == null || !session.isOpen()) return;
|
||||
|
||||
log.info("📥 Получено TEXT-сообщение от клиента: {}", message);
|
||||
String op = RegistrarSocket.operation(message);
|
||||
RegistrarSocket r = registrar;
|
||||
if (r != null && (r.dedicated() || op.startsWith("Registrar"))) {
|
||||
try { r.process(message); } catch (Exception e) { r.disconnect(); }
|
||||
return;
|
||||
}
|
||||
// В заявках есть email и коды подтверждения — не печатаем их в журнал.
|
||||
if (op.equals("StartFreeRegistration") || op.equals("ConfirmFreeRegistration") || op.equals("CheckRegistrationEmail"))
|
||||
log.info("Registration request: {}",op);
|
||||
else log.info("📥 Получено TEXT-сообщение от клиента: {}", message);
|
||||
|
||||
String respJson;
|
||||
try {
|
||||
@@ -118,6 +141,7 @@ public class BlockchainWsEndpoint {
|
||||
public void onClose(int statusCode, String reason) {
|
||||
log.info("WS closed: {} {}", statusCode, reason);
|
||||
|
||||
RegistrarSocket r = registrar; if (r != null) r.closed();
|
||||
ActiveConnectionsRegistry.getInstance().remove(connectionContext);
|
||||
connectionContext.reset();
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package server.ws;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.eclipse.jetty.websocket.api.Session;
|
||||
import server.archive.registration.ExternalRegistrar;
|
||||
import server.archive.registration.FreeRegistrationApiBootstrap;
|
||||
import server.logic.ws_protocol.JSON.ConnectionContext;
|
||||
import server.logic.ws_protocol.JSON.JsonInboundProcessor;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
|
||||
/** Отдельная роль на /ws. Не допускает перехода в обычную пользовательскую авторизацию. */
|
||||
final class RegistrarSocket implements ExternalRegistrar.Peer {
|
||||
private static final ObjectMapper JSON=new ObjectMapper();
|
||||
private final Session session;
|
||||
private final ConnectionContext ctx;
|
||||
private ExternalRegistrar.Challenge challenge;
|
||||
private volatile boolean dedicated;
|
||||
RegistrarSocket(Session session,ConnectionContext ctx){this.session=session;this.ctx=ctx;}
|
||||
boolean dedicated(){return dedicated;}
|
||||
static String operation(String raw){try{return JSON.readTree(raw).path("op").asText();}catch(Exception e){return "";}}
|
||||
@Override public boolean open(){return session.isOpen();}
|
||||
@Override public synchronized void send(Map<String,Object> request) throws Exception {session.getRemote().sendString(JSON.writeValueAsString(request));}
|
||||
private synchronized void sendRaw(String raw) throws Exception {if(raw!=null)session.getRemote().sendString(raw);}
|
||||
@Override public void disconnect(){session.close(1008,"Registrar connection expired");}
|
||||
void closed(){ExternalRegistrar r=FreeRegistrationApiBootstrap.externalRegistrar();if(r!=null)r.detach(this);}
|
||||
void process(String raw) throws Exception {
|
||||
JsonNode node=JSON.readTree(raw), p=node.path("payload");
|
||||
String op=node.path("op").asText(), id=node.path("requestId").asText();
|
||||
ExternalRegistrar r=FreeRegistrationApiBootstrap.externalRegistrar();
|
||||
if(id.isBlank() || id.length()>128 || raw.length()>8192){disconnect();return;}
|
||||
if(r==null){reply(op,id,503,Map.of());return;}
|
||||
switch(op){
|
||||
case "RegistrarChallenge" -> {
|
||||
if(!ctx.isAnonymous() || ctx.isServerConnection() || r.isPeer(this)){reply(op,id,403,Map.of());return;}
|
||||
dedicated=true;
|
||||
try{challenge=r.challenge(p.path("namespace").asText());reply(op,id,200,Map.of("nonce",challenge.nonce(),"expiresAtMs",challenge.expiresAtMs(),"serverLogin",challenge.serverLogin()));}
|
||||
catch(IllegalArgumentException e){challenge=null;reply(op,id,403,Map.of());}
|
||||
}
|
||||
case "RegistrarConnect" -> {
|
||||
var c=challenge;challenge=null;
|
||||
boolean ok=false;
|
||||
try{ok=dedicated && ctx.isAnonymous() && "1.0".equals(p.path("version").asText()) &&
|
||||
r.authenticate(c,p.path("namespace").asText(),p.path("timeMs").asLong(),Base64.getDecoder().decode(p.path("signatureB64").asText())) && r.attach(this);}
|
||||
catch(Exception ignored){}
|
||||
if(ok){ctx.setAuthenticationStatus(ConnectionContext.AUTH_STATUS_REGISTRAR);reply(op,id,200,Map.of());}
|
||||
else {reply(op,id,403,Map.of());disconnect();}
|
||||
}
|
||||
case "RegistrarSignResult" -> {
|
||||
if(!r.isPeer(this)){disconnect();return;}
|
||||
int status=node.path("status").asInt(500);byte[] item=null;
|
||||
if(status==200)try{item=Base64.getDecoder().decode(p.path("dataItemB64").asText());}catch(IllegalArgumentException ignored){}
|
||||
r.result(this,id,status,item); // событие-ответ, без дополнительного ACK
|
||||
}
|
||||
case "Ping" -> {
|
||||
if(!r.isPeer(this)){disconnect();return;}
|
||||
r.ping(this);sendRaw(JsonInboundProcessor.processJson(raw,ctx));
|
||||
}
|
||||
default -> {reply(op,id,403,Map.of());disconnect();}
|
||||
}
|
||||
}
|
||||
private void reply(String op,String id,int status,Map<String,Object> payload) throws Exception {
|
||||
send(Map.of("op",op,"requestId",id,"status",status,"payload",payload));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package server.ws;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.servlet.http.HttpServlet;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import server.archive.registration.FreeRegistrationApiBootstrap;
|
||||
import server.logic.ws_protocol.JSON.ActiveConnectionsRegistry;
|
||||
import shine.db.DbController;
|
||||
import utils.config.AppConfig;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
|
||||
/** Публичные агрегаты; не содержит идентификаторов пользователей/сессий или секретов. */
|
||||
final class ServerStatusServlet extends HttpServlet {
|
||||
private static final ObjectMapper JSON=new ObjectMapper();
|
||||
private static Map<String,Object> cached;
|
||||
private static long cacheAt;
|
||||
private static synchronized Map<String,Object> registered() throws Exception {
|
||||
if(cached!=null && System.nanoTime()-cacheAt<10_000_000_000L)return cached;
|
||||
long total=0,free=0,paid=0;List<Map<String,Object>> namespaces=new ArrayList<>();
|
||||
try(var c=DbController.getInstance().getConnection();var q=c.prepareStatement("""
|
||||
SELECT COALESCE(n.namespace,i.namespace,'') AS namespace, count(i.normalized_login) AS total,
|
||||
count(*) FILTER (WHERE i.registration_status='FREE_CERT') AS free,
|
||||
count(*) FILTER (WHERE i.registration_status='PAID') AS paid
|
||||
FROM shine_namespace_current n FULL OUTER JOIN user_identity_current i ON i.namespace=n.namespace
|
||||
GROUP BY COALESCE(n.namespace,i.namespace,'') ORDER BY 1
|
||||
""");var rs=q.executeQuery()){
|
||||
while(rs.next()){long t=rs.getLong("total"),f=rs.getLong("free"),p=rs.getLong("paid");total+=t;free+=f;paid+=p;
|
||||
namespaces.add(Map.of("namespace",rs.getString("namespace"),"total",t,"free",f,"paid",p));}
|
||||
}
|
||||
cached=Map.of("total",total,"free",free,"paid",paid,"namespaces",List.copyOf(namespaces));cacheAt=System.nanoTime();return cached;
|
||||
}
|
||||
@Override protected void doGet(HttpServletRequest req,HttpServletResponse resp)throws IOException{
|
||||
resp.setHeader("Cache-Control","no-store");resp.setHeader("X-Content-Type-Options","nosniff");
|
||||
if("/status".equals(req.getServletPath())){resp.setContentType("text/html;charset=UTF-8");resp.getWriter().write(HTML);return;}
|
||||
resp.setContentType("application/json;charset=UTF-8");
|
||||
try{
|
||||
var active=ActiveConnectionsRegistry.getInstance().getAllConnectionsSnapshot().stream().filter(c->c.isAuthenticatedUser() && c.getWsSession()!=null && c.getWsSession().isOpen()).toList();
|
||||
long users=active.stream().map(c->c.getLogin()).filter(Objects::nonNull).map(s->s.toLowerCase(Locale.ROOT)).distinct().count();
|
||||
long sessions=active.stream().map(c->c.getSessionId()).filter(Objects::nonNull).distinct().count();
|
||||
var external=FreeRegistrationApiBootstrap.externalRegistrar();var cfg=AppConfig.getInstance();
|
||||
Map<String,Object> registrar=Map.of("mode",external!=null?"external":cfg.getBoolean("freeRegistration.enabled",false)?"local":"disabled",
|
||||
"namespace",cfg.getStringOrEmpty("freeRegistration.namespace"),"connected",external!=null && external.connected());
|
||||
JSON.writeValue(resp.getWriter(),Map.of("serverVersion",cfg.getStringOrEmpty("server.version"),"serverStatus","ONLINE","updatedAtMs",System.currentTimeMillis(),"registered",registered(),"online",Map.of("users",users,"sessions",sessions),"registrar",registrar));
|
||||
}catch(Exception e){resp.setStatus(503);JSON.writeValue(resp.getWriter(),Map.of("serverStatus","DEGRADED","error","Statistics unavailable"));}
|
||||
}
|
||||
private static final String HTML="""
|
||||
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>SHiNE Server Status</title>
|
||||
<style>body{background:#101820;color:#e3edf2;font:16px system-ui;max-width:760px;margin:32px auto;padding:0 20px}h1{color:#7ee6c4}section{border:1px solid #334b56;border-radius:12px;padding:18px;margin:16px 0}table{width:100%;border-collapse:collapse}td,th{text-align:left;padding:8px;border-bottom:1px solid #334b56}small{color:#aabdc7}</style></head>
|
||||
<body><h1>SHiNE Server Status</h1><p id="status">Loading…</p><section><h2>Registrar</h2><p id="registrar"></p></section><section><h2>Registered users</h2><p id="registered"></p><table><thead><tr><th>Namespace</th><th>Total</th><th>Free</th><th>Paid</th></tr></thead><tbody id="rows"></tbody></table></section><section><h2>Online</h2><p id="online"></p></section><small id="updated"></small>
|
||||
<script>const el=id=>document.getElementById(id);async function refresh(){try{const r=await fetch('/api/status',{cache:'no-store'});if(!r.ok)throw Error();const d=await r.json();el('status').textContent=d.serverStatus+' · '+d.serverVersion;const a=d.registrar;el('registrar').textContent=a.mode+' · @'+a.namespace+' · '+(a.mode==='external'?(a.connected?'CONNECTED':'DISCONNECTED'):'not external');const n=d.registered;el('registered').textContent='Total: '+n.total+' | Free: '+n.free+' | Paid: '+n.paid;el('rows').replaceChildren();for(const x of n.namespaces){const tr=document.createElement('tr');for(const v of [x.namespace?'@'+x.namespace:'(no namespace)',x.total,x.free,x.paid]){const td=document.createElement('td');td.textContent=v;tr.append(td)}el('rows').append(tr)}el('online').textContent='Users: '+d.online.users+' | Sessions: '+d.online.sessions;el('updated').textContent='Updated: '+new Date(d.updatedAtMs).toLocaleString()+' · Refresh every minute';}catch(e){el('status').textContent='Statistics unavailable (last successful values may be stale)'}}refresh();setInterval(refresh,60000);</script></body></html>
|
||||
""";
|
||||
}
|
||||
@@ -79,6 +79,9 @@ public final class WsServer {
|
||||
// Universal Solana HTTP JSON-RPC gateway
|
||||
context.addServlet(new ServletHolder(new SolanaRpcGateway()), "/solana-rpc");
|
||||
|
||||
context.addServlet(new ServletHolder(new ServerStatusServlet()), "/status");
|
||||
context.addServlet(new ServletHolder(new ServerStatusServlet()), "/api/status");
|
||||
|
||||
// HTTP debug API
|
||||
DebugApiConfigurator.register(context);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user