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
|
*.publishproj
|
||||||
|
|
||||||
# NuGet Packages Directory
|
# 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/
|
#packages/
|
||||||
|
|
||||||
# Windows Azure Build Output
|
# Windows Azure Build Output
|
||||||
|
|
|
@ -3,7 +3,7 @@ main: buttondevteam.website.ButtonWebsiteModule
|
||||||
version: 4.0
|
version: 4.0
|
||||||
author: NorbiPeti
|
author: NorbiPeti
|
||||||
depend:
|
depend:
|
||||||
- ThorpeCore
|
- ButtonCore
|
||||||
commands:
|
commands:
|
||||||
login:
|
login:
|
||||||
aliases: [web, weblogin, website]
|
aliases: [web, weblogin, website]
|
32
pom.xml
32
pom.xml
|
@ -45,6 +45,11 @@
|
||||||
<!-- <artifactSet> <includes> <include>org.shredzone.acme4j:acme4j-client</include>
|
<!-- <artifactSet> <includes> <include>org.shredzone.acme4j:acme4j-client</include>
|
||||||
<include>org.shredzone.acme4j:acme4j-utils</include> <include>org.bouncycastle:bcprov-jdk15on</include>
|
<include>org.shredzone.acme4j:acme4j-utils</include> <include>org.bouncycastle:bcprov-jdk15on</include>
|
||||||
</includes> </artifactSet> -->
|
</includes> </artifactSet> -->
|
||||||
|
<pluginExecution>
|
||||||
|
<action>
|
||||||
|
<execute />
|
||||||
|
</action>
|
||||||
|
</pluginExecution>
|
||||||
<filters>
|
<filters>
|
||||||
<filter>
|
<filter>
|
||||||
<artifact>*:*</artifact>
|
<artifact>*:*</artifact>
|
||||||
|
@ -63,9 +68,6 @@
|
||||||
</build>
|
</build>
|
||||||
<properties>
|
<properties>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<branch>
|
|
||||||
master
|
|
||||||
</branch>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<repositories>
|
<repositories>
|
||||||
|
@ -121,40 +123,24 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.github.TBMCPlugins.ButtonCore</groupId>
|
<groupId>com.github.TBMCPlugins.ButtonCore</groupId>
|
||||||
<artifactId>ButtonCore</artifactId>
|
<artifactId>ButtonCore</artifactId>
|
||||||
<version>${branch}-SNAPSHOT</version>
|
<version>master-SNAPSHOT</version>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- https://mvnrepository.com/artifact/org.shredzone.acme4j/acme4j-client -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.shredzone.acme4j</groupId>
|
<groupId>org.shredzone.acme4j</groupId>
|
||||||
<artifactId>acme4j-client</artifactId>
|
<artifactId>acme4j-client</artifactId>
|
||||||
<version>2.1</version>
|
<version>0.10</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.shredzone.acme4j</groupId>
|
<groupId>org.shredzone.acme4j</groupId>
|
||||||
<artifactId>acme4j-utils</artifactId>
|
<artifactId>acme4j-utils</artifactId>
|
||||||
<version>2.1</version>
|
<version>0.10</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on -->
|
<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.bouncycastle</groupId>
|
<groupId>org.bouncycastle</groupId>
|
||||||
<artifactId>bcprov-jdk15on</artifactId>
|
<artifactId>bcprov-jdk15on</artifactId>
|
||||||
<version>1.60</version>
|
<version>1.57</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</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>
|
</project>
|
||||||
|
|
|
@ -13,22 +13,32 @@
|
||||||
*/ //Modified
|
*/ //Modified
|
||||||
package buttondevteam.website;
|
package buttondevteam.website;
|
||||||
|
|
||||||
import buttondevteam.lib.TBMCCoreAPI;
|
import java.io.BufferedReader;
|
||||||
import buttondevteam.website.page.AcmeChallengePage;
|
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.*;
|
||||||
import org.shredzone.acme4j.challenge.Challenge;
|
import org.shredzone.acme4j.challenge.Challenge;
|
||||||
import org.shredzone.acme4j.challenge.Http01Challenge;
|
import org.shredzone.acme4j.challenge.Http01Challenge;
|
||||||
|
import org.shredzone.acme4j.exception.AcmeConflictException;
|
||||||
import org.shredzone.acme4j.exception.AcmeException;
|
import org.shredzone.acme4j.exception.AcmeException;
|
||||||
import org.shredzone.acme4j.util.CSRBuilder;
|
import org.shredzone.acme4j.util.CSRBuilder;
|
||||||
|
import org.shredzone.acme4j.util.CertificateUtils;
|
||||||
import org.shredzone.acme4j.util.KeyPairUtils;
|
import org.shredzone.acme4j.util.KeyPairUtils;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.io.*;
|
import buttondevteam.lib.TBMCCoreAPI;
|
||||||
import java.net.URI;
|
import buttondevteam.website.page.AcmeChallengePage;
|
||||||
import java.security.KeyPair;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Collection;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A simple client test tool.
|
* A simple client test tool.
|
||||||
|
@ -37,16 +47,16 @@ import java.util.Collection;
|
||||||
*/
|
*/
|
||||||
public class AcmeClient {
|
public class AcmeClient {
|
||||||
// File name of the User Key Pair
|
// 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
|
// 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
|
// 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
|
// 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
|
// RSA key size of generated key pairs
|
||||||
private static final int KEY_SIZE = 2048;
|
private static final int KEY_SIZE = 2048;
|
||||||
|
@ -67,17 +77,16 @@ public class AcmeClient {
|
||||||
|
|
||||||
// Create a session for Let's Encrypt.
|
// Create a session for Let's Encrypt.
|
||||||
// Use "acme://letsencrypt.org" for production server
|
// 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.
|
// Get the Registration to the account.
|
||||||
// If there is no account yet, create a new one.
|
// If there is no account yet, create a new one.
|
||||||
Account acc = findOrRegisterAccount(session, userKeyPair);
|
Registration reg = findOrRegisterAccount(session);
|
||||||
|
|
||||||
Order order = acc.newOrder().domains(domains).create();
|
|
||||||
|
|
||||||
// Separately authorize every requested domain.
|
// Separately authorize every requested domain.
|
||||||
for (Authorization auth : order.getAuthorizations()) {
|
for (String domain : domains) {
|
||||||
authorize(auth);
|
authorize(reg, domain);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load or create a key pair for the domains. This should not be the userKeyPair!
|
// 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);
|
csrb.write(out);
|
||||||
}
|
}
|
||||||
|
|
||||||
LOG.info("Ordering certificate...");
|
// Now request a signed certificate.
|
||||||
// Order the certificate
|
Certificate certificate = reg.requestCertificate(csrb.getEncoded());
|
||||||
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.");
|
|
||||||
|
|
||||||
LOG.info("Success! The certificate for domains " + domains + " has been generated!");
|
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.
|
// Write a combined file containing the certificate and chain.
|
||||||
try (FileWriter fw = new FileWriter(DOMAIN_CHAIN_FILE)) {
|
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
|
// 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
|
* @param session
|
||||||
* {@link Session} to bind with
|
* {@link Session} to bind with
|
||||||
* @param kp The user keypair
|
* @return {@link Registration} connected to your account
|
||||||
* @return {@link Account} connected to your account
|
|
||||||
*/
|
*/
|
||||||
private Account findOrRegisterAccount(Session session, KeyPair kp) throws AcmeException, IOException {
|
private Registration findOrRegisterAccount(Session session) throws AcmeException, IOException {
|
||||||
Account acc;
|
Registration reg;
|
||||||
|
|
||||||
URI loc = ButtonWebsiteModule.getRegistration();
|
URI loc = ButtonWebsiteModule.getRegistration();
|
||||||
if (loc != null) {
|
if (loc != null) {
|
||||||
LOG.info("Loading account from file");
|
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.
|
try {
|
||||||
AccountBuilder ab = new AccountBuilder().useKeyPair(kp);
|
// 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.
|
// 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.
|
// We won't be able to authorize domains until the ToS is accepted.
|
||||||
URI agreement = session.getMetadata().getTermsOfService();
|
URI agreement = reg.getAgreement();
|
||||||
acceptAgreement(ab, agreement);
|
LOG.info("Terms of Service: " + agreement);
|
||||||
acc = ab.create(session);
|
acceptAgreement(reg, agreement);
|
||||||
LOG.info("Registered a new user, URI: " + acc.getLocation());
|
|
||||||
ButtonWebsiteModule.storeRegistration(acc.getLocation());
|
|
||||||
|
|
||||||
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>
|
* <p>
|
||||||
* You need separate authorizations for subdomains (e.g. "www" subdomain). Wildcard certificates are not currently supported.
|
* You need separate authorizations for subdomains (e.g. "www" subdomain). Wildcard certificates are not currently supported.
|
||||||
*
|
*
|
||||||
* @param auth
|
* @param reg
|
||||||
* {@link Authorization} for the domain
|
* {@link Registration} of your account
|
||||||
|
* @param domain
|
||||||
|
* Name of the domain to authorize
|
||||||
*/
|
*/
|
||||||
private void authorize(Authorization auth) throws AcmeException {
|
private void authorize(Registration reg, String domain) throws AcmeException {
|
||||||
LOG.info("Authorization for domain " + auth.getDomain());
|
// 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.
|
// Find the desired challenge and prepare it.
|
||||||
if (auth.getStatus() == Status.VALID) {
|
Challenge challenge = httpChallenge(auth, domain);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Challenge challenge = httpChallenge(auth);
|
|
||||||
|
|
||||||
if (challenge == null) {
|
if (challenge == null) {
|
||||||
throw new AcmeException("No challenge found");
|
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?
|
// All reattempts are used up and there is still no valid authorization?
|
||||||
if (challenge.getStatus() != Status.VALID) {
|
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
|
* @param auth
|
||||||
* {@link Authorization} to find the challenge in
|
* {@link Authorization} to find the challenge in
|
||||||
|
* @param domain
|
||||||
|
* Domain name to be authorized
|
||||||
* @return {@link Challenge} to verify
|
* @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
|
// Find a single http-01 challenge
|
||||||
Http01Challenge challenge = auth.findChallenge(Http01Challenge.TYPE);
|
Http01Challenge challenge = auth.findChallenge(Http01Challenge.TYPE);
|
||||||
if (challenge == null) {
|
if (challenge == null) {
|
||||||
throw new AcmeException("Found no " + Http01Challenge.TYPE + " challenge, don't know what to do...");
|
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("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.addHttpPage(new AcmeChallengePage(challenge.getToken(), challenge.getAuthorization()));
|
||||||
ButtonWebsiteModule.startHttp();
|
ButtonWebsiteModule.startHttp();
|
||||||
try {
|
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.
|
* 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
|
* @param reg
|
||||||
* {@link AccountBuilder} for the user
|
* {@link Registration} User's registration
|
||||||
* @param agreement
|
* @param agreement
|
||||||
* {@link URI} of the Terms of Service
|
* {@link URI} of the Terms of Service
|
||||||
*/
|
*/
|
||||||
public void acceptAgreement(AccountBuilder ab, URI agreement) throws AcmeException, IOException {
|
public void acceptAgreement(Registration reg, URI agreement) throws AcmeException, IOException {
|
||||||
LOG.info("Terms of Service: " + agreement);
|
|
||||||
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
|
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
|
||||||
System.out.println("Do you accept the terms? (y/n)");
|
System.out.println("Do you accept the terms? (y/n)");
|
||||||
if (br.readLine().equalsIgnoreCase("y\n")) {
|
if (br.readLine().equalsIgnoreCase("y\n")) {
|
||||||
|
@ -289,7 +293,7 @@ public class AcmeClient {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Motify the Registration and accept the agreement
|
// Motify the Registration and accept the agreement
|
||||||
ab.agreeToTermsOfService();
|
reg.modify().setAgreement(agreement).commit();
|
||||||
LOG.info("Updated user's ToS");
|
LOG.info("Updated user's ToS");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -4,10 +4,7 @@ import buttondevteam.lib.TBMCCoreAPI;
|
||||||
import buttondevteam.lib.chat.TBMCChatAPI;
|
import buttondevteam.lib.chat.TBMCChatAPI;
|
||||||
import buttondevteam.website.io.IOHelper;
|
import buttondevteam.website.io.IOHelper;
|
||||||
import buttondevteam.website.page.*;
|
import buttondevteam.website.page.*;
|
||||||
import com.sun.net.httpserver.HttpServer;
|
import com.sun.net.httpserver.*;
|
||||||
import com.sun.net.httpserver.HttpsConfigurator;
|
|
||||||
import com.sun.net.httpserver.HttpsParameters;
|
|
||||||
import com.sun.net.httpserver.HttpsServer;
|
|
||||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||||
import org.bouncycastle.openssl.PEMKeyPair;
|
import org.bouncycastle.openssl.PEMKeyPair;
|
||||||
import org.bouncycastle.openssl.PEMParser;
|
import org.bouncycastle.openssl.PEMParser;
|
||||||
|
@ -17,7 +14,10 @@ import org.bukkit.plugin.java.JavaPlugin;
|
||||||
|
|
||||||
import javax.net.ssl.*;
|
import javax.net.ssl.*;
|
||||||
import java.io.*;
|
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.KeyPair;
|
||||||
import java.security.KeyStore;
|
import java.security.KeyStore;
|
||||||
import java.security.PrivateKey;
|
import java.security.PrivateKey;
|
||||||
|
@ -30,25 +30,23 @@ import java.util.concurrent.ThreadPoolExecutor;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
public class ButtonWebsiteModule extends JavaPlugin {
|
public class ButtonWebsiteModule extends JavaPlugin {
|
||||||
|
public static final int PORT = 443;
|
||||||
private static HttpsServer server;
|
private static HttpsServer server;
|
||||||
/**
|
/**
|
||||||
* For ACME validation and user redirection
|
* For ACME validation and user redirection
|
||||||
*/
|
*/
|
||||||
private static HttpServer httpserver;
|
private static HttpServer httpserver;
|
||||||
private static boolean enabled;
|
|
||||||
|
|
||||||
public ButtonWebsiteModule() {
|
public ButtonWebsiteModule() {
|
||||||
try {
|
try {
|
||||||
int ps = getConfig().getInt("https-port", 443);
|
server = HttpsServer.create(new InetSocketAddress((InetAddress) null, PORT), 10);
|
||||||
int p = getConfig().getInt("http-port", 80);
|
httpserver = HttpServer.create(new InetSocketAddress((InetAddress) null, 80), 10);
|
||||||
server = HttpsServer.create(new InetSocketAddress((InetAddress) null, ps), 10);
|
|
||||||
httpserver = HttpServer.create(new InetSocketAddress((InetAddress) null, p), 10);
|
|
||||||
SSLContext sslContext = SSLContext.getInstance("TLS");
|
SSLContext sslContext = SSLContext.getInstance("TLS");
|
||||||
|
|
||||||
// initialise the keystore
|
// initialise the keystore
|
||||||
char[] password = "password".toCharArray();
|
char[] password = "password".toCharArray();
|
||||||
KeyStore ks = KeyStore.getInstance("JKS");
|
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");
|
File keystoreFile = new File("keystore.keystore");
|
||||||
|
|
||||||
ks.load(keystoreFile.exists() ? new FileInputStream(keystoreFile) : null, password);
|
ks.load(keystoreFile.exists() ? new FileInputStream(keystoreFile) : null, password);
|
||||||
|
@ -59,9 +57,9 @@ public class ButtonWebsiteModule extends JavaPlugin {
|
||||||
|
|
||||||
CertificateFactory cf = CertificateFactory.getInstance("X.509");
|
CertificateFactory cf = CertificateFactory.getInstance("X.509");
|
||||||
InputStream certstream = fullStream(certfile);
|
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());
|
Security.addProvider(new BouncyCastleProvider());
|
||||||
|
|
||||||
|
@ -108,19 +106,14 @@ public class ButtonWebsiteModule extends JavaPlugin {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
enabled = true;
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
TBMCCoreAPI.SendException("An error occurred while starting the webserver!", e);
|
TBMCCoreAPI.SendException("An error occured while starting the webserver!", e);
|
||||||
enabled = false; //It's not even enabled yet, so we need a variable
|
getServer().getPluginManager().disablePlugin(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onEnable() {
|
public void onEnable() {
|
||||||
if (!enabled) {
|
|
||||||
getServer().getPluginManager().disablePlugin(this);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
addPage(new IndexPage());
|
addPage(new IndexPage());
|
||||||
addPage(new LoginPage());
|
addPage(new LoginPage());
|
||||||
addPage(new ProfilePage());
|
addPage(new ProfilePage());
|
||||||
|
@ -131,10 +124,15 @@ public class ButtonWebsiteModule extends JavaPlugin {
|
||||||
Bukkit.getScheduler().runTaskAsynchronously(this, () -> {
|
Bukkit.getScheduler().runTaskAsynchronously(this, () -> {
|
||||||
this.getLogger().info("Starting webserver...");
|
this.getLogger().info("Starting webserver...");
|
||||||
server.setExecutor(
|
server.setExecutor(
|
||||||
new ThreadPoolExecutor(4, 8, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100)));
|
new ThreadPoolExecutor(4, 8, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100)));
|
||||||
httpserver.createContext("/", exchange -> IOHelper.SendResponse(IOHelper.Redirect("https://server.figytuna.com/", exchange)));
|
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();
|
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());
|
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
|
||||||
AcmeClient.main("server.figytuna.com"); // Task is running async so we don't need an extra thread
|
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).
|
* 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) {
|
public static void addPage(Page page) {
|
||||||
if (!enabled)
|
|
||||||
return;
|
|
||||||
server.createContext("/" + page.GetName(), page);
|
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.
|
* Adds an <b>insecure</b> endpoint to the website. This should be avoided when possible.
|
||||||
*/
|
*/
|
||||||
public static void addHttpPage(Page page) {
|
public static void addHttpPage(Page page) {
|
||||||
if (!enabled)
|
|
||||||
return;
|
|
||||||
httpserver.createContext("/" + page.GetName(), page);
|
httpserver.createContext("/" + page.GetName(), page);
|
||||||
}
|
}
|
||||||
|
|
||||||
static void storeRegistration(URL location) {
|
static void storeRegistration(URI location) {
|
||||||
final ButtonWebsiteModule plugin = getPlugin(ButtonWebsiteModule.class);
|
final ButtonWebsiteModule plugin = getPlugin(ButtonWebsiteModule.class);
|
||||||
plugin.getConfig().set("registration", location.toString());
|
plugin.getConfig().set("registration", location.toString());
|
||||||
plugin.saveConfig();
|
plugin.saveConfig();
|
||||||
|
@ -189,12 +183,13 @@ public class ButtonWebsiteModule extends JavaPlugin {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static InputStream fullStream(File f) throws IOException {
|
private static InputStream fullStream(String fname) throws IOException {
|
||||||
FileInputStream fis = new FileInputStream(f);
|
FileInputStream fis = new FileInputStream(fname);
|
||||||
DataInputStream dis = new DataInputStream(fis);
|
DataInputStream dis = new DataInputStream(fis);
|
||||||
byte[] bytes = new byte[dis.available()];
|
byte[] bytes = new byte[dis.available()];
|
||||||
dis.readFully(bytes);
|
dis.readFully(bytes);
|
||||||
dis.close();
|
dis.close();
|
||||||
return new ByteArrayInputStream(bytes);
|
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
|
||||||
|
return bais;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -21,7 +21,7 @@ public class LoginCommand extends PlayerCommandBase {
|
||||||
"§6---- Login ----", //
|
"§6---- Login ----", //
|
||||||
"This command allows you to log in to our website using your Minecraft account.", //
|
"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.", //
|
"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;
|
package buttondevteam.website;
|
||||||
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
import buttondevteam.lib.player.ChromaGamerBase;
|
import buttondevteam.lib.player.ChromaGamerBase;
|
||||||
import buttondevteam.lib.player.PlayerData;
|
import buttondevteam.lib.player.PlayerData;
|
||||||
import buttondevteam.lib.player.UserClass;
|
import buttondevteam.lib.player.UserClass;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
@UserClass(foldername = "web")
|
@UserClass(foldername = "web")
|
||||||
public class WebUser extends ChromaGamerBase {
|
public class WebUser extends ChromaGamerBase {
|
||||||
private UUID uuid;
|
private UUID uuid;
|
||||||
|
@ -16,7 +16,7 @@ public class WebUser extends ChromaGamerBase {
|
||||||
return uuid;
|
return uuid;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PlayerData<UUID> sessionID() {
|
public PlayerData<String> sessionID() {
|
||||||
return data(new UUID(0, 0)); //It's used with toString() directly, so can't be null
|
return data(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,8 +33,8 @@ public class Cookies extends HashMap<String, Cookie> {
|
||||||
public void AddHeaders(HttpExchange exchange) {
|
public void AddHeaders(HttpExchange exchange) {
|
||||||
for (Entry<String, Cookie> item : entrySet())
|
for (Entry<String, Cookie> item : entrySet())
|
||||||
exchange.getResponseHeaders().add("Set-Cookie",
|
exchange.getResponseHeaders().add("Set-Cookie",
|
||||||
item.getKey() + "=" + item.getValue().getValue() + "; expires=" + expiretime + "; Secure; HttpOnly; Domain=figytuna.com"); //Allow for frontend
|
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 + "; Secure; HttpOnly; Domain=figytuna.com");
|
exchange.getResponseHeaders().add("Set-Cookie", "expiretime=" + expiretime + "; expires=" + expiretime + "; Domain=figytuna.com"); //TODO: Fix header stuff
|
||||||
}
|
}
|
||||||
|
|
||||||
public Cookies add(Cookie cookie) {
|
public Cookies add(Cookie cookie) {
|
||||||
|
|
|
@ -31,8 +31,8 @@ public class IOHelper {
|
||||||
|
|
||||||
public static void SendResponse(int code, String content, HttpExchange exchange) throws IOException {
|
public static void SendResponse(int code, String content, HttpExchange exchange) throws IOException {
|
||||||
if (exchange.getRequestMethod().equalsIgnoreCase("HEAD")) {
|
if (exchange.getRequestMethod().equalsIgnoreCase("HEAD")) {
|
||||||
exchange.sendResponseHeaders(200, -1); // -1 indicates no data
|
exchange.sendResponseHeaders(code, -1); // -1 indicates no data
|
||||||
//exchange.getResponseBody().close(); - No stream is created for HEAD requests
|
exchange.getResponseBody().close(); //TODO: Response headers not sent yet <--
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try (BufferedOutputStream out = new BufferedOutputStream(exchange.getResponseBody())) {
|
try (BufferedOutputStream out = new BufferedOutputStream(exchange.getResponseBody())) {
|
||||||
|
@ -57,7 +57,8 @@ public class IOHelper {
|
||||||
try {
|
try {
|
||||||
if (exchange.getRequestBody().available() == 0)
|
if (exchange.getRequestBody().available() == 0)
|
||||||
return "";
|
return "";
|
||||||
return IOUtils.toString(exchange.getRequestBody(), "UTF-8");
|
String content = IOUtils.toString(exchange.getRequestBody(), "UTF-8");
|
||||||
|
return content;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
return "";
|
return "";
|
||||||
|
@ -72,7 +73,8 @@ public class IOHelper {
|
||||||
JsonElement e = new JsonParser().parse(content);
|
JsonElement e = new JsonParser().parse(content);
|
||||||
if (e == null)
|
if (e == null)
|
||||||
return null;
|
return null;
|
||||||
return e.getAsJsonObject();
|
JsonObject obj = e.getAsJsonObject();
|
||||||
|
return obj;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
return null;
|
return null;
|
||||||
|
@ -84,15 +86,15 @@ public class IOHelper {
|
||||||
*/
|
*/
|
||||||
public static void LoginUser(HttpExchange exchange, WebUser user) {
|
public static void LoginUser(HttpExchange exchange, WebUser user) {
|
||||||
Bukkit.getLogger().fine("Logging in user: " + user);
|
Bukkit.getLogger().fine("Logging in user: " + user);
|
||||||
user.sessionID().set(UUID.randomUUID());
|
user.sessionID().set(UUID.randomUUID().toString());
|
||||||
user.save();
|
user.save();
|
||||||
new Cookies(2).add(new Cookie("user_id", user.getUUID() + ""))
|
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.");
|
Bukkit.getLogger().fine("Logged in user.");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void LogoutUser(HttpExchange exchange, WebUser user) {
|
public static void LogoutUser(HttpExchange exchange, WebUser user) {
|
||||||
user.sessionID().set(new UUID(0, 0));
|
user.sessionID().set(null);
|
||||||
user.save();
|
user.save();
|
||||||
SendLogoutHeaders(exchange);
|
SendLogoutHeaders(exchange);
|
||||||
}
|
}
|
||||||
|
@ -103,7 +105,7 @@ public class IOHelper {
|
||||||
.AddHeaders(exchange);
|
.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);
|
exchange.getResponseHeaders().add("Location", url);
|
||||||
return new Response(303, "<a href=\"" + url + "\">If you can see this, click here to continue</a>", exchange);
|
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();
|
return new Cookies();
|
||||||
Map<String, String> map = new HashMap<>();
|
Map<String, String> map = new HashMap<>();
|
||||||
for (String cheader : exchange.getRequestHeaders().get("Cookie")) {
|
for (String cheader : exchange.getRequestHeaders().get("Cookie")) {
|
||||||
String[] spl = cheader.split(";\\s*");
|
String[] spl = cheader.split("\\;\\s*");
|
||||||
for (String s : spl) {
|
for (String s : spl) {
|
||||||
String[] kv = s.split("=");
|
String[] kv = s.split("\\=");
|
||||||
if (kv.length < 2)
|
if (kv.length < 2)
|
||||||
continue;
|
continue;
|
||||||
map.put(kv[0], kv[1]);
|
map.put(kv[0], kv[1]);
|
||||||
|
@ -123,7 +125,7 @@ public class IOHelper {
|
||||||
}
|
}
|
||||||
if (!map.containsKey("expiretime"))
|
if (!map.containsKey("expiretime"))
|
||||||
return new Cookies();
|
return new Cookies();
|
||||||
Cookies cookies;
|
Cookies cookies = null;
|
||||||
try {
|
try {
|
||||||
cookies = new Cookies(map.get("expiretime"));
|
cookies = new Cookies(map.get("expiretime"));
|
||||||
for (Entry<String, String> item : map.entrySet())
|
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>
|
* 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.
|
* @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);
|
Cookies cookies = GetCookies(exchange);
|
||||||
if (!cookies.containsKey("user_id") || !cookies.containsKey("session_id"))
|
if (!cookies.containsKey("user_id") || !cookies.containsKey("session_id"))
|
||||||
return null;
|
return null;
|
||||||
WebUser user = ChromaGamerBase.getUser(cookies.get("user_id").getValue(), WebUser.class);
|
WebUser user = ChromaGamerBase.getUser(cookies.get("user_id").getValue(), WebUser.class);
|
||||||
if (user != null && cookies.get("session_id") != null
|
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"))))
|
if (cookies.getExpireTimeParsed().minusYears(1).isBefore(ZonedDateTime.now(ZoneId.of("GMT"))))
|
||||||
LoginUser(exchange, user);
|
LoginUser(exchange, user);
|
||||||
return user;
|
return user;
|
||||||
|
@ -187,10 +190,10 @@ public class IOHelper {
|
||||||
|
|
||||||
public static HashMap<String, String> GetPOSTKeyValues(HttpExchange exchange) {
|
public static HashMap<String, String> GetPOSTKeyValues(HttpExchange exchange) {
|
||||||
try {
|
try {
|
||||||
String[] content = GetPOST(exchange).split("&");
|
String[] content = GetPOST(exchange).split("\\&");
|
||||||
HashMap<String, String> vars = new HashMap<>();
|
HashMap<String, String> vars = new HashMap<>();
|
||||||
for (String var : content) {
|
for (String var : content) {
|
||||||
String[] spl = var.split("=");
|
String[] spl = var.split("\\=");
|
||||||
if (spl.length == 1)
|
if (spl.length == 1)
|
||||||
vars.put(spl[0], "");
|
vars.put(spl[0], "");
|
||||||
else
|
else
|
||||||
|
|
|
@ -3,9 +3,9 @@ package buttondevteam.website.io;
|
||||||
import com.sun.net.httpserver.HttpExchange;
|
import com.sun.net.httpserver.HttpExchange;
|
||||||
|
|
||||||
public class Response {
|
public class Response {
|
||||||
public final int code;
|
public int code;
|
||||||
public final String content;
|
public String content;
|
||||||
public final HttpExchange exchange;
|
public HttpExchange exchange;
|
||||||
|
|
||||||
public Response(int code, String content, HttpExchange exchange) {
|
public Response(int code, String content, HttpExchange exchange) {
|
||||||
this.code = code;
|
this.code = code;
|
||||||
|
|
|
@ -1,9 +1,5 @@
|
||||||
package buttondevteam.website.page;
|
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.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
|
@ -12,8 +8,15 @@ import java.net.SocketException;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
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 {
|
public class BridgePage extends Page {
|
||||||
private final Map<String, Socket> connections = new HashMap<>();
|
private Map<String, Socket> connections = new HashMap<>();
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String GetName() {
|
public String GetName() {
|
||||||
|
@ -53,14 +56,9 @@ public class BridgePage extends Page {
|
||||||
return new Response(400, "No connection", exchange);
|
return new Response(400, "No connection", exchange);
|
||||||
if (s.isClosed())
|
if (s.isClosed())
|
||||||
return new Response(410, "Socket Gone", exchange);
|
return new Response(410, "Socket Gone", exchange);
|
||||||
try {
|
exchange.sendResponseHeaders(200, 0); // Chunked transfer, any amount of data
|
||||||
exchange.sendResponseHeaders(200, 0); // Chunked transfer, any amount of data
|
copyStream(s.getInputStream(), exchange.getResponseBody());
|
||||||
copyStream(s.getInputStream(), exchange.getResponseBody());
|
exchange.getResponseBody().close(); // It'll only get here when the communication is already done
|
||||||
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());
|
|
||||||
}
|
|
||||||
return null; // Response already sent
|
return null; // Response already sent
|
||||||
case "DELETE":
|
case "DELETE":
|
||||||
System.out.println("[BWM] [" + id + "] delet this");
|
System.out.println("[BWM] [" + id + "] delet this");
|
||||||
|
@ -70,13 +68,7 @@ public class BridgePage extends Page {
|
||||||
return new Response(403, "Unknown request", exchange);
|
return new Response(403, "Unknown request", exchange);
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
if (e instanceof SocketException) {
|
throw new RuntimeException(e);
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -103,22 +95,26 @@ public class BridgePage extends Page {
|
||||||
return;
|
return;
|
||||||
try {
|
try {
|
||||||
socket.close();
|
socket.close();
|
||||||
} catch (IOException ignored) {
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
connections.values().remove(socket);
|
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];
|
byte[] buffer = new byte[4096];
|
||||||
int n;
|
long count = 0;
|
||||||
|
int n = 0;
|
||||||
try {
|
try {
|
||||||
while (-1 != (n = is.read(buffer))) { // Read is blocking
|
while (-1 != (n = is.read(buffer))) { // Read is blocking
|
||||||
os.write(buffer, 0, n);
|
os.write(buffer, 0, n);
|
||||||
|
count += n;
|
||||||
os.flush();
|
os.flush();
|
||||||
}
|
}
|
||||||
} catch (SocketException e) { // Conection closed
|
} catch (SocketException e) { // Conection closed
|
||||||
os.flush();
|
os.flush();
|
||||||
}
|
}
|
||||||
|
return (int) count;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|
|
@ -1,16 +1,5 @@
|
||||||
package buttondevteam.website.page;
|
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.nio.charset.StandardCharsets;
|
||||||
import java.security.KeyFactory;
|
import java.security.KeyFactory;
|
||||||
import java.security.PublicKey;
|
import java.security.PublicKey;
|
||||||
|
@ -21,6 +10,16 @@ import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.function.Supplier;
|
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 {
|
public class BuildNotificationsPage extends Page {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -32,11 +31,8 @@ public class BuildNotificationsPage extends Page {
|
||||||
|
|
||||||
private static final String publickey = ((Supplier<String>) () -> {
|
private static final String publickey = ((Supplier<String>) () -> {
|
||||||
try {
|
try {
|
||||||
JsonElement pubkey = fromString(TBMCCoreAPI.DownloadString("https://api.travis-ci.org/config"),
|
return fromString(TBMCCoreAPI.DownloadString("https://api.travis-ci.org/config"),
|
||||||
"config.notifications.webhook.public_key");
|
"config.notifications.webhook.public_key").getAsString().replace("-----BEGIN PUBLIC KEY-----", "")
|
||||||
if (pubkey == null)
|
|
||||||
return null;
|
|
||||||
return pubkey.getAsString().replace("-----BEGIN PUBLIC KEY-----", "")
|
|
||||||
.replaceAll("\n", "").replace("-----END PUBLIC KEY-----", "");
|
.replaceAll("\n", "").replace("-----END PUBLIC KEY-----", "");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
|
@ -51,7 +47,7 @@ public class BuildNotificationsPage extends Page {
|
||||||
final String payload = post.get("payload");
|
final String payload = post.get("payload");
|
||||||
if (signatures != null && signatures.size() > 0 && post.containsKey("payload")
|
if (signatures != null && signatures.size() > 0 && post.containsKey("payload")
|
||||||
&& verifySignature(payload.getBytes(StandardCharsets.UTF_8),
|
&& verifySignature(payload.getBytes(StandardCharsets.UTF_8),
|
||||||
Base64.getDecoder().decode(signatures.get(0)))) {
|
Base64.getDecoder().decode(signatures.get(0)), publickey)) {
|
||||||
Bukkit.getPluginManager()
|
Bukkit.getPluginManager()
|
||||||
.callEvent(new PluginUpdater.UpdatedEvent(gson.fromJson(payload, JsonObject.class)));
|
.callEvent(new PluginUpdater.UpdatedEvent(gson.fromJson(payload, JsonObject.class)));
|
||||||
return new Response(200, "All right", exchange);
|
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,
|
// Method for signature verification that initializes with the Public Key,
|
||||||
// updates the data to be verified and then verifies them using the signature
|
// 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");
|
Signature sig = Signature.getInstance("SHA1withRSA");
|
||||||
sig.initVerify(getPublic(BuildNotificationsPage.publickey));
|
sig.initVerify(getPublic(keystr));
|
||||||
sig.update(data);
|
sig.update(data);
|
||||||
|
|
||||||
return sig.verify(signature);
|
return sig.verify(signature);
|
||||||
|
|
|
@ -7,6 +7,7 @@ import buttondevteam.website.io.Response;
|
||||||
import com.google.common.collect.HashBiMap;
|
import com.google.common.collect.HashBiMap;
|
||||||
import com.sun.net.httpserver.HttpExchange;
|
import com.sun.net.httpserver.HttpExchange;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.UUID;
|
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
|
cp.connectWith(wu = WebUser.getUser(UUID.randomUUID().toString(), WebUser.class)); //Create new user with random UUID
|
||||||
IOHelper.LoginUser(exchange, wu);
|
IOHelper.LoginUser(exchange, wu);
|
||||||
states.remove(state);
|
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
|
} else return new Response(418, "Now what", exchange); //Minecraft doesn't have full OAuth
|
||||||
}
|
}
|
||||||
return new Response(400, "Wut", exchange);
|
return new Response(400, "Wut", exchange);
|
||||||
|
|
|
@ -1,16 +1,16 @@
|
||||||
package buttondevteam.website.page;
|
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.lib.TBMCCoreAPI;
|
||||||
import buttondevteam.website.io.IOHelper;
|
import buttondevteam.website.io.IOHelper;
|
||||||
import buttondevteam.website.io.Response;
|
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 class Page implements HttpHandler {
|
||||||
public abstract String GetName();
|
public abstract String GetName();
|
||||||
|
@ -18,8 +18,8 @@ public abstract class Page implements HttpHandler {
|
||||||
@Override
|
@Override
|
||||||
public final void handle(HttpExchange exchange) {
|
public final void handle(HttpExchange exchange) {
|
||||||
try {
|
try {
|
||||||
exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "https://chromagaming.figytuna.com");
|
exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "https://tbmcplugins.github.io");
|
||||||
if (!exactPage() || exchange.getRequestURI().getPath().equals("/" + GetName()))
|
if (exactPage() ? exchange.getRequestURI().getPath().equals("/" + GetName()) : true)
|
||||||
IOHelper.SendResponse(handlePage(exchange));
|
IOHelper.SendResponse(handlePage(exchange));
|
||||||
else {
|
else {
|
||||||
IOHelper.SendResponse(404, "404 Not found: " + exchange.getRequestURI().getPath(), exchange);
|
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
|
* 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() {
|
public boolean exactPage() {
|
||||||
return true;
|
return true;
|
||||||
|
|
Loading…
Reference in a new issue