12 Commits
1.0.2 ... 1.0.3

Author SHA1 Message Date
803b763198 Update README.md 2023-06-08 03:05:10 -04:00
fec32230fe Add license actions 2023-06-02 05:50:27 -04:00
68591c90c9 Add a command to view your owned license 2023-06-02 05:10:41 -04:00
5133ab688f Version bump 2023-06-02 05:07:13 -04:00
36673af4d0 Only inform license owners of new IPs and HWIDs if the license was actually used 2023-06-02 00:49:41 -04:00
3038e14b81 Update README 2023-06-02 00:44:10 -04:00
2920a42d76 Update README 2023-06-02 00:42:51 -04:00
c350138caa Simple HWID validation 2023-06-02 00:39:19 -04:00
cf932e2d90 oops, forgot this 2023-06-02 00:35:55 -04:00
6b6958640f Cleanup 2023-06-02 00:32:42 -04:00
e3b6507a6c Document DiscordService#sendOwnerLog 2023-06-02 00:32:27 -04:00
1b482b93e2 Update example 2023-06-02 00:29:45 -04:00
7 changed files with 257 additions and 38 deletions

View File

@ -5,7 +5,7 @@ package me.braydon.example;
*/
public final class Main {
public static void main(String[] args) {
LicenseExample.LicenseResponse response = LicenseExample.check("C45E-40F6-924C-753B", "CloudSpigot");
LicenseExample.LicenseResponse response = LicenseExample.check("XXXX-XXXX-XXXX-XXXX", "Example");
if (!response.isValid()) { // License isn't valid
System.err.println("Invalid license: " + response.getError());
return;

View File

@ -4,7 +4,9 @@ A simple open-source licensing server for your products.
## Discord Preview
![License Usage Log](https://cdn.rainnny.club/SagsCD0I.png)
![License Global Log](https://cdn.rainnny.club/SagsCD0I.png)
![License Owner Log](https://cdn.rainnny.club/JZdFxTCy.png)
![License Owner Lookup](https://cdn.rainnny.club/EU0g1iLZ.png)
## API Reference
@ -39,7 +41,7 @@ POST /check
"description": "Testing",
"ownerSnowflake": 504147739131641857,
"ownerName": "Braydon#2712",
"duration": -1
"expires": "2023-06-02T06:00:47.270+00:00"
}
```

10
pom.xml
View File

@ -12,7 +12,7 @@
<groupId>me.braydon</groupId>
<artifactId>LicenseServer</artifactId>
<version>1.0.2</version>
<version>1.0.3</version>
<description>A simple open-source licensing server for your products.</description>
<properties>
@ -92,6 +92,14 @@
<scope>compile</scope>
</dependency>
<!-- Guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>32.0.0-jre</version>
<scope>compile</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>

View File

@ -61,13 +61,26 @@ public final class LicenseController {
if (IPUtils.getIpType(ip) == -1) {
throw new APIException(HttpStatus.BAD_REQUEST, "Invalid IP address");
}
// Ensure the HWID is valid
// TODO: improve :)
String hwidString = hwid.getAsString();
boolean invalidHwid = true;
if (hwidString.contains("-")) {
int segments = hwidString.substring(0, hwidString.lastIndexOf("-")).split("-").length;
if (segments == 4) {
invalidHwid = false;
}
}
if (invalidHwid) {
throw new APIException(HttpStatus.BAD_REQUEST, "Invalid HWID");
}
// Check the license
License license = service.check(
key.getAsString(),
product.getAsString(),
ip,
hwid.getAsString()
hwidString
);
// Return OK with the license DTO
return ResponseEntity.ok(new LicenseDTO(

View File

@ -94,6 +94,18 @@ public class License {
*/
@NonNull private Date created;
/**
* Check if the Discord user
* with the given snowflake
* owns this license.
*
* @param snowflake the snowflake
* @return true if owns, otherwise false
*/
public boolean isOwner(long snowflake) {
return ownerSnowflake == snowflake;
}
/**
* Check if this license has expired.
* <p>

View File

@ -1,37 +1,72 @@
package me.braydon.license.service;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import jakarta.annotation.Nonnull;
import jakarta.annotation.PostConstruct;
import lombok.Getter;
import lombok.NonNull;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.braydon.license.common.MiscUtils;
import me.braydon.license.common.TimeUtils;
import me.braydon.license.model.License;
import me.braydon.license.repository.LicenseRepository;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.entities.emoji.Emoji;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
import net.dv8tion.jda.api.exceptions.ErrorResponseException;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.Commands;
import net.dv8tion.jda.api.interactions.components.buttons.Button;
import net.dv8tion.jda.api.requests.ErrorResponse;
import net.dv8tion.jda.api.requests.GatewayIntent;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.info.BuildProperties;
import org.springframework.stereotype.Service;
import java.awt.*;
import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
/**
* @author Braydon
*/
@Service
@Slf4j(topic = "Discord")
public final class DiscordService {
private static final String CLEAR_IPS_BUTTON_ID = "clearIps";
private static final String CLEAR_HWIDS_BUTTON_ID = "clearHwids";
/**
* The {@link LicenseRepository} to use.
*/
@Nonnull private final LicenseRepository licenseRepository;
/**
* The version of this Springboot application.
*/
@NonNull private final String applicationVersion;
/**
* The salt to use for hashing license keys.
*/
@Value("${salts.licenses}")
@NonNull private String licensesSalt;
/**
* The name of this Springboot application.
*/
@ -86,19 +121,27 @@ public final class DiscordService {
@Value("${discord.owner-logs.newHwid}") @Getter
private boolean logNewHwidsToOwner;
/**
* Should the license owner be notified when their license is about to expire?
*/
@Value("${discord.owner-logs.expiringSoon}") @Getter
private boolean logExpiringSoonToOwner;
/**
* The {@link JDA} instance of the bot.
*/
private JDA jda;
/**
* Cached licenses for messages.
* <p>
* When a license is looked up by it's owner, the
* response message is cached (key is the message snowflake)
* for 5 minutes. This is so we're able to get the message
* an action was performed on, as well as action timeouts.
* </p>
*/
private final Cache<Long, License> cachedLicenses = CacheBuilder.newBuilder()
.expireAfterWrite(5L, TimeUnit.MINUTES)
.build();
@Autowired
public DiscordService(@NonNull BuildProperties buildProperties) {
public DiscordService(@NonNull LicenseRepository licenseRepository, @NonNull BuildProperties buildProperties) {
this.licenseRepository = licenseRepository;
this.applicationVersion = buildProperties.getVersion();
}
@ -117,6 +160,7 @@ public final class DiscordService {
GatewayIntent.GUILD_MEMBERS
).setStatus(OnlineStatus.DO_NOT_DISTURB)
.setActivity(Activity.watching("your licenses"))
.addEventListeners(new EventHandler())
.build();
jda.awaitReady(); // Await JDA to be ready
@ -124,6 +168,13 @@ public final class DiscordService {
log.info("Logged into {} in {}ms",
jda.getSelfUser().getAsTag(), System.currentTimeMillis() - before
);
// Registering slash commands
jda.updateCommands().addCommands(
Commands.slash("license", "Manage one of your licenses")
.addOption(OptionType.STRING, "key", "The license key", true)
.addOption(OptionType.STRING, "product", "The product the license is for", true)
).queue();
}
/**
@ -151,7 +202,20 @@ public final class DiscordService {
textChannel.sendMessageEmbeds(buildEmbed(embed)).queue();
}
/**
* Send an embed to the owner
* of the given license.
*
* @param license the license
* @param embed the embed to send
* @see License for license
* @see EmbedBuilder for embed
*/
public void sendOwnerLog(@NonNull License license, @NonNull EmbedBuilder embed) {
// JDA must be ready to send logs
if (!isReady()) {
return;
}
// We need an owner for the license
if (license.getOwnerSnowflake() <= 0L) {
return;
@ -198,4 +262,123 @@ public final class DiscordService {
applicationName, applicationVersion, TimeUtils.dateTime()
)).build();
}
/**
* The event handler for the bot.
*/
public class EventHandler extends ListenerAdapter {
@Override
public void onSlashCommandInteraction(@NonNull SlashCommandInteractionEvent event) {
User user = event.getUser(); // The command executor
// Handle the license command
if (event.getName().equals("license")) {
String key = Objects.requireNonNull(event.getOption("key")).getAsString();
String product = Objects.requireNonNull(event.getOption("product")).getAsString();
event.deferReply(true).queue(); // Send thinking...
// License lookup
try {
Optional<License> optionalLicense = licenseRepository.getLicense(BCrypt.hashpw(key, licensesSalt), product);
if (optionalLicense.isEmpty() // License not found or owned by someone else
|| (!optionalLicense.get().isOwner(user.getIdLong()))) {
event.getHook().sendMessageEmbeds(buildEmbed(new EmbedBuilder()
.setColor(Color.RED)
.setTitle("License not found")
.setDescription("Could not locate the license you were looking for")
)).queue(); // Send the error message
return;
}
License license = optionalLicense.get(); // The found license
String obfuscateKey = MiscUtils.obfuscateKey(key); // Obfuscate the key
long expires = license.isPermanent() ? -1L : license.getExpires().getTime() / 1000L;
long lastUsed = license.getLastUsed() == null ? -1L : license.getExpires().getTime() / 1000L;
event.getHook().sendMessageEmbeds(buildEmbed(new EmbedBuilder()
.setColor(Color.BLUE)
.setTitle("Your License")
.addField("License", "`" + obfuscateKey + "`", true)
.addField("Product", license.getProduct(), true)
.addField("Description", license.getDescription(), true)
.addField("Expiration",
expires == -1L ? "Never" : "<t:" + expires + ":R>",
true
)
.addField("Uses", String.valueOf(license.getUses()), true)
.addField("Last Used",
lastUsed == -1L ? "Never" : "<t:" + lastUsed + ":R>",
true
)
.addField("IPs",
license.getIps().size() + "/" + license.getIpLimit(),
true
)
.addField("HWIDs",
license.getHwids().size() + "/" + license.getHwidLimit(),
true
)
.addField("Created",
"<t:" + (license.getCreated().getTime() / 1000L) + ":R>",
true
)
)).addActionRow( // Buttons
Button.danger(CLEAR_IPS_BUTTON_ID, "Clear IPs")
.withEmoji(Emoji.fromUnicode("🗑️")),
Button.danger(CLEAR_HWIDS_BUTTON_ID, "Clear HWIDs")
.withEmoji(Emoji.fromUnicode("🗑️"))
).queue(message -> cachedLicenses.put(message.getIdLong(), license)); // Cache the license for the message
} catch (Exception ex) {
event.getHook().sendMessageEmbeds(buildEmbed(new EmbedBuilder()
.setColor(Color.RED)
.setTitle("Lookup Failed")
.setDescription("More information has been logged")
)).queue(); // Send the error message
ex.printStackTrace();
}
}
}
@Override
public void onButtonInteraction(@NonNull ButtonInteractionEvent event) {
User user = event.getUser(); // The user who clicked the button
String componentId = event.getComponentId(); // The button id
// License Actions
boolean clearIps = componentId.equals(CLEAR_IPS_BUTTON_ID);
boolean clearHwids = componentId.equals(CLEAR_HWIDS_BUTTON_ID);
if (clearIps || clearHwids) {
event.deferReply(true).queue(); // Send thinking...
License license = cachedLicenses.getIfPresent(event.getMessageIdLong()); // Get the cached license
if (license == null || (!license.isOwner(user.getIdLong()))) { // License not found or owned by someone else
event.getHook().sendMessageEmbeds(buildEmbed(new EmbedBuilder()
.setColor(Color.RED)
.setTitle("License Action Failed")
.setDescription("The license couldn't be found or the action timed out")
)).queue(); // Send the error message
return;
}
try {
// Clear IPs
if (clearIps) {
license.setIps(new HashSet<>());
}
// Clear HWIDs
if (clearHwids) {
license.setHwids(new HashSet<>());
}
licenseRepository.save(license); // Save the license
event.getHook().sendMessageEmbeds(buildEmbed(new EmbedBuilder()
.setColor(Color.GREEN)
.setTitle("Cleared " + (clearIps ? "IP" : "HWID") + "s")
)).queue(); // Inform action success
} catch (Exception ex) {
event.getHook().sendMessageEmbeds(buildEmbed(new EmbedBuilder()
.setColor(Color.RED)
.setTitle("License Action Failed")
.setDescription("More information has been logged")
)).queue(); // Send the error message
ex.printStackTrace();
}
}
}
}
}

View File

@ -143,7 +143,7 @@ public final class LicenseService {
license.getOwnerName() == null ? "N/A" : license.getOwnerName(),
true
)
.addField("Expires",
.addField("Expiration",
expires == -1L ? "Never" : "<t:" + expires + ":R>",
true
)
@ -171,33 +171,34 @@ public final class LicenseService {
}
throw new LicenseExpiredException();
}
// Sending new IP log to the license owner
if (newIp && discordService.isLogNewIpsToOwner()) {
discordService.sendOwnerLog(license, new EmbedBuilder()
.setColor(0xF2781B)
.setTitle("New IP")
.setDescription("One of your licenses has been used on a new IP:")
.addField("License", "`" + obfuscateKey + "`", true)
.addField("Product", license.getProduct(), true)
.addField("IP", "```" + ip + "```", false)
);
}
// Sending new HWID log to the license owner
if (newHwid && discordService.isLogNewHwidsToOwner()) {
discordService.sendOwnerLog(license, new EmbedBuilder()
.setColor(0xF2781B)
.setTitle("New HWID")
.setDescription("One of your licenses has been used on a new HWID:")
.addField("License", "`" + obfuscateKey + "`", true)
.addField("Product", license.getProduct(), true)
.addField("HWID", "```" + hwid + "```", false)
);
}
// Use the license
try {
license.use(hashedIp, hwid);
license.use(hashedIp, hwid); // Use the license
repository.save(license); // Save the used license
// Sending new IP log to the license owner
if (newIp && discordService.isLogNewIpsToOwner()) {
discordService.sendOwnerLog(license, new EmbedBuilder()
.setColor(0xF2781B)
.setTitle("New IP")
.setDescription("One of your licenses has been used on a new IP:")
.addField("License", "`" + obfuscateKey + "`", true)
.addField("Product", license.getProduct(), true)
.addField("IP", "```" + ip + "```", false)
);
}
// Sending new HWID log to the license owner
if (newHwid && discordService.isLogNewHwidsToOwner()) {
discordService.sendOwnerLog(license, new EmbedBuilder()
.setColor(0xF2781B)
.setTitle("New HWID")
.setDescription("One of your licenses has been used on a new HWID:")
.addField("License", "`" + obfuscateKey + "`", true)
.addField("Product", license.getProduct(), true)
.addField("HWID", "```" + hwid + "```", false)
);
}
// Logging the license use
log.info("License key '{}' for product '{}' was used by {} (HWID: {})", key, product, ip, hwid);
return license;
} catch (APIException ex) {