Compare commits
1 commit
Author | SHA1 | Date | |
---|---|---|---|
83ba843bf6 |
14 changed files with 205 additions and 220 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
@ -128,7 +128,7 @@ publish/
|
|||
*.publishproj
|
||||
|
||||
# NuGet Packages Directory
|
||||
## TO!DO: If you have NuGet Package Restore enabled, uncomment the next line
|
||||
## TODO: If you have NuGet Package Restore enabled, uncomment the next line
|
||||
#packages/
|
||||
|
||||
# Windows Azure Build Output
|
||||
|
|
|
@ -3,7 +3,7 @@ main: buttondevteam.website.ButtonWebsiteModule
|
|||
version: 4.0
|
||||
author: NorbiPeti
|
||||
depend:
|
||||
- ThorpeCore
|
||||
- ButtonCore
|
||||
commands:
|
||||
login:
|
||||
aliases: [web, weblogin, website]
|
32
pom.xml
32
pom.xml
|
@ -45,6 +45,11 @@
|
|||
<!-- <artifactSet> <includes> <include>org.shredzone.acme4j:acme4j-client</include>
|
||||
<include>org.shredzone.acme4j:acme4j-utils</include> <include>org.bouncycastle:bcprov-jdk15on</include>
|
||||
</includes> </artifactSet> -->
|
||||
<pluginExecution>
|
||||
<action>
|
||||
<execute />
|
||||
</action>
|
||||
</pluginExecution>
|
||||
<filters>
|
||||
<filter>
|
||||
<artifact>*:*</artifact>
|
||||
|
@ -63,9 +68,6 @@
|
|||
</build>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<branch>
|
||||
master
|
||||
</branch>
|
||||
</properties>
|
||||
|
||||
<repositories>
|
||||
|
@ -121,40 +123,24 @@
|
|||
<dependency>
|
||||
<groupId>com.github.TBMCPlugins.ButtonCore</groupId>
|
||||
<artifactId>ButtonCore</artifactId>
|
||||
<version>${branch}-SNAPSHOT</version>
|
||||
<version>master-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.shredzone.acme4j/acme4j-client -->
|
||||
<dependency>
|
||||
<groupId>org.shredzone.acme4j</groupId>
|
||||
<artifactId>acme4j-client</artifactId>
|
||||
<version>2.1</version>
|
||||
<version>0.10</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.shredzone.acme4j</groupId>
|
||||
<artifactId>acme4j-utils</artifactId>
|
||||
<version>2.1</version>
|
||||
<version>0.10</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on -->
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk15on</artifactId>
|
||||
<version>1.60</version>
|
||||
<version>1.57</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>ci</id>
|
||||
<activation>
|
||||
<property>
|
||||
<name>env.TRAVIS_BRANCH</name>
|
||||
</property>
|
||||
</activation>
|
||||
<properties>
|
||||
<!-- Override only if necessary -->
|
||||
<branch>${env.TRAVIS_BRANCH}</branch>
|
||||
</properties>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
||||
|
|
|
@ -13,22 +13,32 @@
|
|||
*/ //Modified
|
||||
package buttondevteam.website;
|
||||
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.website.page.AcmeChallengePage;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Writer;
|
||||
import java.net.URI;
|
||||
import java.security.KeyPair;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
import org.shredzone.acme4j.*;
|
||||
import org.shredzone.acme4j.challenge.Challenge;
|
||||
import org.shredzone.acme4j.challenge.Http01Challenge;
|
||||
import org.shredzone.acme4j.exception.AcmeConflictException;
|
||||
import org.shredzone.acme4j.exception.AcmeException;
|
||||
import org.shredzone.acme4j.util.CSRBuilder;
|
||||
import org.shredzone.acme4j.util.CertificateUtils;
|
||||
import org.shredzone.acme4j.util.KeyPairUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.URI;
|
||||
import java.security.KeyPair;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.website.page.AcmeChallengePage;
|
||||
|
||||
/**
|
||||
* A simple client test tool.
|
||||
|
@ -37,16 +47,16 @@ import java.util.Collection;
|
|||
*/
|
||||
public class AcmeClient {
|
||||
// File name of the User Key Pair
|
||||
public static final File USER_KEY_FILE = new File("user.key");
|
||||
private static final File USER_KEY_FILE = new File("user.key");
|
||||
|
||||
// File name of the Domain Key Pair
|
||||
public static final File DOMAIN_KEY_FILE = new File("domain.key");
|
||||
private static final File DOMAIN_KEY_FILE = new File("domain.key");
|
||||
|
||||
// File name of the CSR
|
||||
public static final File DOMAIN_CSR_FILE = new File("domain.csr");
|
||||
private static final File DOMAIN_CSR_FILE = new File("domain.csr");
|
||||
|
||||
// File name of the signed certificate
|
||||
public static final File DOMAIN_CHAIN_FILE = new File("domain-chain.crt");
|
||||
private static final File DOMAIN_CHAIN_FILE = new File("domain-chain.crt");
|
||||
|
||||
// RSA key size of generated key pairs
|
||||
private static final int KEY_SIZE = 2048;
|
||||
|
@ -67,17 +77,16 @@ public class AcmeClient {
|
|||
|
||||
// Create a session for Let's Encrypt.
|
||||
// Use "acme://letsencrypt.org" for production server
|
||||
Session session = new Session("acme://letsencrypt.org" + (TBMCCoreAPI.IsTestServer() ? "/staging" : ""));
|
||||
Session session = new Session("acme://letsencrypt.org" + (TBMCCoreAPI.IsTestServer() ? "/staging" : ""),
|
||||
userKeyPair);
|
||||
|
||||
// Get the Registration to the account.
|
||||
// If there is no account yet, create a new one.
|
||||
Account acc = findOrRegisterAccount(session, userKeyPair);
|
||||
|
||||
Order order = acc.newOrder().domains(domains).create();
|
||||
Registration reg = findOrRegisterAccount(session);
|
||||
|
||||
// Separately authorize every requested domain.
|
||||
for (Authorization auth : order.getAuthorizations()) {
|
||||
authorize(auth);
|
||||
for (String domain : domains) {
|
||||
authorize(reg, domain);
|
||||
}
|
||||
|
||||
// Load or create a key pair for the domains. This should not be the userKeyPair!
|
||||
|
@ -93,44 +102,19 @@ public class AcmeClient {
|
|||
csrb.write(out);
|
||||
}
|
||||
|
||||
LOG.info("Ordering certificate...");
|
||||
// Order the certificate
|
||||
order.execute(csrb.getEncoded());
|
||||
|
||||
// Wait for the order to complete
|
||||
try {
|
||||
int attempts = 10;
|
||||
while (order.getStatus() != Status.VALID && attempts-- > 0) {
|
||||
// Did the order fail?
|
||||
if (order.getStatus() == Status.INVALID) {
|
||||
throw new AcmeException("Order failed... Giving up.");
|
||||
}
|
||||
|
||||
// Wait for a few seconds
|
||||
Thread.sleep(3000L);
|
||||
|
||||
// Then update the status
|
||||
order.update();
|
||||
if (order.getStatus() != Status.VALID)
|
||||
LOG.info("Not yet...");
|
||||
}
|
||||
} catch (InterruptedException ex) {
|
||||
LOG.error("interrupted", ex);
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
|
||||
// Get the certificate
|
||||
Certificate certificate = order.getCertificate();
|
||||
|
||||
if (certificate == null)
|
||||
throw new AcmeException("Certificate is null. Wot.");
|
||||
// Now request a signed certificate.
|
||||
Certificate certificate = reg.requestCertificate(csrb.getEncoded());
|
||||
|
||||
LOG.info("Success! The certificate for domains " + domains + " has been generated!");
|
||||
LOG.info("Certificate URL: " + certificate.getLocation());
|
||||
LOG.info("Certificate URI: " + certificate.getLocation());
|
||||
|
||||
// Download the leaf certificate and certificate chain.
|
||||
X509Certificate cert = certificate.download();
|
||||
X509Certificate[] chain = certificate.downloadChain();
|
||||
|
||||
// Write a combined file containing the certificate and chain.
|
||||
try (FileWriter fw = new FileWriter(DOMAIN_CHAIN_FILE)) {
|
||||
certificate.writeCertificate(fw);
|
||||
CertificateUtils.writeX509CertificateChain(fw, cert, chain);
|
||||
}
|
||||
|
||||
// That's all! Configure your web server to use the DOMAIN_KEY_FILE and
|
||||
|
@ -157,34 +141,44 @@ public class AcmeClient {
|
|||
}
|
||||
|
||||
/**
|
||||
* Finds your {@link Account} at the ACME server. It will be found by your user's public key. If your key is not known to the server yet, a new registration will be created.
|
||||
* Finds your {@link Registration} at the ACME server. It will be found by your user's public key. If your key is not known to the server yet, a new registration will be created.
|
||||
* <p>
|
||||
* This is a simple way of finding your {@link Registration}. A better way is to get the URI of your new registration with {@link Registration#getLocation()} and store it somewhere. If you need to
|
||||
* get access to your account later, reconnect to it via {@link Registration#bind(Session, URI)} by using the stored location.
|
||||
*
|
||||
* @param session
|
||||
* {@link Session} to bind with
|
||||
* @param kp The user keypair
|
||||
* @return {@link Account} connected to your account
|
||||
* @return {@link Registration} connected to your account
|
||||
*/
|
||||
private Account findOrRegisterAccount(Session session, KeyPair kp) throws AcmeException, IOException {
|
||||
Account acc;
|
||||
private Registration findOrRegisterAccount(Session session) throws AcmeException, IOException {
|
||||
Registration reg;
|
||||
|
||||
URI loc = ButtonWebsiteModule.getRegistration();
|
||||
if (loc != null) {
|
||||
LOG.info("Loading account from file");
|
||||
return new Login(loc.toURL(), kp, session).getAccount();
|
||||
return Registration.bind(session, loc);
|
||||
}
|
||||
|
||||
// Try to create a new Registration.
|
||||
AccountBuilder ab = new AccountBuilder().useKeyPair(kp);
|
||||
try {
|
||||
// Try to create a new Registration.
|
||||
reg = new RegistrationBuilder().create(session);
|
||||
LOG.info("Registered a new user, URI: " + reg.getLocation());
|
||||
|
||||
// This is a new account. Let the user accept the Terms of Service.
|
||||
// We won't be able to authorize domains until the ToS is accepted.
|
||||
URI agreement = session.getMetadata().getTermsOfService();
|
||||
acceptAgreement(ab, agreement);
|
||||
acc = ab.create(session);
|
||||
LOG.info("Registered a new user, URI: " + acc.getLocation());
|
||||
ButtonWebsiteModule.storeRegistration(acc.getLocation());
|
||||
// This is a new account. Let the user accept the Terms of Service.
|
||||
// We won't be able to authorize domains until the ToS is accepted.
|
||||
URI agreement = reg.getAgreement();
|
||||
LOG.info("Terms of Service: " + agreement);
|
||||
acceptAgreement(reg, agreement);
|
||||
|
||||
return acc;
|
||||
} catch (AcmeConflictException ex) {
|
||||
// The Key Pair is already registered. getLocation() contains the
|
||||
// URL of the existing registration's location. Bind it to the session.
|
||||
reg = Registration.bind(session, ex.getLocation());
|
||||
LOG.info("Account does already exist, URI: " + reg.getLocation(), ex);
|
||||
ButtonWebsiteModule.storeRegistration(ex.getLocation());
|
||||
}
|
||||
|
||||
return reg;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -192,18 +186,18 @@ public class AcmeClient {
|
|||
* <p>
|
||||
* You need separate authorizations for subdomains (e.g. "www" subdomain). Wildcard certificates are not currently supported.
|
||||
*
|
||||
* @param auth
|
||||
* {@link Authorization} for the domain
|
||||
* @param reg
|
||||
* {@link Registration} of your account
|
||||
* @param domain
|
||||
* Name of the domain to authorize
|
||||
*/
|
||||
private void authorize(Authorization auth) throws AcmeException {
|
||||
LOG.info("Authorization for domain " + auth.getDomain());
|
||||
private void authorize(Registration reg, String domain) throws AcmeException {
|
||||
// Authorize the domain.
|
||||
Authorization auth = reg.authorizeDomain(domain);
|
||||
LOG.info("Authorization for domain " + domain);
|
||||
|
||||
// The authorization is already valid. No need to process a challenge.
|
||||
if (auth.getStatus() == Status.VALID) {
|
||||
return;
|
||||
}
|
||||
|
||||
Challenge challenge = httpChallenge(auth);
|
||||
// Find the desired challenge and prepare it.
|
||||
Challenge challenge = httpChallenge(auth, domain);
|
||||
|
||||
if (challenge == null) {
|
||||
throw new AcmeException("No challenge found");
|
||||
|
@ -239,7 +233,7 @@ public class AcmeClient {
|
|||
|
||||
// All reattempts are used up and there is still no valid authorization?
|
||||
if (challenge.getStatus() != Status.VALID) {
|
||||
throw new AcmeException("Failed to pass the challenge for domain " + auth.getDomain() + ", ... Giving up.");
|
||||
throw new AcmeException("Failed to pass the challenge for domain " + domain + ", ... Giving up.");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -253,16 +247,27 @@ public class AcmeClient {
|
|||
*
|
||||
* @param auth
|
||||
* {@link Authorization} to find the challenge in
|
||||
* @param domain
|
||||
* Domain name to be authorized
|
||||
* @return {@link Challenge} to verify
|
||||
*/
|
||||
public Challenge httpChallenge(Authorization auth) throws AcmeException {
|
||||
public Challenge httpChallenge(Authorization auth, String domain) throws AcmeException {
|
||||
// Find a single http-01 challenge
|
||||
Http01Challenge challenge = auth.findChallenge(Http01Challenge.TYPE);
|
||||
if (challenge == null) {
|
||||
throw new AcmeException("Found no " + Http01Challenge.TYPE + " challenge, don't know what to do...");
|
||||
}
|
||||
// if (ButtonWebsiteModule.PORT == 443)
|
||||
LOG.info("Storing the challenge data.");
|
||||
LOG.info("It should be reachable at: http://" + auth.getDomain() + "/.well-known/acme-challenge/" + challenge.getToken());
|
||||
/*
|
||||
* else LOG.info("Store the challenge data! Can't do automatically.");
|
||||
*/
|
||||
LOG.info("It should be reachable at: http://" + domain + "/.well-known/acme-challenge/" + challenge.getToken());
|
||||
// LOG.info("File name: " + challenge.getToken());
|
||||
// LOG.info("Content: " + challenge.getAuthorization());
|
||||
/*
|
||||
* LOG.info("Press any key to continue..."); if (ButtonWebsiteModule.PORT != 443) try { System.in.read(); } catch (IOException e) { e.printStackTrace(); }
|
||||
*/
|
||||
ButtonWebsiteModule.addHttpPage(new AcmeChallengePage(challenge.getToken(), challenge.getAuthorization()));
|
||||
ButtonWebsiteModule.startHttp();
|
||||
try {
|
||||
|
@ -275,13 +280,12 @@ public class AcmeClient {
|
|||
/**
|
||||
* Presents the user a link to the Terms of Service, and asks for confirmation. If the user denies confirmation, an exception is thrown.
|
||||
*
|
||||
* @param ab
|
||||
* {@link AccountBuilder} for the user
|
||||
* @param reg
|
||||
* {@link Registration} User's registration
|
||||
* @param agreement
|
||||
* {@link URI} of the Terms of Service
|
||||
*/
|
||||
public void acceptAgreement(AccountBuilder ab, URI agreement) throws AcmeException, IOException {
|
||||
LOG.info("Terms of Service: " + agreement);
|
||||
public void acceptAgreement(Registration reg, URI agreement) throws AcmeException, IOException {
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
|
||||
System.out.println("Do you accept the terms? (y/n)");
|
||||
if (br.readLine().equalsIgnoreCase("y\n")) {
|
||||
|
@ -289,7 +293,7 @@ public class AcmeClient {
|
|||
}
|
||||
|
||||
// Motify the Registration and accept the agreement
|
||||
ab.agreeToTermsOfService();
|
||||
reg.modify().setAgreement(agreement).commit();
|
||||
LOG.info("Updated user's ToS");
|
||||
}
|
||||
|
||||
|
|
|
@ -4,10 +4,7 @@ import buttondevteam.lib.TBMCCoreAPI;
|
|||
import buttondevteam.lib.chat.TBMCChatAPI;
|
||||
import buttondevteam.website.io.IOHelper;
|
||||
import buttondevteam.website.page.*;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import com.sun.net.httpserver.HttpsConfigurator;
|
||||
import com.sun.net.httpserver.HttpsParameters;
|
||||
import com.sun.net.httpserver.HttpsServer;
|
||||
import com.sun.net.httpserver.*;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
import org.bouncycastle.openssl.PEMKeyPair;
|
||||
import org.bouncycastle.openssl.PEMParser;
|
||||
|
@ -17,7 +14,10 @@ import org.bukkit.plugin.java.JavaPlugin;
|
|||
|
||||
import javax.net.ssl.*;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyStore;
|
||||
import java.security.PrivateKey;
|
||||
|
@ -30,25 +30,23 @@ import java.util.concurrent.ThreadPoolExecutor;
|
|||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class ButtonWebsiteModule extends JavaPlugin {
|
||||
public static final int PORT = 443;
|
||||
private static HttpsServer server;
|
||||
/**
|
||||
* For ACME validation and user redirection
|
||||
*/
|
||||
private static HttpServer httpserver;
|
||||
private static boolean enabled;
|
||||
|
||||
public ButtonWebsiteModule() {
|
||||
try {
|
||||
int ps = getConfig().getInt("https-port", 443);
|
||||
int p = getConfig().getInt("http-port", 80);
|
||||
server = HttpsServer.create(new InetSocketAddress((InetAddress) null, ps), 10);
|
||||
httpserver = HttpServer.create(new InetSocketAddress((InetAddress) null, p), 10);
|
||||
server = HttpsServer.create(new InetSocketAddress((InetAddress) null, PORT), 10);
|
||||
httpserver = HttpServer.create(new InetSocketAddress((InetAddress) null, 80), 10);
|
||||
SSLContext sslContext = SSLContext.getInstance("TLS");
|
||||
|
||||
// initialise the keystore
|
||||
char[] password = "password".toCharArray();
|
||||
KeyStore ks = KeyStore.getInstance("JKS");
|
||||
File certfile = AcmeClient.DOMAIN_CHAIN_FILE; /* your cert path */
|
||||
String certfile = "domain-chain.crt"; /* your cert path */
|
||||
File keystoreFile = new File("keystore.keystore");
|
||||
|
||||
ks.load(keystoreFile.exists() ? new FileInputStream(keystoreFile) : null, password);
|
||||
|
@ -59,9 +57,9 @@ public class ButtonWebsiteModule extends JavaPlugin {
|
|||
|
||||
CertificateFactory cf = CertificateFactory.getInstance("X.509");
|
||||
InputStream certstream = fullStream(certfile);
|
||||
Certificate[] certs = cf.generateCertificates(certstream).toArray(new Certificate[0]);
|
||||
Certificate[] certs = cf.generateCertificates(certstream).stream().toArray(Certificate[]::new);
|
||||
|
||||
BufferedReader br = new BufferedReader(new FileReader(AcmeClient.DOMAIN_KEY_FILE));
|
||||
BufferedReader br = new BufferedReader(new FileReader("domain.key"));
|
||||
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
|
||||
|
@ -108,19 +106,14 @@ public class ButtonWebsiteModule extends JavaPlugin {
|
|||
}
|
||||
}
|
||||
});
|
||||
enabled = true;
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("An error occurred while starting the webserver!", e);
|
||||
enabled = false; //It's not even enabled yet, so we need a variable
|
||||
TBMCCoreAPI.SendException("An error occured while starting the webserver!", e);
|
||||
getServer().getPluginManager().disablePlugin(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
if (!enabled) {
|
||||
getServer().getPluginManager().disablePlugin(this);
|
||||
return;
|
||||
}
|
||||
addPage(new IndexPage());
|
||||
addPage(new LoginPage());
|
||||
addPage(new ProfilePage());
|
||||
|
@ -131,10 +124,15 @@ public class ButtonWebsiteModule extends JavaPlugin {
|
|||
Bukkit.getScheduler().runTaskAsynchronously(this, () -> {
|
||||
this.getLogger().info("Starting webserver...");
|
||||
server.setExecutor(
|
||||
new ThreadPoolExecutor(4, 8, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100)));
|
||||
httpserver.createContext("/", exchange -> IOHelper.SendResponse(IOHelper.Redirect("https://server.figytuna.com/", exchange)));
|
||||
new ThreadPoolExecutor(4, 8, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100)));
|
||||
httpserver.createContext("/", new HttpHandler() {
|
||||
@Override
|
||||
public void handle(HttpExchange exchange) throws IOException {
|
||||
IOHelper.SendResponse(IOHelper.Redirect("https://server.figytuna.com/", exchange));
|
||||
}
|
||||
});
|
||||
final Calendar calendar = Calendar.getInstance();
|
||||
if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY && !TBMCCoreAPI.IsTestServer()) { // Only update every week
|
||||
if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY && !TBMCCoreAPI.IsTestServer()) { // Only update every week
|
||||
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
|
||||
AcmeClient.main("server.figytuna.com"); // Task is running async so we don't need an extra thread
|
||||
}
|
||||
|
@ -159,8 +157,6 @@ public class ButtonWebsiteModule extends JavaPlugin {
|
|||
* Adds a new page/endpoint to the website. This method needs to be called before the server finishes loading (onEnable).
|
||||
*/
|
||||
public static void addPage(Page page) {
|
||||
if (!enabled)
|
||||
return;
|
||||
server.createContext("/" + page.GetName(), page);
|
||||
}
|
||||
|
||||
|
@ -168,12 +164,10 @@ public class ButtonWebsiteModule extends JavaPlugin {
|
|||
* Adds an <b>insecure</b> endpoint to the website. This should be avoided when possible.
|
||||
*/
|
||||
public static void addHttpPage(Page page) {
|
||||
if (!enabled)
|
||||
return;
|
||||
httpserver.createContext("/" + page.GetName(), page);
|
||||
}
|
||||
|
||||
static void storeRegistration(URL location) {
|
||||
static void storeRegistration(URI location) {
|
||||
final ButtonWebsiteModule plugin = getPlugin(ButtonWebsiteModule.class);
|
||||
plugin.getConfig().set("registration", location.toString());
|
||||
plugin.saveConfig();
|
||||
|
@ -189,12 +183,13 @@ public class ButtonWebsiteModule extends JavaPlugin {
|
|||
}
|
||||
}
|
||||
|
||||
private static InputStream fullStream(File f) throws IOException {
|
||||
FileInputStream fis = new FileInputStream(f);
|
||||
private static InputStream fullStream(String fname) throws IOException {
|
||||
FileInputStream fis = new FileInputStream(fname);
|
||||
DataInputStream dis = new DataInputStream(fis);
|
||||
byte[] bytes = new byte[dis.available()];
|
||||
dis.readFully(bytes);
|
||||
dis.close();
|
||||
return new ByteArrayInputStream(bytes);
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
|
||||
return bais;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -21,7 +21,7 @@ public class LoginCommand extends PlayerCommandBase {
|
|||
"§6---- Login ----", //
|
||||
"This command allows you to log in to our website using your Minecraft account.", //
|
||||
"If you are already logged in to the site, you can connect your MC account to it.", //
|
||||
"This is good for getting Minecraft rewards if you're a patron for example." //
|
||||
"This is good for getting Minecraft rewards if you're a patreon for example." //
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,11 +1,11 @@
|
|||
package buttondevteam.website;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import buttondevteam.lib.player.ChromaGamerBase;
|
||||
import buttondevteam.lib.player.PlayerData;
|
||||
import buttondevteam.lib.player.UserClass;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@UserClass(foldername = "web")
|
||||
public class WebUser extends ChromaGamerBase {
|
||||
private UUID uuid;
|
||||
|
@ -16,7 +16,7 @@ public class WebUser extends ChromaGamerBase {
|
|||
return uuid;
|
||||
}
|
||||
|
||||
public PlayerData<UUID> sessionID() {
|
||||
return data(new UUID(0, 0)); //It's used with toString() directly, so can't be null
|
||||
public PlayerData<String> sessionID() {
|
||||
return data(null);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -33,8 +33,8 @@ public class Cookies extends HashMap<String, Cookie> {
|
|||
public void AddHeaders(HttpExchange exchange) {
|
||||
for (Entry<String, Cookie> item : entrySet())
|
||||
exchange.getResponseHeaders().add("Set-Cookie",
|
||||
item.getKey() + "=" + item.getValue().getValue() + "; expires=" + expiretime + "; Secure; HttpOnly; Domain=figytuna.com"); //Allow for frontend
|
||||
exchange.getResponseHeaders().add("Set-Cookie", "expiretime=" + expiretime + "; expires=" + expiretime + "; Secure; HttpOnly; Domain=figytuna.com");
|
||||
item.getKey() + "=" + item.getValue().getValue() + "; expires=" + expiretime + "; Domain=figytuna.com"); //chromagaming.figytuna.com too (commented so that I can find it later) - server.figytuna.com
|
||||
exchange.getResponseHeaders().add("Set-Cookie", "expiretime=" + expiretime + "; expires=" + expiretime + "; Domain=figytuna.com"); //TODO: Fix header stuff
|
||||
}
|
||||
|
||||
public Cookies add(Cookie cookie) {
|
||||
|
|
|
@ -31,8 +31,8 @@ public class IOHelper {
|
|||
|
||||
public static void SendResponse(int code, String content, HttpExchange exchange) throws IOException {
|
||||
if (exchange.getRequestMethod().equalsIgnoreCase("HEAD")) {
|
||||
exchange.sendResponseHeaders(200, -1); // -1 indicates no data
|
||||
//exchange.getResponseBody().close(); - No stream is created for HEAD requests
|
||||
exchange.sendResponseHeaders(code, -1); // -1 indicates no data
|
||||
exchange.getResponseBody().close(); //TODO: Response headers not sent yet <--
|
||||
return;
|
||||
}
|
||||
try (BufferedOutputStream out = new BufferedOutputStream(exchange.getResponseBody())) {
|
||||
|
@ -57,7 +57,8 @@ public class IOHelper {
|
|||
try {
|
||||
if (exchange.getRequestBody().available() == 0)
|
||||
return "";
|
||||
return IOUtils.toString(exchange.getRequestBody(), "UTF-8");
|
||||
String content = IOUtils.toString(exchange.getRequestBody(), "UTF-8");
|
||||
return content;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return "";
|
||||
|
@ -72,7 +73,8 @@ public class IOHelper {
|
|||
JsonElement e = new JsonParser().parse(content);
|
||||
if (e == null)
|
||||
return null;
|
||||
return e.getAsJsonObject();
|
||||
JsonObject obj = e.getAsJsonObject();
|
||||
return obj;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
|
@ -84,15 +86,15 @@ public class IOHelper {
|
|||
*/
|
||||
public static void LoginUser(HttpExchange exchange, WebUser user) {
|
||||
Bukkit.getLogger().fine("Logging in user: " + user);
|
||||
user.sessionID().set(UUID.randomUUID());
|
||||
user.sessionID().set(UUID.randomUUID().toString());
|
||||
user.save();
|
||||
new Cookies(2).add(new Cookie("user_id", user.getUUID() + ""))
|
||||
.add(new Cookie("session_id", user.sessionID().get().toString())).AddHeaders(exchange);
|
||||
.add(new Cookie("session_id", user.sessionID().get())).AddHeaders(exchange);
|
||||
Bukkit.getLogger().fine("Logged in user.");
|
||||
}
|
||||
|
||||
public static void LogoutUser(HttpExchange exchange, WebUser user) {
|
||||
user.sessionID().set(new UUID(0, 0));
|
||||
user.sessionID().set(null);
|
||||
user.save();
|
||||
SendLogoutHeaders(exchange);
|
||||
}
|
||||
|
@ -103,7 +105,7 @@ public class IOHelper {
|
|||
.AddHeaders(exchange);
|
||||
}
|
||||
|
||||
public static Response Redirect(String url, HttpExchange exchange) {
|
||||
public static Response Redirect(String url, HttpExchange exchange) throws IOException {
|
||||
exchange.getResponseHeaders().add("Location", url);
|
||||
return new Response(303, "<a href=\"" + url + "\">If you can see this, click here to continue</a>", exchange);
|
||||
}
|
||||
|
@ -113,9 +115,9 @@ public class IOHelper {
|
|||
return new Cookies();
|
||||
Map<String, String> map = new HashMap<>();
|
||||
for (String cheader : exchange.getRequestHeaders().get("Cookie")) {
|
||||
String[] spl = cheader.split(";\\s*");
|
||||
String[] spl = cheader.split("\\;\\s*");
|
||||
for (String s : spl) {
|
||||
String[] kv = s.split("=");
|
||||
String[] kv = s.split("\\=");
|
||||
if (kv.length < 2)
|
||||
continue;
|
||||
map.put(kv[0], kv[1]);
|
||||
|
@ -123,7 +125,7 @@ public class IOHelper {
|
|||
}
|
||||
if (!map.containsKey("expiretime"))
|
||||
return new Cookies();
|
||||
Cookies cookies;
|
||||
Cookies cookies = null;
|
||||
try {
|
||||
cookies = new Cookies(map.get("expiretime"));
|
||||
for (Entry<String, String> item : map.entrySet())
|
||||
|
@ -137,17 +139,18 @@ public class IOHelper {
|
|||
|
||||
/**
|
||||
* Get logged in user. It may also send logout headers if the cookies are invalid, or login headers to keep the user logged in. <b>Make sure to save the user data.</b>
|
||||
*
|
||||
* @param exchange The exchange
|
||||
*
|
||||
* @param exchange
|
||||
* @return The logged in user or null if not logged in.
|
||||
* @throws IOException
|
||||
*/
|
||||
public static WebUser GetLoggedInUser(HttpExchange exchange) {
|
||||
public static WebUser GetLoggedInUser(HttpExchange exchange) throws IOException {
|
||||
Cookies cookies = GetCookies(exchange);
|
||||
if (!cookies.containsKey("user_id") || !cookies.containsKey("session_id"))
|
||||
return null;
|
||||
WebUser user = ChromaGamerBase.getUser(cookies.get("user_id").getValue(), WebUser.class);
|
||||
if (user != null && cookies.get("session_id") != null
|
||||
&& cookies.get("session_id").getValue().equals(user.sessionID().get().toString())) {
|
||||
&& cookies.get("session_id").getValue().equals(user.sessionID().get())) {
|
||||
if (cookies.getExpireTimeParsed().minusYears(1).isBefore(ZonedDateTime.now(ZoneId.of("GMT"))))
|
||||
LoginUser(exchange, user);
|
||||
return user;
|
||||
|
@ -187,10 +190,10 @@ public class IOHelper {
|
|||
|
||||
public static HashMap<String, String> GetPOSTKeyValues(HttpExchange exchange) {
|
||||
try {
|
||||
String[] content = GetPOST(exchange).split("&");
|
||||
String[] content = GetPOST(exchange).split("\\&");
|
||||
HashMap<String, String> vars = new HashMap<>();
|
||||
for (String var : content) {
|
||||
String[] spl = var.split("=");
|
||||
String[] spl = var.split("\\=");
|
||||
if (spl.length == 1)
|
||||
vars.put(spl[0], "");
|
||||
else
|
||||
|
|
|
@ -3,9 +3,9 @@ package buttondevteam.website.io;
|
|||
import com.sun.net.httpserver.HttpExchange;
|
||||
|
||||
public class Response {
|
||||
public final int code;
|
||||
public final String content;
|
||||
public final HttpExchange exchange;
|
||||
public int code;
|
||||
public String content;
|
||||
public HttpExchange exchange;
|
||||
|
||||
public Response(int code, String content, HttpExchange exchange) {
|
||||
this.code = code;
|
||||
|
|
|
@ -1,9 +1,5 @@
|
|||
package buttondevteam.website.page;
|
||||
|
||||
import buttondevteam.website.io.Response;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
@ -12,8 +8,15 @@ import java.net.SocketException;
|
|||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
|
||||
import buttondevteam.website.io.Response;
|
||||
|
||||
public class BridgePage extends Page {
|
||||
private final Map<String, Socket> connections = new HashMap<>();
|
||||
private Map<String, Socket> connections = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public String GetName() {
|
||||
|
@ -53,14 +56,9 @@ public class BridgePage extends Page {
|
|||
return new Response(400, "No connection", exchange);
|
||||
if (s.isClosed())
|
||||
return new Response(410, "Socket Gone", exchange);
|
||||
try {
|
||||
exchange.sendResponseHeaders(200, 0); // Chunked transfer, any amount of data
|
||||
copyStream(s.getInputStream(), exchange.getResponseBody());
|
||||
exchange.getResponseBody().close(); // It'll only get here when the communication is already done
|
||||
} catch (IOException ex) { //Failed to send it over HTTP, GET connection closed
|
||||
closeSocket(exchange); //We only have one GET, connection over
|
||||
System.out.println("[BWM] [" + id + "] over (GET): " + ex.toString());
|
||||
}
|
||||
exchange.sendResponseHeaders(200, 0); // Chunked transfer, any amount of data
|
||||
copyStream(s.getInputStream(), exchange.getResponseBody());
|
||||
exchange.getResponseBody().close(); // It'll only get here when the communication is already done
|
||||
return null; // Response already sent
|
||||
case "DELETE":
|
||||
System.out.println("[BWM] [" + id + "] delet this");
|
||||
|
@ -70,13 +68,7 @@ public class BridgePage extends Page {
|
|||
return new Response(403, "Unknown request", exchange);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
if (e instanceof SocketException) {
|
||||
closeSocket(exchange);
|
||||
System.out.println("[BWM] [" + id + "] closed: " + e.toString());
|
||||
return new Response(410, "Socket Gone because of error: " + e, exchange);
|
||||
}
|
||||
e.printStackTrace();
|
||||
return new Response(500, "Internal Server Error: " + e, exchange);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -103,22 +95,26 @@ public class BridgePage extends Page {
|
|||
return;
|
||||
try {
|
||||
socket.close();
|
||||
} catch (IOException ignored) {
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
connections.values().remove(socket);
|
||||
}
|
||||
|
||||
private void copyStream(InputStream is, OutputStream os) throws IOException { // Based on IOUtils.copy()
|
||||
private int copyStream(InputStream is, OutputStream os) throws IOException { // Based on IOUtils.copy()
|
||||
byte[] buffer = new byte[4096];
|
||||
int n;
|
||||
long count = 0;
|
||||
int n = 0;
|
||||
try {
|
||||
while (-1 != (n = is.read(buffer))) { // Read is blocking
|
||||
os.write(buffer, 0, n);
|
||||
count += n;
|
||||
os.flush();
|
||||
}
|
||||
} catch (SocketException e) { // Conection closed
|
||||
os.flush();
|
||||
}
|
||||
return (int) count;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -1,16 +1,5 @@
|
|||
package buttondevteam.website.page;
|
||||
|
||||
import buttondevteam.core.component.updater.PluginUpdater;
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.website.io.IOHelper;
|
||||
import buttondevteam.website.io.Response;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.PublicKey;
|
||||
|
@ -21,6 +10,16 @@ import java.util.HashMap;
|
|||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
|
||||
import buttondevteam.lib.PluginUpdater;
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.website.io.IOHelper;
|
||||
import buttondevteam.website.io.Response;
|
||||
|
||||
public class BuildNotificationsPage extends Page {
|
||||
|
||||
@Override
|
||||
|
@ -32,11 +31,8 @@ public class BuildNotificationsPage extends Page {
|
|||
|
||||
private static final String publickey = ((Supplier<String>) () -> {
|
||||
try {
|
||||
JsonElement pubkey = fromString(TBMCCoreAPI.DownloadString("https://api.travis-ci.org/config"),
|
||||
"config.notifications.webhook.public_key");
|
||||
if (pubkey == null)
|
||||
return null;
|
||||
return pubkey.getAsString().replace("-----BEGIN PUBLIC KEY-----", "")
|
||||
return fromString(TBMCCoreAPI.DownloadString("https://api.travis-ci.org/config"),
|
||||
"config.notifications.webhook.public_key").getAsString().replace("-----BEGIN PUBLIC KEY-----", "")
|
||||
.replaceAll("\n", "").replace("-----END PUBLIC KEY-----", "");
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
|
@ -51,7 +47,7 @@ public class BuildNotificationsPage extends Page {
|
|||
final String payload = post.get("payload");
|
||||
if (signatures != null && signatures.size() > 0 && post.containsKey("payload")
|
||||
&& verifySignature(payload.getBytes(StandardCharsets.UTF_8),
|
||||
Base64.getDecoder().decode(signatures.get(0)))) {
|
||||
Base64.getDecoder().decode(signatures.get(0)), publickey)) {
|
||||
Bukkit.getPluginManager()
|
||||
.callEvent(new PluginUpdater.UpdatedEvent(gson.fromJson(payload, JsonObject.class)));
|
||||
return new Response(200, "All right", exchange);
|
||||
|
@ -65,9 +61,9 @@ public class BuildNotificationsPage extends Page {
|
|||
|
||||
// Method for signature verification that initializes with the Public Key,
|
||||
// updates the data to be verified and then verifies them using the signature
|
||||
private boolean verifySignature(byte[] data, byte[] signature) throws Exception {
|
||||
private boolean verifySignature(byte[] data, byte[] signature, String keystr) throws Exception {
|
||||
Signature sig = Signature.getInstance("SHA1withRSA");
|
||||
sig.initVerify(getPublic(BuildNotificationsPage.publickey));
|
||||
sig.initVerify(getPublic(keystr));
|
||||
sig.update(data);
|
||||
|
||||
return sig.verify(signature);
|
||||
|
|
|
@ -7,6 +7,7 @@ import buttondevteam.website.io.Response;
|
|||
import com.google.common.collect.HashBiMap;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
|
@ -42,7 +43,11 @@ public class LoginPage extends Page {
|
|||
cp.connectWith(wu = WebUser.getUser(UUID.randomUUID().toString(), WebUser.class)); //Create new user with random UUID
|
||||
IOHelper.LoginUser(exchange, wu);
|
||||
states.remove(state);
|
||||
return IOHelper.Redirect("https://chromagaming.figytuna.com/", exchange);
|
||||
try {
|
||||
return IOHelper.Redirect("https://tbmcplugins.github.io/", exchange);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
} else return new Response(418, "Now what", exchange); //Minecraft doesn't have full OAuth
|
||||
}
|
||||
return new Response(400, "Wut", exchange);
|
||||
|
|
|
@ -1,16 +1,16 @@
|
|||
package buttondevteam.website.page;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import org.apache.commons.io.output.ByteArrayOutputStream;
|
||||
|
||||
import com.sun.net.httpserver.*;
|
||||
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.website.io.IOHelper;
|
||||
import buttondevteam.website.io.Response;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpHandler;
|
||||
import org.apache.commons.io.output.ByteArrayOutputStream;
|
||||
|
||||
import java.io.PrintStream;
|
||||
|
||||
/**
|
||||
* Add using {@link buttondevteam.website.ButtonWebsiteModule#addPage(Page)}
|
||||
* Add to {@link Main}.Pages
|
||||
*/
|
||||
public abstract class Page implements HttpHandler {
|
||||
public abstract String GetName();
|
||||
|
@ -18,8 +18,8 @@ public abstract class Page implements HttpHandler {
|
|||
@Override
|
||||
public final void handle(HttpExchange exchange) {
|
||||
try {
|
||||
exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "https://chromagaming.figytuna.com");
|
||||
if (!exactPage() || exchange.getRequestURI().getPath().equals("/" + GetName()))
|
||||
exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "https://tbmcplugins.github.io");
|
||||
if (exactPage() ? exchange.getRequestURI().getPath().equals("/" + GetName()) : true)
|
||||
IOHelper.SendResponse(handlePage(exchange));
|
||||
else {
|
||||
IOHelper.SendResponse(404, "404 Not found: " + exchange.getRequestURI().getPath(), exchange);
|
||||
|
@ -46,8 +46,8 @@ public abstract class Page implements HttpHandler {
|
|||
|
||||
/**
|
||||
* Whether to return 404 when the URL doesn't match the exact path
|
||||
*
|
||||
* @return Whether it should only match the page path
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public boolean exactPage() {
|
||||
return true;
|
||||
|
|
Loading…
Reference in a new issue